refactor: code cleanup for next edit (#7312)

* feat: don't format when model is not mercury

* chore: bump

* fix: remove mercury-coder-nextedit

* refactor: remove refs to mercury-coder-nextedit

* feat: add util function for converting model name to enum

* refactor: add new types

* refactor: create an abstract base class for providers

* refactor: add child provider for instinct

* refactor: add provider for mercury coder

* refactor: provider factory

* refactor: use factory to create model providers based on helper.modelName

* refactor: clean up redundant logic to be more provider-friendly

* add buildPromptMetadata as an abstract method

* refactor: use handlebars and provider-specific template renderers

* refactor: use this.modelProvider instead of prompt engine

* refactor: remove redundant helper

* fix: update vitest after refactor

* feat: add test for convertNextEditModelNameToEnum

* fix: add isSecurityConcern imports
This commit is contained in:
Jacob Kim 2025-08-22 14:44:37 -07:00 • committed by GitHub
parent 657ee9f8cd
commit c2231a9366
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 1066 additions and 1089 deletions

View file

@ -178,7 +178,6 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
NEXT_EDIT_MODELS.MERCURY_CODER,
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
NEXT_EDIT_MODELS.INSTINCT,
];

View file

@ -220,7 +220,7 @@ describe("modelSupportsNextEdit", () => {
expect(
modelSupportsNextEdit(
{ nextEdit: false },
"mercury-coder-nextedit",
"mercury-coder",
"Mercury Coder",
),
).toBe(false);
@ -231,7 +231,7 @@ describe("modelSupportsNextEdit", () => {
expect(
modelSupportsNextEdit(
{ nextEdit: false },
"mercury-coder-nextedit",
"mercury-coder",
"Mercury Coder",
),
).toBe(false);
@ -239,10 +239,10 @@ describe("modelSupportsNextEdit", () => {
});
describe("when capabilities.nextEdit is undefined", () => {
it("should return true for mercury-coder-nextedit model (case insensitive)", () => {
expect(
modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined),
).toBe(true);
it("should return true for mercury-coder model (case insensitive)", () => {
expect(modelSupportsNextEdit(undefined, "Mercury-Coder", undefined)).toBe(
true,
);
});
it("should return true for instinct", () => {
@ -255,7 +255,7 @@ describe("modelSupportsNextEdit", () => {
expect(
modelSupportsNextEdit(
undefined,
"provider/mercury-coder-nextedit-v2",
"provider/mercury-coder-v2",
undefined,
),
).toBe(true);
@ -266,7 +266,7 @@ describe("modelSupportsNextEdit", () => {
modelSupportsNextEdit(
undefined,
"some-model",
"This is mercury-coder-nextedit model",
"This is mercury-coder model",
),
).toBe(true);
});
@ -312,14 +312,14 @@ describe("modelSupportsNextEdit", () => {
});
it("should handle undefined title gracefully", () => {
expect(
modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined),
).toBe(true);
expect(modelSupportsNextEdit(undefined, "mercury-coder", undefined)).toBe(
true,
);
});
it("should handle case sensitivity correctly", () => {
expect(
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
modelSupportsNextEdit(undefined, "MERCURY-CODER", "instinct"),
).toBe(true);
});

View file

@ -21,7 +21,6 @@ export enum LLMConfigurationStatuses {
export enum NEXT_EDIT_MODELS {
MERCURY_CODER = "mercury-coder",
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
INSTINCT = "instinct",
}

View file

@ -1,15 +1,6 @@
import * as path from "path";
import { v4 as uuidv4 } from "uuid";
import { ConfigHandler } from "../config/ConfigHandler.js";
import {
ChatMessage,
DiffLine,
IDE,
ILLM,
Position,
Range,
RangeInFile,
} from "../index.js";
import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
@ -18,10 +9,7 @@ import { ContextRetrievalService } from "../autocomplete/context/ContextRetrieva
import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
import {
getAllSnippetsWithoutRace,
SnippetPayload,
} from "../autocomplete/snippets/index.js";
import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
import { getAst } from "../autocomplete/util/ast.js";
@ -29,39 +17,23 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce
import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { AutocompleteInput } from "../autocomplete/util/types.js";
import { myersDiff } from "../diff/myers.js";
import { isSecurityConcern } from "../indexing/ignore.js";
import { modelSupportsNextEdit } from "../llm/autodetect.js";
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import {
INSTINCT_SYSTEM_PROMPT,
MERCURY_SYSTEM_PROMPT,
MODEL_WINDOW_SIZES,
UNIQUE_TOKEN,
} from "./constants.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import {
calculateFinalCursorPosition,
DiffGroup,
groupDiffLines,
} from "./diff/diff.js";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
import { NextEditLoggingService } from "./NextEditLoggingService.js";
import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
import {
renderDefaultSystemPrompt,
renderDefaultUserPrompt,
renderPrompt,
} from "./templating/NextEditPromptEngine.js";
import {
ModelSpecificContext,
NextEditOutcome,
Prompt,
PromptMetadata,
RecentlyEditedRange,
} from "./types.js";
import { isWhitespaceOnlyDeletion } from "./utils.js";
const autocompleteCache = AutocompleteLruCache.get();
@ -92,6 +64,9 @@ export class NextEditProvider {
private previousCompletions: NextEditOutcome[] = [];
// private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
// Model-specific provider instance.
private modelProvider: BaseNextEditProvider | null = null;
private constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
@ -298,28 +273,23 @@ export class NextEditProvider {
} = await this._initializeCompletionRequest(input, token);
if (!helper) return undefined;
// Create model-specific provider based on the model name.
this.modelProvider = NextEditProviderFactory.createProvider(
helper.modelName,
);
const { editableRegionStartLine, editableRegionEndLine, prompts } =
await this._generatePrompts(helper, opts);
if (this.endpointType === "default") {
return await this._handleDefaultEndpointCompletion(
helper,
prompts,
abortToken,
startTime,
editableRegionEndLine,
);
} else {
return await this._handleFineTunedEndpointCompletion(
helper,
prompts,
abortToken,
startTime,
editableRegionStartLine,
editableRegionEndLine,
opts,
);
}
return await this._handleCompletion(
helper,
prompts,
abortToken,
startTime,
editableRegionStartLine,
editableRegionEndLine,
opts,
);
} catch (e: any) {
this.onError(e);
} finally {
@ -335,7 +305,7 @@ export class NextEditProvider {
startTime: number;
helper: HelperVars | undefined;
}> {
// Create abort signal if not given.
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
@ -345,7 +315,7 @@ export class NextEditProvider {
const startTime = Date.now();
const options = await this._getAutocompleteOptions();
// Debounce.
// Debounce
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
return { token, startTime, helper: undefined };
}
@ -355,9 +325,7 @@ export class NextEditProvider {
return { token, startTime, helper: undefined };
}
// In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts.
// For other editors, this check should be done in their respective config reloaders.
// This is left for a final check.
// Check model capabilities
if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
console.error(`${llm.model} is not capable of next edit.`);
return { token, startTime, helper: undefined };
@ -387,6 +355,10 @@ export class NextEditProvider {
editableRegionEndLine: number;
prompts: Prompt[];
}> {
if (!this.modelProvider) {
throw new Error("Model provider not initialized");
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippetsWithoutRace({
helper,
@ -397,56 +369,118 @@ export class NextEditProvider {
this.ide.getWorkspaceDirs(),
]);
const modelName = helper.modelName.includes(
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
)
? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT
: helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)
? NEXT_EDIT_MODELS.MERCURY_CODER
: NEXT_EDIT_MODELS.INSTINCT;
// Calculate editable region based on model and options.
const { editableRegionStartLine, editableRegionEndLine } =
opts?.usingFullFileDiff
? this._calculateOptimalEditableRegion(helper, "tokenizer")
: {
editableRegionStartLine: Math.max(
helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
0,
),
editableRegionEndLine: Math.min(
helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
helper.fileLines.length - 1,
),
};
this.modelProvider.calculateEditableRegion(
helper,
opts?.usingFullFileDiff ?? false,
);
// const editableRegionStartLine = opts?.usingFullFileDiff
// ? 0
// : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0);
// Build context for model-specific prompt generation.
const context: ModelSpecificContext = {
helper,
snippetPayload,
editableRegionStartLine,
editableRegionEndLine,
diffContext: this.diffContext,
autocompleteContext: this.autocompleteContext,
historyDiff: createDiff({
beforeContent:
DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
localPathOrUriToPath(helper.filepath),
) ?? "",
afterContent: helper.fileContents,
filePath: helper.filepath,
diffType: DiffFormatType.Unified,
contextLines: 3,
}),
};
// const editableRegionEndLine = opts?.usingFullFileDiff
// ? helper.fileLines.length - 1
// : Math.min(
// helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
// helper.fileLines.length - 1,
// );
const prompts = await this.modelProvider.generatePrompts(context);
const prompts: Prompt[] = [];
this.promptMetadata = this.modelProvider.buildPromptMetadata(context);
if (this.endpointType === "default") {
prompts.push(renderDefaultSystemPrompt());
prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
return { editableRegionStartLine, editableRegionEndLine, prompts };
}
private async _handleCompletion(
helper: HelperVars,
prompts: Prompt[],
token: AbortSignal,
startTime: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
opts?: {
withChain: boolean;
usingFullFileDiff: boolean;
},
): Promise<NextEditOutcome | undefined> {
if (!this.modelProvider) {
throw new Error("Model provider not initialized");
}
const llm = await this._prepareLlm();
if (!llm) return undefined;
// Inject unique token if needed (for Mercury models).
if (this.modelProvider.shouldInjectUniqueToken()) {
const uniqueToken = this.modelProvider.getUniqueToken();
if (uniqueToken) {
const lastPrompt = prompts[prompts.length - 1];
if (lastPrompt && typeof lastPrompt.content === "string") {
lastPrompt.content += uniqueToken;
}
}
}
// Send prompts to LLM (using only user prompt for fine-tuned models).
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
stream: false,
});
if (typeof msg.content !== "string") {
return undefined;
}
// Extract completion using model-specific logic.
const nextCompletion = this.modelProvider.extractCompletion(msg.content);
let outcome: NextEditOutcome | undefined;
// Handle based on diff type.
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
outcome = await this.modelProvider.handlePartialFileDiff(
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
this.promptMetadata!,
this.ide,
);
} else {
prompts.push(
...(await this._generateFineTunedPrompts(
helper,
snippetPayload,
editableRegionStartLine,
editableRegionEndLine,
)),
outcome = await this.modelProvider.handleFullFileDiff(
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
this.promptMetadata!,
this.ide,
);
}
return { editableRegionStartLine, editableRegionEndLine, prompts };
if (outcome) {
// Handle NextEditProvider-specific state
this.previousCompletions.push(outcome);
// Mark as displayed for JetBrains
await this._markDisplayedIfJetBrains(helper.input.completionId, outcome);
}
return outcome;
}
private _calculateOptimalEditableRegion(
@ -540,500 +574,6 @@ export class NextEditProvider {
};
}
private async _generateFineTunedPrompts(
helper: HelperVars,
snippetPayload: SnippetPayload,
editableRegionStartLine: number,
editableRegionEndLine: number,
): Promise<Prompt[]> {
const historyDiff = createDiff({
beforeContent:
DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
localPathOrUriToPath(helper.filepath),
) ?? "",
afterContent: helper.fileContents,
filePath: helper.filepath,
diffType: DiffFormatType.Unified,
contextLines: 3,
});
const modelName = helper.modelName;
let ctx: any;
if (
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
) {
ctx = {
recentlyViewedCodeSnippets:
snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
filepath: snip.filepath,
content: snip.content,
})) ?? [],
currentFileContent: helper.fileContents,
editableRegionStartLine,
editableRegionEndLine,
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
};
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
// Calculate the window around the cursor position (25 lines above and below).
const windowStart = Math.max(0, helper.pos.line - 25);
const windowEnd = Math.min(
helper.fileLines.length - 1,
helper.pos.line + 25,
);
// // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
// const actualEditableStart = Math.max(
// 0,
// helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin,
// );
// const actualEditableEnd = Math.min(
// helper.fileLines.length - 1,
// helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin,
// );
// Ensure editable region boundaries are within the window.
const adjustedEditableStart = Math.max(
windowStart,
editableRegionStartLine,
);
const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
ctx = {
contextSnippets: this.autocompleteContext,
currentFileContent: helper.fileContents,
windowStart,
windowEnd,
editableRegionStartLine: adjustedEditableStart,
editableRegionEndLine: adjustedEditableEnd,
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
languageShorthand: helper.lang.name,
};
} else {
ctx = {};
}
const promptMetadata = await renderPrompt(helper, ctx);
this.promptMetadata = promptMetadata;
const systemPrompt: Prompt = {
role: "system",
content:
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
? MERCURY_SYSTEM_PROMPT
: INSTINCT_SYSTEM_PROMPT,
};
return [systemPrompt, promptMetadata.prompt];
}
private async _handleDefaultEndpointCompletion(
helper: HelperVars,
prompts: Prompt[],
token: AbortSignal,
startTime: number,
editableRegionEndLine: number,
): Promise<NextEditOutcome | undefined> {
const llm = await this._prepareLlm();
if (!llm) return undefined;
const msg: ChatMessage = await llm.chat(prompts, token);
if (typeof msg.content === "string") {
const nextCompletion = JSON.parse(msg.content).newCode;
const finalCursorPos: Position = {
line: editableRegionEndLine,
character: 0,
};
const outcomeNext = await this._createNextEditOutcome({
helper,
startTime,
llm,
promptContent: prompts.join("\n"),
completion: nextCompletion,
finalCursorPosition: finalCursorPos,
editableRegionStartLine: 0,
editableRegionEndLine: 0,
userEdits: "",
userExcerpts: "",
originalEditableRange: "",
diffLines: [],
});
// Mark as displayed for JetBrains extension
await this._markDisplayedIfJetBrains(
helper.input.completionId,
outcomeNext,
);
return outcomeNext;
}
return undefined;
}
private async _handleFineTunedEndpointCompletion(
helper: HelperVars,
prompts: Prompt[],
token: AbortSignal,
startTime: number,
editableRegionStartLine: number,
editableRegionEndLine: number,
opts?: {
withChain: boolean;
usingFullFileDiff: boolean;
},
): Promise<NextEditOutcome | undefined> {
const llm = await this._prepareLlm();
if (!llm) return undefined;
// Check for mercury models, and inject unique token for next edit.
// Capture the unique tokens in llm Inception.ts and apis Inception.ts
const modelName = helper.modelName;
if (
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
) {
// Inject the unique token to the last prompt's content.
const lastPrompt = prompts[prompts.length - 1];
if (lastPrompt && typeof lastPrompt.content === "string") {
lastPrompt.content += UNIQUE_TOKEN;
}
}
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
stream: false,
});
if (typeof msg.content !== "string") {
return undefined;
}
// NOTE: Keep this in case there is a change in spec.
// const nextCompletion =
// msg.content
// .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
// .replace(/\n$/, "") ?? msg.content;
const nextCompletion = msg.content.slice(
msg.content.indexOf("```\n") + "'''\n".length,
msg.content.lastIndexOf("\n\n```"),
);
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
return await this._handlePartialFileDiff(
// we could use fillFileDiff
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
);
} else {
return await this._handleFullFileDiff(
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
);
}
}
private async _handlePartialFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
): Promise<NextEditOutcome | undefined> {
const oldEditRangeSlice = helper.fileContents
.split("\n")
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const finalCursorPos = calculateFinalCursorPosition(
helper.pos,
editableRegionStartLine,
oldEditRangeSlice,
nextCompletion,
);
const outcomeNext = await this._createNextEditOutcome({
helper,
startTime,
llm,
promptContent: this.promptMetadata!.prompt.content,
completion: nextCompletion,
finalCursorPosition: finalCursorPos,
editableRegionStartLine,
editableRegionEndLine,
userEdits: this.promptMetadata!.userEdits,
userExcerpts: this.promptMetadata!.userExcerpts,
originalEditableRange: oldEditRangeSlice,
diffLines: [],
});
this.previousCompletions.push(outcomeNext);
// Mark as displayed for JetBrains extension
await this._markDisplayedIfJetBrains(
helper.input.completionId,
outcomeNext,
);
return outcomeNext;
}
private async _handleFullFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
): Promise<NextEditOutcome | undefined> {
const fileSlice = helper.fileLines
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const diffLines = myersDiff(fileSlice, nextCompletion);
const diffGroups = groupDiffLines(
diffLines,
editableRegionStartLine,
5,
).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
const currentLine = helper.pos.line;
const prefetchQueue = PrefetchQueue.getInstance();
// Process diff groups and find the one containing the cursor
const cursorLocalDiffGroup = await this._processDiffGroups(
diffGroups,
currentLine,
helper,
startTime,
llm,
prefetchQueue,
);
// Handle the diff group containing the cursor if found
if (cursorLocalDiffGroup) {
return await this._createOutcomeFromDiffGroup(
cursorLocalDiffGroup,
helper,
startTime,
llm,
helper.input.completionId,
true,
);
// } else if (diffGroups.length > 0) {
// // Fallback to first diff group if cursor's group not found
// return await this._createOutcomeFromDiffGroup(
// diffGroups[0],
// helper,
// startTime,
// llm,
// helper.input.completionId,
// false,
// );
}
return undefined;
}
private async _processDiffGroups(
diffGroups: DiffGroup[],
currentLine: number,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
): Promise<DiffGroup | undefined> {
let cursorGroup: DiffGroup | undefined;
console.log("diffGroups:");
console.log(diffGroups);
for (const group of diffGroups) {
if (currentLine >= group.startLine && currentLine <= group.endLine) {
cursorGroup = group;
} else {
// Add non-cursor groups to prefetch queue
await this._addDiffGroupToPrefetchQueue(
group,
helper,
startTime,
llm,
prefetchQueue,
);
}
}
return cursorGroup;
}
private async _addDiffGroupToPrefetchQueue(
group: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
): Promise<void> {
const groupContent = group.lines
.filter((l) => l.type !== "old")
.map((l) => l.line)
.join("\n");
// Create a range for this diff group
const rangeInFile: RangeInFile = {
filepath: helper.filepath,
range: {
start: { line: group.startLine, character: 0 },
end: {
line: group.endLine,
character: group.lines[group.lines.length - 1].line.length,
},
},
};
const originalContent = group.lines
.filter((l) => l.type !== "new")
.map((l) => l.line)
.join("\n");
// Build outcome for this diff group
const groupOutcome = await this._createNextEditOutcome({
helper,
startTime,
llm,
promptContent: this.promptMetadata!.prompt.content,
completion: groupContent,
finalCursorPosition: {
line: group.endLine,
character: group.lines[group.lines.length - 1].line.length,
},
editableRegionStartLine: group.startLine,
editableRegionEndLine: group.endLine,
userEdits: this.promptMetadata!.userEdits,
userExcerpts: this.promptMetadata!.userExcerpts,
originalEditableRange: originalContent,
cursorPosition: { line: group.startLine, character: 0 },
completionId: uuidv4(), // Generate a new ID for this prefetched item
diffLines: group.lines,
});
// Add to prefetch queue
prefetchQueue.enqueueProcessed({
location: rangeInFile,
outcome: groupOutcome,
});
}
private async _createOutcomeFromDiffGroup(
diffGroup: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
completionId: string,
isCurrentCursorGroup: boolean,
): Promise<NextEditOutcome> {
const groupContent = diffGroup.lines
.filter((l) => l.type !== "old")
.map((line) => line.line)
.join("\n");
const originalContent = diffGroup.lines
.filter((l) => l.type !== "new")
.map((l) => l.line)
.join("\n");
// Use the actual cursor position if this is the group containing the cursor
// Otherwise use the start of the diff group
const cursorPos = isCurrentCursorGroup
? helper.pos
: { line: diffGroup.startLine, character: 0 };
const finalCursorPos = calculateFinalCursorPosition(
cursorPos,
diffGroup.startLine,
originalContent,
groupContent,
);
const outcomeNext = await this._createNextEditOutcome({
helper,
startTime,
llm,
promptContent: this.promptMetadata!.prompt.content,
completion: groupContent,
finalCursorPosition: finalCursorPos,
editableRegionStartLine: diffGroup.startLine,
editableRegionEndLine: diffGroup.endLine,
userEdits: this.promptMetadata!.userEdits,
userExcerpts: this.promptMetadata!.userExcerpts,
originalEditableRange: originalContent,
cursorPosition: cursorPos,
completionId,
diffLines: diffGroup.lines,
});
this.previousCompletions.push(outcomeNext);
// Mark as displayed for JetBrains
await this._markDisplayedIfJetBrains(completionId, outcomeNext);
return outcomeNext;
}
private async _createNextEditOutcome(outcomeCtx: {
helper: HelperVars;
startTime: number;
llm: ILLM;
promptContent: string;
completion: string;
finalCursorPosition: Position;
editableRegionStartLine: number;
editableRegionEndLine: number;
userEdits: string;
userExcerpts: string;
originalEditableRange: string;
cursorPosition?: Position;
completionId?: string;
diffLines: DiffLine[];
}): Promise<NextEditOutcome> {
return {
elapsed: Date.now() - outcomeCtx.startTime,
modelProvider: outcomeCtx.llm.underlyingProviderName,
modelName: outcomeCtx.llm.model + ":zetaDataset",
completionOptions: null,
completionId:
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
fileUri: outcomeCtx.helper.filepath,
workspaceDirUri:
outcomeCtx.helper.workspaceUris[0] ??
path.dirname(outcomeCtx.helper.filepath),
prompt: outcomeCtx.promptContent,
userEdits: outcomeCtx.userEdits ?? "",
userExcerpts: outcomeCtx.userExcerpts ?? "",
originalEditableRange: outcomeCtx.originalEditableRange ?? "",
completion: outcomeCtx.completion,
cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
finalCursorPosition: outcomeCtx.finalCursorPosition,
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
diffLines: outcomeCtx.diffLines,
...outcomeCtx.helper.options,
};
}
private async _markDisplayedIfJetBrains(
completionId: string,
outcome: NextEditOutcome,

View file

@ -0,0 +1,16 @@
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
import { InstinctProvider } from "./providers/InstinctNextEditProvider.js";
import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js";
export class NextEditProviderFactory {
static createProvider(modelName: string): BaseNextEditProvider {
if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) {
return new MercuryCoderProvider();
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
return new InstinctProvider();
} else {
throw new Error(`Unsupported model: ${modelName}`);
}
}
}

View file

@ -12,10 +12,6 @@ export const MODEL_WINDOW_SIZES: Record<
topMargin: 0,
bottomMargin: 5,
}, // mercury coder uses full file diff, so this should be unnecessary
"mercury-coder-nextedit": {
topMargin: 0,
bottomMargin: 5,
}, // mercury coder nextedit uses full file diff, so this should be unnecessary
instinct: { topMargin: 1, bottomMargin: 5 },
};

View file

@ -0,0 +1,415 @@
import * as path from "path";
import { v4 as uuidv4 } from "uuid";
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
import { myersDiff } from "../../diff/myers.js";
import { DiffLine, IDE, ILLM, Position, RangeInFile } from "../../index.js";
import { countTokens } from "../../llm/countTokens.js";
import {
calculateFinalCursorPosition,
DiffGroup,
groupDiffLines,
} from "../diff/diff.js";
import { PrefetchQueue } from "../NextEditPrefetchQueue.js";
import {
ModelSpecificContext,
NextEditOutcome,
Prompt,
PromptMetadata,
} from "../types.js";
import { isWhitespaceOnlyDeletion } from "../utils.js";
export abstract class BaseNextEditProvider {
protected readonly modelName: string;
constructor(modelName: string) {
this.modelName = modelName;
}
// Leave methods as abstract when you must have the models implement their own versions.
abstract getSystemPrompt(): string;
abstract generatePrompts(context: ModelSpecificContext): Promise<Prompt[]>;
abstract extractCompletion(message: string): string;
abstract buildPromptContext(context: ModelSpecificContext): any;
abstract buildPromptMetadata(context: ModelSpecificContext): PromptMetadata;
abstract getWindowSize(): { topMargin: number; bottomMargin: number };
abstract calculateEditableRegion(
helper: HelperVars,
usingFullFileDiff: boolean,
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
};
// Methods that can be used as default fallback.
public async handlePartialFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome> {
const oldEditRangeSlice = helper.fileContents
.split("\n")
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const finalCursorPos = calculateFinalCursorPosition(
helper.pos,
editableRegionStartLine,
oldEditRangeSlice,
nextCompletion,
);
const outcome = await this.createNextEditOutcome({
helper,
startTime,
llm,
promptContent: promptMetadata.prompt.content,
completion: nextCompletion,
finalCursorPosition: finalCursorPos,
editableRegionStartLine,
editableRegionEndLine,
userEdits: promptMetadata.userEdits,
userExcerpts: promptMetadata.userExcerpts,
originalEditableRange: oldEditRangeSlice,
diffLines: [],
ide,
});
return outcome;
}
public async handleFullFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome | undefined> {
const fileSlice = helper.fileLines
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
const diffLines = myersDiff(fileSlice, nextCompletion);
const diffGroups = groupDiffLines(
diffLines,
editableRegionStartLine,
5,
).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
const currentLine = helper.pos.line;
const prefetchQueue = PrefetchQueue.getInstance();
const cursorLocalDiffGroup = await this.processDiffGroups(
diffGroups,
currentLine,
helper,
startTime,
llm,
prefetchQueue,
promptMetadata,
ide,
);
if (cursorLocalDiffGroup) {
return await this.createOutcomeFromDiffGroup(
cursorLocalDiffGroup,
helper,
startTime,
llm,
helper.input.completionId,
true,
promptMetadata,
ide,
);
}
return undefined;
}
/**
* Process diff groups and find the one containing the cursor.
*/
private async processDiffGroups(
diffGroups: DiffGroup[],
currentLine: number,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<DiffGroup | undefined> {
let cursorGroup: DiffGroup | undefined;
for (const group of diffGroups) {
if (currentLine >= group.startLine && currentLine <= group.endLine) {
cursorGroup = group;
} else {
await this.addDiffGroupToPrefetchQueue(
group,
helper,
startTime,
llm,
prefetchQueue,
promptMetadata,
ide,
);
}
}
return cursorGroup;
}
private async addDiffGroupToPrefetchQueue(
group: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<void> {
// Extract lines that are not old.
const groupContent = group.lines
.filter((l) => l.type !== "old")
.map((l) => l.line)
.join("\n");
const rangeInFile: RangeInFile = {
filepath: helper.filepath,
range: {
start: { line: group.startLine, character: 0 },
end: {
line: group.endLine,
character: group.lines[group.lines.length - 1].line.length,
},
},
};
// Extract lines that are not new.
const originalContent = group.lines
.filter((l) => l.type !== "new")
.map((l) => l.line)
.join("\n");
const groupOutcome = await this.createNextEditOutcome({
helper,
startTime,
llm,
promptContent: promptMetadata.prompt.content,
completion: groupContent,
finalCursorPosition: {
line: group.endLine,
character: group.lines[group.lines.length - 1].line.length,
},
editableRegionStartLine: group.startLine,
editableRegionEndLine: group.endLine,
userEdits: promptMetadata.userEdits,
userExcerpts: promptMetadata.userExcerpts,
originalEditableRange: originalContent,
cursorPosition: { line: group.startLine, character: 0 },
completionId: uuidv4(), // Generate a new ID for this prefetched item.
diffLines: group.lines,
ide,
});
prefetchQueue.enqueueProcessed({
location: rangeInFile,
outcome: groupOutcome,
});
}
private async createOutcomeFromDiffGroup(
diffGroup: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
completionId: string,
isCurrentCursorGroup: boolean,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome> {
const groupContent = diffGroup.lines
.filter((l) => l.type !== "old")
.map((l) => l.line)
.join("\n");
const originalContent = diffGroup.lines
.filter((l) => l.type !== "new")
.map((l) => l.line)
.join("\n");
const cursorPos = isCurrentCursorGroup
? helper.pos
: { line: diffGroup.startLine, character: 0 };
const finalCursorPos = calculateFinalCursorPosition(
cursorPos,
diffGroup.startLine,
originalContent,
groupContent,
);
const outcomeNext = await this.createNextEditOutcome({
helper,
startTime,
llm,
promptContent: promptMetadata.prompt.content,
completion: groupContent,
finalCursorPosition: finalCursorPos,
editableRegionStartLine: diffGroup.startLine,
editableRegionEndLine: diffGroup.endLine,
userEdits: promptMetadata.userEdits,
userExcerpts: promptMetadata.userExcerpts,
originalEditableRange: originalContent,
cursorPosition: cursorPos,
completionId,
diffLines: diffGroup.lines,
ide,
});
return outcomeNext;
}
protected async createNextEditOutcome(outcomeCtx: {
helper: HelperVars;
startTime: number;
llm: ILLM;
promptContent: string;
completion: string;
finalCursorPosition: Position;
editableRegionStartLine: number;
editableRegionEndLine: number;
userEdits: string;
userExcerpts: string;
originalEditableRange: string;
cursorPosition?: Position;
completionId?: string;
diffLines: DiffLine[];
ide: IDE;
}): Promise<NextEditOutcome> {
return {
elapsed: Date.now() - outcomeCtx.startTime,
modelProvider: outcomeCtx.llm.underlyingProviderName,
modelName: outcomeCtx.llm.model + ":zetaDataset",
completionOptions: null,
completionId:
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath),
uniqueId: await outcomeCtx.ide.getUniqueId(),
timestamp: Date.now(),
fileUri: outcomeCtx.helper.filepath,
workspaceDirUri:
outcomeCtx.helper.workspaceUris[0] ??
path.dirname(outcomeCtx.helper.filepath),
prompt: outcomeCtx.promptContent,
userEdits: outcomeCtx.userEdits ?? "",
userExcerpts: outcomeCtx.userExcerpts ?? "",
originalEditableRange: outcomeCtx.originalEditableRange ?? "",
completion: outcomeCtx.completion,
cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
finalCursorPosition: outcomeCtx.finalCursorPosition,
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
diffLines: outcomeCtx.diffLines,
...outcomeCtx.helper.options,
};
}
// Shared utility for calculating editable regions.
protected calculateOptimalEditableRegion(
helper: HelperVars,
maxTokens: number = 512,
heuristic: "fourChars" | "tokenizer" = "tokenizer",
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
} {
const cursorLine = helper.pos.line;
const fileLines = helper.fileLines;
let editableRegionStartLine = cursorLine;
let editableRegionEndLine = cursorLine;
let currentContent = fileLines[cursorLine];
let totalTokens =
heuristic === "tokenizer"
? countTokens(currentContent, helper.modelName)
: Math.ceil(currentContent.length / 4);
let addingAbove = true;
while (totalTokens < maxTokens) {
let addedLine = false;
if (addingAbove) {
if (editableRegionStartLine > 0) {
editableRegionStartLine--;
const lineContent = fileLines[editableRegionStartLine];
const lineTokens =
heuristic === "tokenizer"
? countTokens(lineContent, helper.modelName)
: Math.ceil(lineContent.length / 4);
totalTokens += lineTokens;
addedLine = true;
}
} else {
if (editableRegionEndLine < fileLines.length - 1) {
editableRegionEndLine++;
const lineContent = fileLines[editableRegionEndLine];
const lineTokens =
heuristic === "tokenizer"
? countTokens(lineContent, helper.modelName)
: Math.ceil(lineContent.length / 4);
totalTokens += lineTokens;
addedLine = true;
}
}
if (!addedLine) {
if (
editableRegionStartLine === 0 &&
editableRegionEndLine === fileLines.length - 1
) {
break;
}
addingAbove = !addingAbove;
continue;
}
if (totalTokens > maxTokens) {
if (addingAbove) {
editableRegionStartLine++;
} else {
editableRegionEndLine--;
}
break;
}
addingAbove = !addingAbove;
}
return {
editableRegionStartLine,
editableRegionEndLine,
};
}
// Optional methods with defaults.
shouldInjectUniqueToken(): boolean {
return false;
}
getUniqueToken(): string | null {
return null;
}
}

View file

@ -0,0 +1,155 @@
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
import { INSTINCT_SYSTEM_PROMPT } from "../constants.js";
import {
contextSnippetsBlock,
currentFileContentBlock,
editHistoryBlock,
} from "../templating/instinct.js";
import {
NEXT_EDIT_MODEL_TEMPLATES,
PromptTemplateRenderer,
} from "../templating/NextEditPromptEngine.js";
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
export class InstinctProvider extends BaseNextEditProvider {
private templateRenderer: PromptTemplateRenderer;
constructor() {
super(NEXT_EDIT_MODELS.INSTINCT);
const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT];
this.templateRenderer = new PromptTemplateRenderer(template.template);
}
getSystemPrompt(): string {
return INSTINCT_SYSTEM_PROMPT;
}
getWindowSize() {
return { topMargin: 1, bottomMargin: 5 };
}
shouldInjectUniqueToken(): boolean {
return false; // Instinct doesn't use unique tokens.
}
extractCompletion(message: string): string {
return message; // Instinct returns the completion directly.
}
buildPromptContext(context: ModelSpecificContext): any {
// Calculate the window around the cursor position (25 lines above and below).
const windowStart = Math.max(0, context.helper.pos.line - 25);
const windowEnd = Math.min(
context.helper.fileLines.length - 1,
context.helper.pos.line + 25,
);
// Ensure editable region boundaries are within the window.
const adjustedEditableStart = Math.max(
windowStart,
context.editableRegionStartLine,
);
const adjustedEditableEnd = Math.min(
windowEnd,
context.editableRegionEndLine,
);
return {
contextSnippets: context.autocompleteContext,
currentFileContent: context.helper.fileContents,
windowStart,
windowEnd,
editableRegionStartLine: adjustedEditableStart,
editableRegionEndLine: adjustedEditableEnd,
editDiffHistory: context.diffContext,
currentFilePath: context.helper.filepath,
languageShorthand: context.helper.lang.name,
};
}
async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> {
const promptCtx = this.buildPromptContext(context);
const templateVars = {
contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets),
currentFileContent: currentFileContentBlock(
promptCtx.currentFileContent,
promptCtx.windowStart,
promptCtx.windowEnd,
promptCtx.editableRegionStartLine,
promptCtx.editableRegionEndLine,
context.helper.pos,
),
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
currentFilePath: promptCtx.currentFilePath,
languageShorthand: promptCtx.languageShorthand,
};
const userPromptContent = this.templateRenderer.render(templateVars);
return [
{
role: "system",
content: this.getSystemPrompt(),
},
{
role: "user",
content: userPromptContent,
},
];
}
buildPromptMetadata(context: ModelSpecificContext): PromptMetadata {
const promptCtx = this.buildPromptContext(context);
const templateVars = {
contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets),
currentFileContent: currentFileContentBlock(
promptCtx.currentFileContent,
promptCtx.windowStart,
promptCtx.windowEnd,
promptCtx.editableRegionStartLine,
promptCtx.editableRegionEndLine,
context.helper.pos,
),
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
currentFilePath: promptCtx.currentFilePath,
languageShorthand: promptCtx.languageShorthand,
};
const userPromptContent = this.templateRenderer.render(templateVars);
return {
prompt: {
role: "user",
content: userPromptContent,
},
userEdits: promptCtx.editDiffHistory.join("\n"),
userExcerpts: templateVars.currentFileContent,
};
}
calculateEditableRegion(
helper: HelperVars,
usingFullFileDiff: boolean,
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
} {
if (usingFullFileDiff) {
return this.calculateOptimalEditableRegion(helper, 512, "tokenizer");
} else {
const { topMargin, bottomMargin } = this.getWindowSize();
return {
editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0),
editableRegionEndLine: Math.min(
helper.pos.line + bottomMargin,
helper.fileLines.length - 1,
),
};
}
}
}

View file

@ -0,0 +1,145 @@
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
import { MERCURY_SYSTEM_PROMPT, UNIQUE_TOKEN } from "../constants.js";
import {
currentFileContentBlock,
editHistoryBlock,
recentlyViewedCodeSnippetsBlock,
} from "../templating/mercuryCoderNextEdit.js";
import {
NEXT_EDIT_MODEL_TEMPLATES,
PromptTemplateRenderer,
} from "../templating/NextEditPromptEngine.js";
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
export class MercuryCoderProvider extends BaseNextEditProvider {
private templateRenderer: PromptTemplateRenderer;
constructor() {
super(NEXT_EDIT_MODELS.MERCURY_CODER);
const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER];
this.templateRenderer = new PromptTemplateRenderer(template.template);
}
getSystemPrompt(): string {
return MERCURY_SYSTEM_PROMPT;
}
getWindowSize() {
return { topMargin: 0, bottomMargin: 5 };
}
shouldInjectUniqueToken(): boolean {
return true;
}
getUniqueToken(): string {
return UNIQUE_TOKEN;
}
extractCompletion(message: string): string {
// Extract the code between the markdown code blocks.
return message.slice(
message.indexOf("```\n") + "```\n".length,
message.lastIndexOf("\n\n```"),
);
}
buildPromptContext(context: ModelSpecificContext): any {
return {
recentlyViewedCodeSnippets:
context.snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
filepath: snip.filepath,
content: snip.content,
})) ?? [],
currentFileContent: context.helper.fileContents,
editableRegionStartLine: context.editableRegionStartLine,
editableRegionEndLine: context.editableRegionEndLine,
editDiffHistory: context.diffContext,
currentFilePath: context.helper.filepath,
};
}
async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> {
const promptCtx = this.buildPromptContext(context);
const templateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
promptCtx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
promptCtx.currentFileContent,
promptCtx.editableRegionStartLine,
promptCtx.editableRegionEndLine,
context.helper.pos,
),
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
currentFilePath: promptCtx.currentFilePath,
};
const userPromptContent = this.templateRenderer.render(templateVars);
return [
{
role: "system",
content: this.getSystemPrompt(),
},
{
role: "user",
content: userPromptContent,
},
];
}
buildPromptMetadata(context: ModelSpecificContext): PromptMetadata {
const promptCtx = this.buildPromptContext(context);
const templateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
promptCtx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
promptCtx.currentFileContent,
promptCtx.editableRegionStartLine,
promptCtx.editableRegionEndLine,
context.helper.pos,
),
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
currentFilePath: promptCtx.currentFilePath,
};
const userPromptContent = this.templateRenderer.render(templateVars);
return {
prompt: {
role: "user",
content: userPromptContent,
},
userEdits: promptCtx.editDiffHistory.join("\n"),
userExcerpts: templateVars.currentFileContent,
};
}
calculateEditableRegion(
helper: HelperVars,
usingFullFileDiff: boolean,
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
} {
if (usingFullFileDiff) {
return this.calculateOptimalEditableRegion(helper, 512, "tokenizer");
} else {
const { topMargin, bottomMargin } = this.getWindowSize();
return {
editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0),
editableRegionEndLine: Math.min(
helper.pos.line + bottomMargin,
helper.fileLines.length - 1,
),
};
}
}
}

View file

@ -1,7 +1,4 @@
import Handlebars from "handlebars";
import { Position } from "../..";
import { SnippetPayload } from "../../autocomplete/snippets";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_PROMPT_PREFIX,
@ -12,274 +9,39 @@ import {
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
} from "../constants";
import {
InstinctTemplateVars,
MercuryTemplateVars,
NextEditTemplate,
PromptMetadata,
SystemPrompt,
TemplateVars,
UserPrompt,
} from "../types";
import {
contextSnippetsBlock,
currentFileContentBlock as instinctCurrentFileContentBlock,
editHistoryBlock as instinctEditHistoryBlock,
} from "./instinct";
import {
currentFileContentBlock,
editHistoryBlock,
recentlyViewedCodeSnippetsBlock,
} from "./mercuryCoderNextEdit";
import {
insertCursorToken,
insertEditableRegionTokensWithStaticRange,
} from "./utils";
import { NextEditTemplate, TemplateVars } from "../types";
type TemplateRenderer = (vars: TemplateVars) => string;
const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
// Keep the template registry
export const NEXT_EDIT_MODEL_TEMPLATES: Record<
NEXT_EDIT_MODELS,
NextEditTemplate
> = {
"mercury-coder": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
},
"mercury-coder-nextedit": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
},
instinct: {
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
},
};
function templateRendererOfModel(
modelName: NEXT_EDIT_MODELS,
): TemplateRenderer {
let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
// Export a utility for providers to use
export class PromptTemplateRenderer {
private compiledTemplate: HandlebarsTemplateDelegate;
constructor(template: string) {
this.compiledTemplate = Handlebars.compile(template);
}
render(vars: TemplateVars): string {
return this.compiledTemplate(vars);
}
}
// Keep for backward compatibility or remove if not needed
export function getTemplateForModel(modelName: NEXT_EDIT_MODELS): string {
const template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
if (!template) {
throw new Error(`Model ${modelName} is not supported for next edit.`);
}
const compiledTemplate = Handlebars.compile(template.template);
return (vars: TemplateVars): string => {
return compiledTemplate(vars);
};
}
export async function renderPrompt(
helper: HelperVars,
ctx: any,
): Promise<PromptMetadata> {
let modelName = helper.modelName as NEXT_EDIT_MODELS;
// Validate that the modelName is actually a supported model.
if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
// Check if modelName includes any known model name as substring.
const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) =>
modelName.includes(key),
);
if (matchingModel) {
modelName = matchingModel as NEXT_EDIT_MODELS;
} else {
throw new Error(
`${helper.modelName} is not yet supported for next edit.`,
);
}
}
const renderer = templateRendererOfModel(modelName);
let userEdits = "";
let editedCodeWithTokens = "";
let tv: TemplateVars;
switch (modelName) {
case NEXT_EDIT_MODELS.MERCURY_CODER: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// MERCURY_CURSOR,
// );
const mercuryCtx: MercuryTemplateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
ctx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
ctx.currentFileContent,
ctx.editableRegionStartLine,
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
};
tv = mercuryCtx;
editedCodeWithTokens = mercuryCtx.currentFileContent;
break;
}
case NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// MERCURY_CURSOR,
// );
const mercuryCtx: MercuryTemplateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
ctx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
ctx.currentFileContent,
ctx.editableRegionStartLine,
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
};
tv = mercuryCtx;
editedCodeWithTokens = mercuryCtx.currentFileContent;
break;
}
case NEXT_EDIT_MODELS.INSTINCT: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
// );
const instinctCtx: InstinctTemplateVars = {
contextSnippets: contextSnippetsBlock(ctx.contextSnippets),
currentFileContent: instinctCurrentFileContentBlock(
ctx.currentFileContent,
ctx.windowStart,
ctx.windowEnd,
ctx.editableRegionStartLine,
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
languageShorthand: ctx.languageShorthand,
};
tv = instinctCtx;
editedCodeWithTokens = instinctCtx.currentFileContent;
break;
}
default:
tv = {};
break;
}
return {
prompt: {
role: "user",
content: renderer(tv),
},
userEdits,
userExcerpts: editedCodeWithTokens,
};
}
export function renderDefaultSystemPrompt(): SystemPrompt {
return {
role: "system",
content: [
/* Identity forming */
"You are an expert polyglot developer who is overseeing a junior developer write code in some language.",
"You are psychic as well, so you are an expert at reading minds just from what the junior has done.",
"As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.",
/* Action crash course */
"An action is a change in code state that preserves the well-formedness of the code.",
"Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.",
/* Input description */
// 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.',
// "language is the language the code is written in.",
// "originalCode is the code state before the junior has taken some edit action.",
// "editedCode is the code state after the junior has taken some edit action.",
// "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.",
// "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.",
'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.',
"rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.",
"recentlyEditedRange is the code that the junior has recently edited.",
"Do not guess what previous edit the junior has taken right before the request -- this is already given to you.",
"The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.",
"The junior might want to add new code, delete existing code, or replace different parts of code.",
"The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.",
/* Output description */
'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.',
/* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/
/* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */
"actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.",
// "actionType is the type of action the junior has taken.",
"newCode is what the full code looks like after applying your nextEditContent.",
// "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.",
"Given the above definition of an action, you should prioritize fixing the following:",
"- Patterns and repetition in code.",
"- Static errors that the compiler of the language may return.",
"- The junior's code style.",
"If the junior has deleted some code, there's a good chance that the next edit will also be deletions.",
"If the junior has added some code, there's a good chance that the next edit will also be additions.",
"If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.",
"Careful of language intricacies.",
// "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.",
"Do not reply in markdown.",
"Do not hallucinate.",
].join(" "),
};
}
export function renderDefaultUserPrompt(
// originalCode: string,
// editedCode: string,
snippets: SnippetPayload,
helper: HelperVars,
): UserPrompt {
const userEdit = {
language: helper.lang,
rootPathSnippets: snippets.rootPathSnippets,
importDefinitionSnippets: snippets.importDefinitionSnippets,
ideSnippets: snippets.ideSnippets,
recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets,
diffSnippets: snippets.diffSnippets,
clipboardSnippets: snippets.clipboardSnippets,
recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets,
};
return {
role: "user",
content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`,
};
}
function insertTokens(
lines: string[],
cursorPos: Position,
cursorToken: string,
editableRegionStart?: number,
editableRegionEnd?: number,
) {
const a = insertCursorToken(lines, cursorPos, cursorToken);
const b = insertEditableRegionTokensWithStaticRange(
a,
cursorPos,
editableRegionStart,
editableRegionEnd,
);
return b.join("\n");
return template.template;
}

View file

@ -1,243 +1,112 @@
import { beforeEach, describe, expect, it } from "vitest";
import { Position } from "../..";
import { SnippetPayload } from "../../autocomplete/snippets";
import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
import { HelperVars } from "../../autocomplete/util/HelperVars";
import { describe, expect, it } from "vitest";
import { NEXT_EDIT_MODELS } from "../../llm/constants";
import {
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
INSTINCT_USER_PROMPT_PREFIX,
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
MERCURY_CURRENT_FILE_CONTENT_OPEN,
MERCURY_CURSOR,
MERCURY_EDIT_DIFF_HISTORY_CLOSE,
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
} from "../constants";
import {
renderDefaultSystemPrompt,
renderDefaultUserPrompt,
renderPrompt,
NEXT_EDIT_MODEL_TEMPLATES,
PromptTemplateRenderer,
getTemplateForModel,
} from "./NextEditPromptEngine";
describe("NextEditPromptEngine", () => {
describe("renderPrompt", () => {
let mercuryHelper: HelperVars;
let instinctHelper: HelperVars;
let testHelper: HelperVars;
let unsupportedHelper: HelperVars;
let ctx: any;
beforeEach(() => {
mercuryHelper = {
modelName: "inception/mercury-coder" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
instinctHelper = {
modelName: "continuedev/instinct" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
unsupportedHelper = {
modelName: "mistral/codestral" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
ctx = {
recentlyViewedCodeSnippets: [
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
],
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
editableRegionStartLine: 0,
editableRegionEndLine: 3,
userEdits: "Added constant a",
languageShorthand: "ts",
userExcerpts: "const a = 1;",
};
});
it("should render mercury-coder prompt correctly", async () => {
const result = await renderPrompt(mercuryHelper, ctx);
expect(result).toHaveProperty("prompt");
expect(result.prompt.role).toBe("user");
const content = result.prompt.content;
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE);
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
expect(result.userEdits).toBe(ctx.editDiffHistory);
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
});
it("should render instinct prompt correctly", async () => {
// Create proper instinct context structure matching NextEditProvider.ts
const instinctCtx = {
contextSnippets:
"+++++ /path/to/context.ts\nconst contextVar = 'test';",
currentFileContent: instinctHelper.fileContents,
windowStart: 0, // Math.max(0, helper.pos.line - 25)
windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25)
editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window
editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window
editDiffHistory: [
"diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }",
], // unified diff
currentFilePath: "/path/to/file.ts",
languageShorthand: "ts",
};
const result = await renderPrompt(instinctHelper, instinctCtx);
console.log(result);
expect(result).toHaveProperty("prompt");
expect(result.prompt.role).toBe("user");
expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX);
expect(result.prompt.content).toContain("### Context:");
expect(result.prompt.content).toContain("### User Edits:");
expect(result.prompt.content).toContain("### User Excerpt:");
expect(result.userEdits).toBe(instinctCtx.editDiffHistory);
expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN);
});
it("should throw error for unsupported model name", async () => {
await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow(
"mistral/codestral is not yet supported for next edit.",
describe("NEXT_EDIT_MODEL_TEMPLATES", () => {
it("should contain templates for all supported models", () => {
expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty(
NEXT_EDIT_MODELS.MERCURY_CODER,
);
expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty(
NEXT_EDIT_MODELS.INSTINCT,
);
});
});
describe("renderDefaultSystemPrompt", () => {
it("should return a system prompt with expected role and content", () => {
const result = renderDefaultSystemPrompt();
it("mercury-coder template should contain expected tokens", () => {
const template =
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template;
expect(result.role).toBe("system");
expect(result.content).toContain("You are an expert polyglot developer");
expect(result.content).toContain("Do not hallucinate.");
expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
expect(template).toContain("{{{recentlyViewedCodeSnippets}}}");
expect(template).toContain("{{{currentFileContent}}}");
expect(template).toContain("{{{editDiffHistory}}}");
});
it("instinct template should contain expected tokens", () => {
const template =
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT].template;
expect(template).toContain(INSTINCT_USER_PROMPT_PREFIX);
expect(template).toContain("### Context:");
expect(template).toContain("### User Edits:");
expect(template).toContain("### User Excerpt:");
expect(template).toContain("{{{contextSnippets}}}");
expect(template).toContain("{{{currentFileContent}}}");
expect(template).toContain("{{{editDiffHistory}}}");
expect(template).toContain("{{{currentFilePath}}}");
});
});
describe("renderDefaultUserPrompt", () => {
it("should render a user prompt with the correct structure", () => {
const snippets: SnippetPayload = {
rootPathSnippets: [
{
type: AutocompleteSnippetType.Code,
filepath: "",
content: "root path",
},
],
importDefinitionSnippets: [
{
type: AutocompleteSnippetType.Code,
filepath: "",
content: "import def",
},
],
ideSnippets: [
{
type: AutocompleteSnippetType.Code,
filepath: "",
content: "ide snippets",
},
],
recentlyEditedRangeSnippets: [
{
type: AutocompleteSnippetType.Code,
filepath: "",
content: "recent edits",
},
],
diffSnippets: [
{
type: AutocompleteSnippetType.Diff,
content: "diff snippets",
},
],
clipboardSnippets: [
{
type: AutocompleteSnippetType.Clipboard,
content: "clipboard",
copiedAt: new Date().toISOString(),
},
],
recentlyVisitedRangesSnippets: [
{
type: AutocompleteSnippetType.Code,
filepath: "",
content: "visited ranges",
},
],
recentlyOpenedFileSnippets: [
{
type: AutocompleteSnippetType.Code,
filepath: "",
content: "recently opened files",
},
],
staticSnippet: [
{
type: AutocompleteSnippetType.Static,
filepath: "",
content: "static content",
},
],
};
describe("PromptTemplateRenderer", () => {
it("should render a template with provided variables", () => {
const template = "Hello {{{name}}}, you have {{{count}}} messages";
const renderer = new PromptTemplateRenderer(template);
const helper: HelperVars = {
lang: { name: "typescript" },
} as HelperVars;
const result = renderDefaultUserPrompt(snippets, helper);
expect(result.role).toBe("user");
expect(result.content).toContain("Your junior made the following edit:");
expect(result.content).toContain("typescript");
expect(result.content).toContain("root path");
});
});
describe("insertTokens", () => {
it("should correctly insert cursor and editable region tokens", () => {
const mercuryHelper = {
modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
} as HelperVars;
const ctx = {
recentlyViewedCodeSnippets: [
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
],
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
editableRegionStartLine: 0,
editableRegionEndLine: 3,
userEdits: "Added constant a",
languageShorthand: "ts",
userExcerpts: "const a = 1;",
};
return renderPrompt(mercuryHelper, ctx).then((result) => {
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
const result = renderer.render({
name: "Alice",
count: "5",
});
expect(result).toBe("Hello Alice, you have 5 messages");
});
it("should handle missing variables gracefully", () => {
const template = "Hello {{{name}}}";
const renderer = new PromptTemplateRenderer(template);
const result = renderer.render({});
expect(result).toBe("Hello ");
});
it("should render complex templates correctly", () => {
const template =
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template;
const renderer = new PromptTemplateRenderer(template);
const result = renderer.render({
recentlyViewedCodeSnippets: "snippet1",
currentFileContent: "file content",
editDiffHistory: "diff history",
});
expect(result).toContain("snippet1");
expect(result).toContain("file content");
expect(result).toContain("diff history");
});
});
describe("getTemplateForModel", () => {
it("should return the correct template for a supported model", () => {
const template = getTemplateForModel(NEXT_EDIT_MODELS.MERCURY_CODER);
expect(template).toBe(
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template,
);
});
it("should throw an error for an unsupported model", () => {
expect(() =>
getTemplateForModel("unsupported" as NEXT_EDIT_MODELS),
).toThrow("Model unsupported is not supported for next edit.");
});
});
});

View file

@ -5,7 +5,9 @@ import {
RangeInFile,
TabAutocompleteOptions,
} from "../";
import { SnippetPayload } from "../autocomplete/snippets";
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
import { HelperVars } from "../autocomplete/util/HelperVars";
export type RecentlyEditedRange = RangeInFile & {
timestamp: number;
@ -104,3 +106,36 @@ export interface MercuryTemplateVars extends TemplateVars {
editDiffHistory: string; // could be a singe large unified diff
currentFilePath: string;
}
/**
* Context object containing all necessary information for model-specific operations.
*/
export interface ModelSpecificContext {
helper: HelperVars;
snippetPayload: SnippetPayload;
editableRegionStartLine: number;
editableRegionEndLine: number;
diffContext: string[];
autocompleteContext: string;
historyDiff?: string;
workspaceDirs?: string[];
}
/**
* Configuration for editable region calculation.
*/
export interface EditableRegionConfig {
usingFullFileDiff?: boolean;
maxTokens?: number;
topMargin?: number;
bottomMargin?: number;
}
/**
* Configuration for prompt generation.
*/
export interface PromptConfig {
includeHistory?: boolean;
includeRecentEdits?: boolean;
maxContextSnippets?: number;
}

View file

@ -1,4 +1,5 @@
import { DiffLine } from "..";
import { NEXT_EDIT_MODELS } from "../llm/constants";
export function isNextEditTest(): boolean {
const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
@ -21,3 +22,11 @@ export function isWhitespaceOnlyDeletion(diffLines: DiffLine[]): boolean {
(diff.line.trim() === "" || /^\s+$/.test(diff.line)),
);
}
export function convertNextEditModelNameToEnum(
modelName: string,
): NEXT_EDIT_MODELS | undefined {
const nextEditModels = Object.values(NEXT_EDIT_MODELS);
return nextEditModels.find((model) => modelName.includes(model));
}

View file

@ -1,6 +1,11 @@
import { describe, expect, test, vi } from "vitest";
import { DiffLine } from "..";
import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils";
import { NEXT_EDIT_MODELS } from "../llm/constants";
import {
convertNextEditModelNameToEnum,
isNextEditTest,
isWhitespaceOnlyDeletion,
} from "./utils";
describe("isNextEditTest", () => {
test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => {
@ -57,3 +62,35 @@ describe("isWhitespaceOnlyDeletion", () => {
expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
});
});
describe("convertNextEditModelNameToEnum", () => {
test("returns correct enum for exact matches", () => {
Object.values(NEXT_EDIT_MODELS).forEach((model) => {
expect(convertNextEditModelNameToEnum(model)).toBe(model);
});
});
test("returns correct enum when model name is contained in a longer string", () => {
expect(convertNextEditModelNameToEnum("inception/mercury-coder")).toBe(
NEXT_EDIT_MODELS.MERCURY_CODER,
);
expect(convertNextEditModelNameToEnum("blah/instinct")).toBe(
NEXT_EDIT_MODELS.INSTINCT,
);
});
test("returns undefined for non-matching model names", () => {
expect(convertNextEditModelNameToEnum("unknown-model")).toBeUndefined();
expect(convertNextEditModelNameToEnum("random-string")).toBeUndefined();
expect(convertNextEditModelNameToEnum("")).toBeUndefined();
});
test("returns first match when multiple models could match", () => {
const modelName = "model-that-contains-multiple-matches";
const result = convertNextEditModelNameToEnum(modelName);
if (result !== undefined) {
expect(Object.values(NEXT_EDIT_MODELS)).toContain(result);
}
});
});