From 377cdf571fbccf54f578fde3fd627a1e0e07d672 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 18 Aug 2025 18:51:12 -0700 Subject: [PATCH 1/8] feat: use mercury-coder in favor of nextedit --- core/llm/autodetect.ts | 1 + core/llm/constants.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index f167d02f9..3f9e62dfc 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -177,6 +177,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( // NOTE: When updating this list, // 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, ]; diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 704931af5..4364257ab 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -20,6 +20,7 @@ export enum LLMConfigurationStatuses { } export enum NEXT_EDIT_MODELS { + MERCURY_CODER = "mercury-coder", MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit", INSTINCT = "instinct", } From e45171f786a9e8238dab8ae222eb94c859275f41 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 18 Aug 2025 18:51:46 -0700 Subject: [PATCH 2/8] feat: add overrides to handle /edit/completions requests --- core/llm/llms/Inception.ts | 97 +++++++++++++- .../openai-adapters/src/apis/Inception.ts | 120 +++++++++++++++++- 2 files changed, 215 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts index 385dea23c..9d2b67ea7 100644 --- a/core/llm/llms/Inception.ts +++ b/core/llm/llms/Inception.ts @@ -1,6 +1,8 @@ import { streamSse } from "@continuedev/fetch"; -import { CompletionOptions, LLMOptions } from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { ChatCompletionCreateParams } from "@continuedev/openai-adapters"; +import { UNIQUE_TOKEN } from "../../nextEdit/constants.js"; import OpenAI from "./OpenAI.js"; /** @@ -32,6 +34,26 @@ class Inception extends OpenAI { return true; } + // It seems like this should be inherited automatically from the parent OpenAI class, but it sometimes doesn't. + // protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [ + // "chat", + // "embed", + // "list", + // "rerank", + // "streamChat", + // "streamFim", + // ]; + + protected modifyChatBody( + body: ChatCompletionCreateParams, + ): ChatCompletionCreateParams { + const hasNextEditCapability = this.capabilities?.nextEdit ?? false; + + // Add the nextEdit parameter for Inception-specific routing. + (body as any).nextEdit = hasNextEditCapability; + return body; + } + async *_streamFim( prefix: string, suffix: string, @@ -67,6 +89,79 @@ class Inception extends OpenAI { yield chunk.choices[0].text; } } + + protected async *_streamChat( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + if (this.isNextEdit(messages)) { + messages = this.removeNextEditToken(messages); + + // Use edit/completions endpoint. + const endpoint = new URL("edit/completions", this.apiBase); + + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + messages: messages, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal, + }); + + for await (const chunk of streamSse(resp)) { + if (chunk.choices?.[0]?.delta?.content) { + yield { + role: "assistant", + content: chunk.choices[0].delta.content, + }; + } + } + } else { + // Use regular chat/completions endpoint - call parent OpenAI implementation. + yield* super._streamChat(messages, signal, options); + } + } + + private isNextEdit(messages: ChatMessage[]): boolean { + // Check if any message contains the unique next edit token. + return messages.some( + (message) => + typeof message.content === "string" && + message.content.endsWith(UNIQUE_TOKEN), + ); + } + + private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] { + const lastMessage = messages[messages.length - 1]; + + if ( + typeof lastMessage?.content === "string" && + lastMessage.content.endsWith(UNIQUE_TOKEN) + ) { + const cleanedMessages = [...messages]; + cleanedMessages[cleanedMessages.length - 1] = { + ...lastMessage, + content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), + }; + return cleanedMessages; + } + + return messages; + } } export default Inception; diff --git a/packages/openai-adapters/src/apis/Inception.ts b/packages/openai-adapters/src/apis/Inception.ts index 99795517a..71b9ceff6 100644 --- a/packages/openai-adapters/src/apis/Inception.ts +++ b/packages/openai-adapters/src/apis/Inception.ts @@ -1,10 +1,28 @@ import { streamSse } from "@continuedev/fetch"; -import { ChatCompletionChunk, Model } from "openai/resources/index"; +import { + ChatCompletion, + ChatCompletionChunk, + ChatCompletionCreateParamsNonStreaming, + ChatCompletionCreateParamsStreaming, + ChatCompletionMessageParam, + Model, +} from "openai/resources/index"; import { InceptionConfig } from "../types.js"; import { chatChunk, customFetch } from "../util.js"; import { OpenAIApi } from "./OpenAI.js"; import { FimCreateParamsStreaming } from "./base.js"; +// export type InceptionChatCompletionCreateParamsStreaming = +// ChatCompletionCreateParamsStreaming & { +// nextEdit?: boolean; +// }; + +// export type InceptionChatCompletionCreateParamsNonStreaming = +// ChatCompletionCreateParamsNonStreaming & { +// nextEdit?: boolean; +// }; + +export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>"; export const INCEPTION_API_BASE = "https://api.inceptionlabs.ai/v1/"; export class InceptionApi extends OpenAIApi { constructor(config: InceptionConfig) { @@ -15,6 +33,77 @@ export class InceptionApi extends OpenAIApi { }); } + // Add custom edit completions method + async *editCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const endpoint = new URL("chat/completions", this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: body.messages, + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + + for await (const chunk of streamSse(resp as any)) { + if (chunk.choices?.[0]?.delta?.content) { + yield chatChunk({ + content: chunk.choices[0].delta.content, + finish_reason: chunk.choices[0].finish_reason || null, + model: body.model, + }); + } + } + } + + // Override the regular chat method to route to edit endpoint for certain models + async *chatCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + // Cast to access the custom property + // const bodyWithNextEdit = + // body as InceptionChatCompletionCreateParamsStreaming; + // const { nextEdit, ...cleanBody } = bodyWithNextEdit; + + if (this.isNextEdit(body.messages)) { + body.messages = this.removeNextEditToken(body.messages); + yield* this.editCompletionStream(body, signal); + } else { + yield* super.chatCompletionStream(body, signal); + } + } + + async chatCompletionNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + // const bodyWithNextEdit = + // body as InceptionChatCompletionCreateParamsNonStreaming; + // const { nextEdit, ...cleanBody } = bodyWithNextEdit; + + if (this.isNextEdit(body.messages)) { + throw new Error("Non-streaming edit completions not yet implemented"); + } else { + return super.chatCompletionNonStream(body, signal); + } + } + async *fimStream( body: FimCreateParamsStreaming, signal: AbortSignal, @@ -56,4 +145,33 @@ export class InceptionApi extends OpenAIApi { list(): Promise { throw new Error("Method not implemented."); } + + private isNextEdit(messages: ChatCompletionMessageParam[]): boolean { + // Check if any message contains the unique next edit token. + return messages.some( + (message) => + typeof message.content === "string" && + message.content.endsWith(UNIQUE_TOKEN), + ); + } + + private removeNextEditToken( + messages: ChatCompletionMessageParam[], + ): ChatCompletionMessageParam[] { + const lastMessage = messages[messages.length - 1]; + + if ( + typeof lastMessage?.content === "string" && + lastMessage.content.endsWith(UNIQUE_TOKEN) + ) { + const cleanedMessages = [...messages]; + cleanedMessages[cleanedMessages.length - 1] = { + ...lastMessage, + content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), + }; + return cleanedMessages; + } + + return messages; + } } From 2efdf38a17ce923ec1c6afd4f6b1dbb921c76ef1 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 18 Aug 2025 18:52:08 -0700 Subject: [PATCH 3/8] feat: add mercury-coder specific constants --- core/nextEdit/constants.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 27a743dcc..377938071 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -8,6 +8,10 @@ export const MODEL_WINDOW_SIZES: Record< NEXT_EDIT_MODELS, { topMargin: number; bottomMargin: number } > = { + "mercury-coder": { + topMargin: 0, + bottomMargin: 5, + }, // mercury coder uses full file diff, so this should be unnecessary "mercury-coder-nextedit": { topMargin: 0, bottomMargin: 5, @@ -15,6 +19,8 @@ export const MODEL_WINDOW_SIZES: Record< instinct: { topMargin: 1, bottomMargin: 5 }, }; +export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>"; + // Model 1-specific tokens. export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; From 0358717d0646f9440a3d510f9ad93f0bd190fda0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 18 Aug 2025 18:52:56 -0700 Subject: [PATCH 4/8] feat: use enums instead of strings --- core/nextEdit/NextEditProvider.ts | 50 +++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0b525de4a..026592aaf 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -31,6 +31,7 @@ import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; import { myersDiff } from "../diff/myers.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 { @@ -38,6 +39,7 @@ import { MERCURY_CODE_TO_EDIT_OPEN, MERCURY_SYSTEM_PROMPT, MODEL_WINDOW_SIZES, + UNIQUE_TOKEN, } from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { @@ -392,9 +394,13 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); - const modelName = helper.modelName.includes("mercury-coder-nextedit") - ? "mercury-coder-nextedit" - : "instinct"; + 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; const { editableRegionStartLine, editableRegionEndLine } = opts?.usingFullFileDiff @@ -551,7 +557,10 @@ export class NextEditProvider { const modelName = helper.modelName; let ctx: any; - if (modelName.includes("mercury-coder-nextedit")) { + if ( + modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || + modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) + ) { ctx = { recentlyViewedCodeSnippets: snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ @@ -564,7 +573,7 @@ export class NextEditProvider { editDiffHistory: this.diffContext, currentFilePath: helper.filepath, }; - } else if (modelName.includes("instinct")) { + } 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( @@ -608,9 +617,11 @@ export class NextEditProvider { const systemPrompt: Prompt = { role: "system", - content: modelName.includes("mercury-coder-nextedit") - ? MERCURY_SYSTEM_PROMPT - : INSTINCT_SYSTEM_PROMPT, + 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]; @@ -677,7 +688,28 @@ export class NextEditProvider { const llm = await this._prepareLlm(); if (!llm) return undefined; - const msg: ChatMessage = await llm.chat(prompts, token); + // TODO: Check for mercury models, and inject some unique tokens so that + // the backend knows that mercury-coder is a next edit. + // TODO: Capture the unique tokens in llm Inception.ts and apis Inception.ts + // TODO: where does capabilities come in??? + // My best answer is that it's a non-mercury-specific way of determining if + // the model supports next edit. If it does, then we can inject the unique tokens. + + // Check for mercury models, and inject unique token for next edit. + 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. + // TODO: Check if there is an actual modification of prompts. + 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); console.log("message"); console.log(msg.content); From 1e7aeeabbcce8336e6283c054c7aa30abf055e74 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 18 Aug 2025 18:53:19 -0700 Subject: [PATCH 5/8] feat: add prompt generation templates for mercury-coder --- .../templating/NextEditPromptEngine.ts | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 98e23e45b..3ec20fb37 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -39,6 +39,9 @@ import { type TemplateRenderer = (vars: TemplateVars) => string; const NEXT_EDIT_MODEL_TEMPLATES: Record = { + "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\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, + }, "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\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, @@ -90,7 +93,7 @@ export async function renderPrompt( let tv: TemplateVars; switch (modelName) { - case "mercury-coder-nextedit": { + case NEXT_EDIT_MODELS.MERCURY_CODER: { userEdits = ctx.editDiffHistory; // editedCodeWithTokens = insertTokens( @@ -119,7 +122,36 @@ export async function renderPrompt( break; } - case "instinct": { + 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( From 14e73dd6ade165fc2f68c8abebdf1f5df284329c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 18 Aug 2025 21:53:53 -0700 Subject: [PATCH 6/8] feat: only send user prompt --- core/nextEdit/NextEditProvider.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 026592aaf..e6634896f 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -709,7 +709,9 @@ export class NextEditProvider { } } - const msg: ChatMessage = await llm.chat([prompts[1]], token); + const msg: ChatMessage = await llm.chat([prompts[1]], token, { + stream: false, + }); console.log("message"); console.log(msg.content); From 60d0056a128add93eeec827bd2595c164257764e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 18 Aug 2025 21:55:33 -0700 Subject: [PATCH 7/8] feat: add a non-stream method --- .../openai-adapters/src/apis/Inception.ts | 53 ++++++++++++++----- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/packages/openai-adapters/src/apis/Inception.ts b/packages/openai-adapters/src/apis/Inception.ts index 71b9ceff6..e32694277 100644 --- a/packages/openai-adapters/src/apis/Inception.ts +++ b/packages/openai-adapters/src/apis/Inception.ts @@ -33,12 +33,12 @@ export class InceptionApi extends OpenAIApi { }); } - // Add custom edit completions method + // Add custom edit completions method. async *editCompletionStream( body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { - const endpoint = new URL("chat/completions", this.apiBase); + const endpoint = new URL("edit/completions", this.apiBase); const resp = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify({ @@ -71,16 +71,42 @@ export class InceptionApi extends OpenAIApi { } } - // Override the regular chat method to route to edit endpoint for certain models + // Add custom edit completions method (non-streaming). + async editCompletionNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + const endpoint = new URL("edit/completions", this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: body.messages, + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: false, // Set to false for non-streaming + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + + const data = await resp.json(); + return data as ChatCompletion; + } + + // Override the regular chat stream method to route to edit endpoint for next edit requests. async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { - // Cast to access the custom property - // const bodyWithNextEdit = - // body as InceptionChatCompletionCreateParamsStreaming; - // const { nextEdit, ...cleanBody } = bodyWithNextEdit; - if (this.isNextEdit(body.messages)) { body.messages = this.removeNextEditToken(body.messages); yield* this.editCompletionStream(body, signal); @@ -89,16 +115,14 @@ export class InceptionApi extends OpenAIApi { } } + // Override the regular chat non stream method to route to edit endpoint for next edit requests. async chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, ): Promise { - // const bodyWithNextEdit = - // body as InceptionChatCompletionCreateParamsNonStreaming; - // const { nextEdit, ...cleanBody } = bodyWithNextEdit; - if (this.isNextEdit(body.messages)) { - throw new Error("Non-streaming edit completions not yet implemented"); + body.messages = this.removeNextEditToken(body.messages); + return this.editCompletionNonStream(body, signal); } else { return super.chatCompletionNonStream(body, signal); } @@ -146,8 +170,8 @@ export class InceptionApi extends OpenAIApi { throw new Error("Method not implemented."); } + // Check if any message contains the unique next edit token. private isNextEdit(messages: ChatCompletionMessageParam[]): boolean { - // Check if any message contains the unique next edit token. return messages.some( (message) => typeof message.content === "string" && @@ -155,6 +179,7 @@ export class InceptionApi extends OpenAIApi { ); } + // Remove the unique token from messages. private removeNextEditToken( messages: ChatCompletionMessageParam[], ): ChatCompletionMessageParam[] { From c766bb060b7d4d2c7bb82a22676a458de518dc51 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 19 Aug 2025 00:22:35 -0700 Subject: [PATCH 8/8] feat: fix the next edit provider to use the new edit endpoint (#7233) * feat: handle new model output format * feat: remove trailing user prompt --- core/nextEdit/NextEditProvider.ts | 32 ++++++------------- .../templating/NextEditPromptEngine.ts | 4 +-- 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index e6634896f..c3bc079d1 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -36,7 +36,6 @@ import { countTokens } from "../llm/countTokens.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { INSTINCT_SYSTEM_PROMPT, - MERCURY_CODE_TO_EDIT_OPEN, MERCURY_SYSTEM_PROMPT, MODEL_WINDOW_SIZES, UNIQUE_TOKEN, @@ -688,21 +687,14 @@ export class NextEditProvider { const llm = await this._prepareLlm(); if (!llm) return undefined; - // TODO: Check for mercury models, and inject some unique tokens so that - // the backend knows that mercury-coder is a next edit. - // TODO: Capture the unique tokens in llm Inception.ts and apis Inception.ts - // TODO: where does capabilities come in??? - // My best answer is that it's a non-mercury-specific way of determining if - // the model supports next edit. If it does, then we can inject the unique tokens. - // 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. - // TODO: Check if there is an actual modification of prompts. const lastPrompt = prompts[prompts.length - 1]; if (lastPrompt && typeof lastPrompt.content === "string") { lastPrompt.content += UNIQUE_TOKEN; @@ -712,24 +704,20 @@ export class NextEditProvider { const msg: ChatMessage = await llm.chat([prompts[1]], token, { stream: false, }); - console.log("message"); - console.log(msg.content); if (typeof msg.content !== "string") { return undefined; } - // const nextCompletion = msg.content.split( - // `${MERCURY_CODE_TO_EDIT_OPEN}\n`, - // )[1] - // ? replaceEscapedCharacters( - // msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1], - // ).replace(/\n$/, "") - // : replaceEscapedCharacters(msg.content); - const nextCompletion = - msg.content - .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1] - .replace(/\n$/, "") ?? msg.content; + // 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( diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 3ec20fb37..a8f8b32b9 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -40,10 +40,10 @@ type TemplateRenderer = (vars: TemplateVars) => string; const NEXT_EDIT_MODEL_TEMPLATES: Record = { "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\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, + 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\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, + 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 Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,