Merge branch 'main' into nate/clean-gui
This commit is contained in:
commit
d43af15aa8
340 changed files with 21135 additions and 4384 deletions
9
.continue/rules/continue-pun.md
Normal file
9
.continue/rules/continue-pun.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
name: Add Continue pun easter eggs
|
||||
description: Adds an easter egg whenever the "continue" keyword
|
||||
pattern: "continue"
|
||||
---
|
||||
|
||||
Our product name is "Continue", so whenever the "continue" statement is used in our codebase, you should add a comment joking about the use of the continue keyword in the Continue codebase
|
||||
|
||||
Do not add a comment if the use of "continue" is not in a code continue statement
|
||||
5
.continue/rules/css-units.md
Normal file
5
.continue/rules/css-units.md
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
globs: "gui/**/*.tsx"
|
||||
---
|
||||
|
||||
You should try to use the `rem` CSS unit whenever possible for scalability instead of `px`.
|
||||
8
.continue/rules/edit-aggregator-singleton-rule.md
Normal file
8
.continue/rules/edit-aggregator-singleton-rule.md
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
---
|
||||
patterns: ["EditAggregator", "processEdit"]
|
||||
glob: "**/*.tsx"
|
||||
name: "Enforce EditAggregator Singleton"
|
||||
description: "Ensure that EditAggregator is used as a singleton in the codebase."
|
||||
---
|
||||
|
||||
When you encounter usage of EditAggregator, be sure that this is compatible with the singleton nature of the EditAggregator class. If you are creating a new instance of EditAggregator, you should instead use the existing singleton. Refer to the `aggregateEdits.ts` to examine how the singleton pattern is used. Do not create a new instance of EditAggregator.
|
||||
3
.github/workflows/cla.yaml
vendored
3
.github/workflows/cla.yaml
vendored
|
|
@ -26,5 +26,6 @@ jobs:
|
|||
path-to-signatures: "signatures/version1/cla.json"
|
||||
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
|
||||
branch: cla-signatures
|
||||
allowlist: dependabot[bot]
|
||||
# Bots and CLAs signed outside of GitHub
|
||||
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline
|
||||
signed-commit-message: "CLA signed in $pullRequestNo"
|
||||
|
|
|
|||
16
.github/workflows/jetbrains-release.yaml
vendored
16
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -167,20 +167,8 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build and check config-yaml
|
||||
run: |
|
||||
cd ../../packages/config-yaml
|
||||
npm i
|
||||
npx tsc --noEmit
|
||||
# Tests are currently failing, commenting out for now
|
||||
# npm test
|
||||
npm run build
|
||||
- name: Build packages (Unix)
|
||||
run: ./scripts/build-packages.sh
|
||||
|
||||
# npm install core
|
||||
- name: Install core node_modules
|
||||
|
|
|
|||
27
.vscode/launch.json
vendored
27
.vscode/launch.json
vendored
|
|
@ -19,6 +19,7 @@
|
|||
"pauseForSourceMap": false,
|
||||
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
|
||||
"preLaunchTask": "vscode-extension:build",
|
||||
"postDebugTask": "Terminate All Tasks",
|
||||
"env": {
|
||||
// "CONTROL_PLANE_ENV": "local",
|
||||
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
|
||||
|
|
@ -73,32 +74,6 @@
|
|||
"sourceMaps": true
|
||||
// "preLaunchTask": "gui:dev"
|
||||
},
|
||||
// Has to be run after starting the server (separately or using the compound configuration)
|
||||
{
|
||||
"name": "Run tests",
|
||||
"type": "extensionHost",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}/extensions/vscode",
|
||||
"runtimeExecutable": "${execPath}",
|
||||
"args": [
|
||||
// Pass a directory to run tests in
|
||||
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox",
|
||||
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode",
|
||||
"--extensionTestsPath=${workspaceFolder}/extensions/vscode/out/test/runner/mochaRunner"
|
||||
],
|
||||
"outFiles": [
|
||||
// Allows setting breakpoints in test suites across the /src folder
|
||||
"${workspaceFolder}/extensions/vscode/out/test/test-suites/**/*.js",
|
||||
// Allows setting breakpoints in mocha test runner file
|
||||
"${workspaceFolder}/extensions/vscode/out/test/runner/**/*.js"
|
||||
],
|
||||
"internalConsoleOptions": "openOnSessionStart",
|
||||
"preLaunchTask": "vscode-extension:tests:build",
|
||||
"env": {
|
||||
// Avoid timing out when stopping on breakpoints during debugging in VSCode
|
||||
"MOCHA_TIMEOUT": "0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "[Core] Jest Test Debugger, Current Open File",
|
||||
"type": "node",
|
||||
|
|
|
|||
46
.vscode/tasks.json
vendored
46
.vscode/tasks.json
vendored
|
|
@ -109,39 +109,6 @@
|
|||
"cwd": "${workspaceFolder}/extensions/vscode"
|
||||
}
|
||||
},
|
||||
//
|
||||
// Compile and bundle tests
|
||||
{
|
||||
"label": "vscode-extension:tests:build",
|
||||
"dependsOn": [
|
||||
// Build the extension
|
||||
"vscode-extension:build",
|
||||
// To detect compile errors - this type checks both the extension and the tests
|
||||
"tsc:watch",
|
||||
"vscode-extension:tests:esbuild"
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "vscode-extension:tests:esbuild",
|
||||
"type": "npm",
|
||||
"script": "build-test",
|
||||
"path": "extensions/vscode",
|
||||
"problemMatcher": [
|
||||
{
|
||||
"pattern": [
|
||||
{
|
||||
"regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$",
|
||||
"file": 1,
|
||||
"line": 2,
|
||||
"column": 3,
|
||||
"severity": 4,
|
||||
"message": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
//
|
||||
// Install or update all dependencies for all projects in the monrepo
|
||||
{
|
||||
"label": "install-all-dependencies",
|
||||
|
|
@ -256,6 +223,19 @@
|
|||
],
|
||||
"type": "shell",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "Terminate All Tasks",
|
||||
"command": "${input:terminate}",
|
||||
"type": "shell"
|
||||
}
|
||||
],
|
||||
"inputs": [
|
||||
{
|
||||
"id": "terminate",
|
||||
"type": "command",
|
||||
"command": "workbench.action.tasks.terminate",
|
||||
"args": "terminateAll"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
1
binary/package-lock.json
generated
1
binary/package-lock.json
generated
|
|
@ -144,6 +144,7 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"shiki": "^3.6.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
|
|
|
|||
|
|
@ -6,12 +6,36 @@ import {
|
|||
} from "../filtering/streamTransforms/lineStream";
|
||||
|
||||
export interface AutocompleteLanguageInfo {
|
||||
/**
|
||||
* The display name of the language
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Keywords that show up at the top-level of files. We often use these as stop words or soft breaks
|
||||
*/
|
||||
topLevelKeywords: string[];
|
||||
/**
|
||||
* The character that prefixes a single line comment
|
||||
* We use this to format snippets from other files as large comment blocks
|
||||
*/
|
||||
singleLineComment?: string;
|
||||
/**
|
||||
* Semi-colon or other end of line indicator that may be used as a stop char
|
||||
* or other parsing
|
||||
*/
|
||||
endOfLine: string[];
|
||||
/**
|
||||
* Strings that indicate we should filter out a line from completion
|
||||
* Primarily currently used for .ipynb files
|
||||
*/
|
||||
lineFilters?: LineFilter[];
|
||||
/**
|
||||
* Similar to line filters, but characters. I think.
|
||||
*/
|
||||
charFilters?: CharacterFilter[];
|
||||
/**
|
||||
* Function that allows cusotmization of whether to use a multi-line completion on a per-language and completion basis
|
||||
*/
|
||||
useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
|
||||
}
|
||||
|
||||
|
|
@ -23,6 +47,14 @@ export const Typescript = {
|
|||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// JavaScript
|
||||
export const JavaScript = {
|
||||
name: "JavaScript",
|
||||
topLevelKeywords: ["function", "class", "module", "export", "import"],
|
||||
singleLineComment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// Python
|
||||
export const Python = {
|
||||
name: "Python",
|
||||
|
|
@ -336,7 +368,7 @@ export const Markdown: AutocompleteLanguageInfo = {
|
|||
|
||||
export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
||||
ts: Typescript,
|
||||
js: Typescript,
|
||||
js: JavaScript,
|
||||
tsx: Typescript,
|
||||
json: Json,
|
||||
jsx: Typescript,
|
||||
|
|
|
|||
|
|
@ -70,4 +70,20 @@ export class ContextRetrievalService {
|
|||
helper.treePath,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the import definitions cache for a file.
|
||||
* This is normally done automatically when the active text editor changes,
|
||||
* but needs to be called manually when using context fetching outside the normal flow.
|
||||
*/
|
||||
public async initializeForFile(filepath: string): Promise<void> {
|
||||
try {
|
||||
await (this.importDefinitionsService as any).cache.initKey(filepath);
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`Failed to initialize import definitions cache for ${filepath}:`,
|
||||
e,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -132,6 +132,14 @@ export function postprocessCompletion({
|
|||
completion = "\n" + completion;
|
||||
}
|
||||
|
||||
if (
|
||||
(llm.model.includes("gemini") || llm.model.includes("gemma")) &&
|
||||
completion.endsWith("<|file_separator|>")
|
||||
) {
|
||||
// "<|file_separator|>" is 18 characters long
|
||||
completion = completion.slice(0, -18);
|
||||
}
|
||||
|
||||
// If prefix ends with space and so does completion, then remove the space from completion
|
||||
|
||||
if (prefix.endsWith(" ") && completion.startsWith(" ")) {
|
||||
|
|
|
|||
|
|
@ -209,3 +209,47 @@ export const getAllSnippets = async ({
|
|||
recentlyOpenedFileSnippets,
|
||||
};
|
||||
};
|
||||
|
||||
export const getAllSnippetsWithoutRace = async ({
|
||||
helper,
|
||||
ide,
|
||||
getDefinitionsFromLsp,
|
||||
contextRetrievalService,
|
||||
}: {
|
||||
helper: HelperVars;
|
||||
ide: IDE;
|
||||
getDefinitionsFromLsp: GetLspDefinitionsFunction;
|
||||
contextRetrievalService: ContextRetrievalService;
|
||||
}): Promise<SnippetPayload> => {
|
||||
const recentlyEditedRangeSnippets =
|
||||
getSnippetsFromRecentlyEditedRanges(helper);
|
||||
|
||||
const [
|
||||
rootPathSnippets,
|
||||
importDefinitionSnippets,
|
||||
ideSnippets,
|
||||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyOpenedFileSnippets,
|
||||
] = await Promise.all([
|
||||
contextRetrievalService.getRootPathSnippets(helper),
|
||||
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
|
||||
IDE_SNIPPETS_ENABLED
|
||||
? getIdeSnippets(helper, ide, getDefinitionsFromLsp)
|
||||
: [],
|
||||
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
|
||||
getClipboardSnippets(ide),
|
||||
getSnippetsFromRecentlyOpenedFiles(helper, ide),
|
||||
]);
|
||||
|
||||
return {
|
||||
rootPathSnippets,
|
||||
importDefinitionSnippets,
|
||||
ideSnippets,
|
||||
recentlyEditedRangeSnippets,
|
||||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
|
||||
recentlyOpenedFileSnippets,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
272
core/codeRenderer/CodeRenderer.ts
Normal file
272
core/codeRenderer/CodeRenderer.ts
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
/**
|
||||
* CodeRenderer is a class that, when given a code string,
|
||||
* highlights the code string using shiki and
|
||||
* returns a svg representation of it.
|
||||
* We could technically just call shiki's methods to do a
|
||||
* one-liner syntax highlighting code, but
|
||||
* a separate class for this is useful because
|
||||
* we rarely ever need syntax highlighting outside of
|
||||
* creating a render of it.
|
||||
*/
|
||||
import { JSDOM } from "jsdom";
|
||||
import { BundledTheme, codeToHtml, getSingletonHighlighter } from "shiki";
|
||||
import { escapeForSVG, kebabOfStr } from "../util/text";
|
||||
|
||||
interface CodeRendererOptions {
|
||||
themesDir?: string;
|
||||
theme?: string;
|
||||
}
|
||||
|
||||
interface HTMLOptions {
|
||||
theme?: string;
|
||||
customCSS?: string;
|
||||
containerClass?: string;
|
||||
}
|
||||
|
||||
interface ConversionOptions extends HTMLOptions {
|
||||
transparent?: boolean;
|
||||
imageType: "svg";
|
||||
}
|
||||
|
||||
interface Dimensions {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
type DataUri = PngUri | SvgUri;
|
||||
type PngUri = string;
|
||||
type SvgUri = string;
|
||||
|
||||
export class CodeRenderer {
|
||||
private static instance: CodeRenderer;
|
||||
private currentTheme: string = "dark-plus";
|
||||
private editorBackground: string = "#000000";
|
||||
private editorForeground: string = "#FFFFFF";
|
||||
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): CodeRenderer {
|
||||
if (!CodeRenderer.instance) {
|
||||
CodeRenderer.instance = new CodeRenderer();
|
||||
}
|
||||
return CodeRenderer.instance;
|
||||
}
|
||||
|
||||
public async setTheme(themeName: string): Promise<void> {
|
||||
if (
|
||||
this.themeExists(kebabOfStr(themeName)) ||
|
||||
themeName === "Default Dark Modern"
|
||||
) {
|
||||
this.currentTheme =
|
||||
themeName === "Default Dark Modern"
|
||||
? "dark-plus"
|
||||
: kebabOfStr(themeName);
|
||||
|
||||
const highlighter = await getSingletonHighlighter({
|
||||
themes: [this.currentTheme],
|
||||
});
|
||||
|
||||
const th = highlighter.getTheme(this.currentTheme);
|
||||
this.editorBackground = th.bg;
|
||||
this.editorForeground = th.fg;
|
||||
} else {
|
||||
this.currentTheme = "dark-plus";
|
||||
}
|
||||
}
|
||||
|
||||
async init(): Promise<void> {}
|
||||
|
||||
async close(): Promise<void> {}
|
||||
|
||||
themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
|
||||
const themeArray: BundledTheme[] = [
|
||||
"andromeeda",
|
||||
"aurora-x",
|
||||
"ayu-dark",
|
||||
"catppuccin-frappe",
|
||||
"catppuccin-latte",
|
||||
"catppuccin-macchiato",
|
||||
"catppuccin-mocha",
|
||||
"dark-plus",
|
||||
"dracula",
|
||||
"dracula-soft",
|
||||
"everforest-dark",
|
||||
"everforest-light",
|
||||
"github-dark",
|
||||
"github-dark-default",
|
||||
"github-dark-dimmed",
|
||||
"github-dark-high-contrast",
|
||||
"github-light",
|
||||
"github-light-default",
|
||||
"github-light-high-contrast",
|
||||
"gruvbox-dark-hard",
|
||||
"gruvbox-dark-medium",
|
||||
"gruvbox-dark-soft",
|
||||
"gruvbox-light-hard",
|
||||
"gruvbox-light-medium",
|
||||
"gruvbox-light-soft",
|
||||
"houston",
|
||||
"kanagawa-dragon",
|
||||
"kanagawa-lotus",
|
||||
"kanagawa-wave",
|
||||
"laserwave",
|
||||
"light-plus",
|
||||
"material-theme",
|
||||
"material-theme-darker",
|
||||
"material-theme-lighter",
|
||||
"material-theme-ocean",
|
||||
"material-theme-palenight",
|
||||
"min-dark",
|
||||
"min-light",
|
||||
"monokai",
|
||||
"night-owl",
|
||||
"nord",
|
||||
"one-dark-pro",
|
||||
"one-light",
|
||||
"plastic",
|
||||
"poimandres",
|
||||
"red",
|
||||
"rose-pine",
|
||||
"rose-pine-dawn",
|
||||
"rose-pine-moon",
|
||||
"slack-dark",
|
||||
"slack-ochin",
|
||||
"snazzy-light",
|
||||
"solarized-dark",
|
||||
"solarized-light",
|
||||
"synthwave-84",
|
||||
"tokyo-night",
|
||||
"vesper",
|
||||
"vitesse-black",
|
||||
"vitesse-dark",
|
||||
"vitesse-light",
|
||||
];
|
||||
|
||||
return themeArray.includes(themeNameKebab as BundledTheme);
|
||||
}
|
||||
|
||||
async highlightCode(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
): Promise<string> {
|
||||
return await codeToHtml(code, {
|
||||
lang: language,
|
||||
theme: this.currentTheme,
|
||||
});
|
||||
}
|
||||
|
||||
async convertToSVG(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
dimensions: Dimensions,
|
||||
lineHeight: number,
|
||||
options: ConversionOptions,
|
||||
): Promise<Buffer> {
|
||||
const highlightedCodeHtml = await this.highlightCode(code, language);
|
||||
|
||||
const guts = this.convertShikiHtmlToSvgGut(
|
||||
highlightedCodeHtml,
|
||||
fontSize,
|
||||
fontFamily,
|
||||
lineHeight,
|
||||
);
|
||||
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
|
||||
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}">
|
||||
<g>
|
||||
<rect width="${dimensions.width}" height="${dimensions.height}" fill="${backgroundColor}" stroke="${this.editorForeground}" stroke-width="1" />
|
||||
${guts}
|
||||
</g>
|
||||
</svg>`;
|
||||
|
||||
return Buffer.from(svg, "utf8");
|
||||
}
|
||||
|
||||
convertShikiHtmlToSvgGut(
|
||||
shikiHtml: string,
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
lineHeight: number,
|
||||
): string {
|
||||
const dom = new JSDOM(shikiHtml);
|
||||
const document = dom.window.document;
|
||||
|
||||
const lines = Array.from(document.querySelectorAll(".line"));
|
||||
const svgLines = lines.map((line, index) => {
|
||||
const spans = Array.from(line.childNodes)
|
||||
.map((node) => {
|
||||
if (node.nodeType === 3) {
|
||||
return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
|
||||
}
|
||||
|
||||
const el = node as HTMLElement;
|
||||
const style = el.getAttribute("style") || "";
|
||||
const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
|
||||
const fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
|
||||
const content = el.textContent || "";
|
||||
return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
const y = (index + 1) * lineHeight;
|
||||
return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve">${spans}</text>`;
|
||||
});
|
||||
|
||||
return `
|
||||
${svgLines.join("\n")}
|
||||
`.trim();
|
||||
}
|
||||
|
||||
getBackgroundColor(shikiHtml: string): string {
|
||||
const dom = new JSDOM(shikiHtml);
|
||||
const document = dom.window.document;
|
||||
|
||||
const preElement = document.querySelector("pre");
|
||||
let backgroundColor = "#333333"; // Default white background
|
||||
if (preElement) {
|
||||
const style = preElement.getAttribute("style") || "";
|
||||
const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
|
||||
if (bgColorMatch) {
|
||||
backgroundColor = bgColorMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
return backgroundColor;
|
||||
}
|
||||
|
||||
async getDataUri(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
dimensions: Dimensions,
|
||||
lineHeight: number,
|
||||
options: ConversionOptions,
|
||||
): Promise<DataUri> {
|
||||
switch (options.imageType) {
|
||||
// case "png":
|
||||
// const pngBuffer = await this.convertToPNG(
|
||||
// code,
|
||||
// language,
|
||||
// fontSize,
|
||||
// dimensions,
|
||||
// lineHeight,
|
||||
// options,
|
||||
// );
|
||||
// return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
|
||||
case "svg":
|
||||
const svgBuffer = await this.convertToSVG(
|
||||
code,
|
||||
language,
|
||||
fontSize,
|
||||
fontFamily,
|
||||
dimensions,
|
||||
lineHeight,
|
||||
options,
|
||||
);
|
||||
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
|
||||
import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
|
||||
import { renderChatMessage } from "../util/messageContent";
|
||||
|
||||
import SlashCommands from "./slash";
|
||||
|
||||
export function slashFromCustomCommand(
|
||||
customCommand: CustomCommand,
|
||||
): SlashCommand {
|
||||
const commandName = customCommand.name.startsWith("/")
|
||||
? customCommand.name.substring(1)
|
||||
: customCommand.name;
|
||||
return {
|
||||
name: commandName,
|
||||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
run: async function* ({
|
||||
input,
|
||||
llm,
|
||||
history,
|
||||
ide,
|
||||
completionOptions,
|
||||
config,
|
||||
selectedCode,
|
||||
fetch,
|
||||
abortController,
|
||||
}) {
|
||||
// Render prompt template
|
||||
let renderedPrompt: string;
|
||||
if (customCommand.prompt.includes("{{{ input }}}")) {
|
||||
renderedPrompt = await renderTemplatedString(
|
||||
customCommand.prompt,
|
||||
ide.readFile.bind(ide),
|
||||
{ input },
|
||||
);
|
||||
} else {
|
||||
const renderedPromptFile = await renderPromptFileV2(
|
||||
customCommand.prompt,
|
||||
{
|
||||
config,
|
||||
llm,
|
||||
ide,
|
||||
selectedCode,
|
||||
fetch,
|
||||
fullInput: input,
|
||||
embeddingsProvider: config.modelsByRole.embed[0],
|
||||
reranker: config.modelsByRole.rerank[0],
|
||||
},
|
||||
);
|
||||
|
||||
renderedPrompt = renderedPromptFile[1];
|
||||
}
|
||||
|
||||
// Replaces slash command messages with the rendered prompt
|
||||
// which INCLUDES the input
|
||||
const messages = replaceSlashCommandWithPromptInChatHistory(
|
||||
history,
|
||||
commandName,
|
||||
renderedPrompt,
|
||||
undefined,
|
||||
);
|
||||
|
||||
for await (const chunk of llm.streamChat(
|
||||
messages,
|
||||
abortController.signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function slashCommandFromDescription(
|
||||
desc: SlashCommandDescription,
|
||||
): SlashCommand | undefined {
|
||||
const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
|
||||
if (!cmd) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
...cmd,
|
||||
params: desc.params,
|
||||
description: desc.description ?? cmd.description,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { streamLines } from "../../diff/util.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../util/index.js";
|
||||
import { streamLines } from "../../../diff/util.js";
|
||||
import { SlashCommand } from "../../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../../util/index.js";
|
||||
|
||||
function commandIsPotentiallyDangerous(command: string) {
|
||||
return (
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { SlashCommand } from "../../../index.js";
|
||||
import { renderChatMessage } from "../../../util/messageContent.js";
|
||||
|
||||
const CommitMessageCommand: SlashCommand = {
|
||||
name: "commit",
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../util/index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { ChatMessage, SlashCommand } from "../../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../../util/index.js";
|
||||
import { renderChatMessage } from "../../../util/messageContent.js";
|
||||
|
||||
const PROMPT = (
|
||||
input: string,
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { streamResponse } from "@continuedev/fetch";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../util/index.js";
|
||||
import { SlashCommand } from "../../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../../util/index.js";
|
||||
|
||||
const HttpSlashCommand: SlashCommand = {
|
||||
name: "http",
|
||||
37
core/commands/slash/built-in-legacy/index.ts
Normal file
37
core/commands/slash/built-in-legacy/index.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import {
|
||||
SlashCommand,
|
||||
SlashCommandDescription,
|
||||
SlashCommandWithSource,
|
||||
} from "../../..";
|
||||
import GenerateTerminalCommand from "./cmd";
|
||||
import CommitMessageCommand from "./commit";
|
||||
import DraftIssueCommand from "./draftIssue";
|
||||
import HttpSlashCommand from "./http";
|
||||
import OnboardSlashCommand from "./onboard";
|
||||
import ReviewMessageCommand from "./review";
|
||||
import ShareSlashCommand from "./share";
|
||||
|
||||
const LegacyBuiltInSlashCommands: SlashCommand[] = [
|
||||
DraftIssueCommand,
|
||||
ShareSlashCommand,
|
||||
GenerateTerminalCommand,
|
||||
HttpSlashCommand,
|
||||
CommitMessageCommand,
|
||||
ReviewMessageCommand,
|
||||
OnboardSlashCommand,
|
||||
];
|
||||
|
||||
export function getLegacyBuiltInSlashCommandFromDescription(
|
||||
desc: SlashCommandDescription,
|
||||
): SlashCommandWithSource | undefined {
|
||||
const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name);
|
||||
if (!cmd) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
...cmd,
|
||||
params: desc.params,
|
||||
description: desc.description ?? cmd.description,
|
||||
source: "built-in-legacy",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +1,17 @@
|
|||
import ignore from "ignore";
|
||||
|
||||
import type { FileType, IDE, SlashCommand } from "../..";
|
||||
import type { FileType, IDE, SlashCommand } from "../../..";
|
||||
import {
|
||||
DEFAULT_IGNORE,
|
||||
getGlobalContinueIgArray,
|
||||
gitIgArrayFromFile,
|
||||
} from "../../indexing/ignore";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
} from "../../../indexing/ignore";
|
||||
import { renderChatMessage } from "../../../util/messageContent";
|
||||
import {
|
||||
findUriInDirs,
|
||||
getUriPathBasename,
|
||||
joinPathsToUri,
|
||||
} from "../../util/uri";
|
||||
} from "../../../util/uri";
|
||||
|
||||
const LANGUAGE_DEP_MGMT_FILENAMES = [
|
||||
"package.json", // JavaScript (Node.js)
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { ChatMessage, SlashCommand } from "../../../index.js";
|
||||
import { renderChatMessage } from "../../../util/messageContent.js";
|
||||
|
||||
const prompt = `
|
||||
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
|
||||
|
|
@ -3,10 +3,10 @@ import { homedir } from "node:os";
|
|||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import path from "path";
|
||||
|
||||
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { getContinueGlobalPath } from "../../util/paths.js";
|
||||
import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
|
||||
import { SlashCommand } from "../../../index.js";
|
||||
import { renderChatMessage } from "../../../util/messageContent.js";
|
||||
import { getContinueGlobalPath } from "../../../util/paths.js";
|
||||
|
||||
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
|
||||
function getOffsetDatetime(date: Date): Date {
|
||||
15
core/commands/slash/customSlashCommand.ts
Normal file
15
core/commands/slash/customSlashCommand.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { CustomCommand, SlashCommandWithSource } from "../..";
|
||||
|
||||
export function convertCustomCommandToSlashCommand(
|
||||
customCommand: CustomCommand,
|
||||
): SlashCommandWithSource {
|
||||
const commandName = customCommand.name.startsWith("/")
|
||||
? customCommand.name.substring(1)
|
||||
: customCommand.name;
|
||||
return {
|
||||
name: commandName,
|
||||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
source: "json-custom-command",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
import GenerateTerminalCommand from "./cmd";
|
||||
import CommitMessageCommand from "./commit";
|
||||
import DraftIssueCommand from "./draftIssue";
|
||||
import HttpSlashCommand from "./http";
|
||||
import OnboardSlashCommand from "./onboard";
|
||||
import ReviewMessageCommand from "./review";
|
||||
import ShareSlashCommand from "./share";
|
||||
|
||||
export default [
|
||||
DraftIssueCommand,
|
||||
ShareSlashCommand,
|
||||
GenerateTerminalCommand,
|
||||
HttpSlashCommand,
|
||||
CommitMessageCommand,
|
||||
ReviewMessageCommand,
|
||||
OnboardSlashCommand,
|
||||
];
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
export function constructMcpSlashCommand(
|
||||
client: Client,
|
||||
name: string,
|
||||
description?: string,
|
||||
args?: string[],
|
||||
): SlashCommand {
|
||||
return {
|
||||
name,
|
||||
description: description ?? "MCP Prompt",
|
||||
params: {},
|
||||
run: async function* (context) {
|
||||
const argsObject: { [key: string]: string } = {};
|
||||
const userInput = context.input.split(" ").slice(1).join(" ");
|
||||
if (args) {
|
||||
args.forEach((arg, i) => {
|
||||
argsObject[arg] = ""; // userInput
|
||||
});
|
||||
}
|
||||
|
||||
const result = await client.getPrompt({ name, arguments: argsObject });
|
||||
const mcpMessages: PromptMessage[] = result.messages;
|
||||
const messages: ChatMessage[] = mcpMessages.map((msg) => {
|
||||
if (msg.content.type !== "text") {
|
||||
throw new Error(
|
||||
"Continue currently only supports text prompts through MCP",
|
||||
);
|
||||
}
|
||||
return {
|
||||
content: msg.content.text,
|
||||
role: msg.role,
|
||||
};
|
||||
});
|
||||
|
||||
if (messages.length === 0) {
|
||||
yield "The MCP prompt returned no messages";
|
||||
return;
|
||||
}
|
||||
|
||||
if (userInput) {
|
||||
const lastMessage = messages.at(-1);
|
||||
if (!lastMessage || lastMessage.role !== "user") {
|
||||
messages.push({
|
||||
role: "user",
|
||||
content: userInput,
|
||||
});
|
||||
} else {
|
||||
let newContent = renderChatMessage(lastMessage);
|
||||
if (newContent) {
|
||||
newContent += "\n\n";
|
||||
}
|
||||
newContent += userInput;
|
||||
lastMessage.content = newContent;
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
context.abortController.signal,
|
||||
context.completionOptions,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
34
core/commands/slash/mcpSlashCommand.ts
Normal file
34
core/commands/slash/mcpSlashCommand.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { SlashCommandWithSource } from "../../index.js";
|
||||
|
||||
export function constructMcpSlashCommand(
|
||||
client: Client,
|
||||
name: string,
|
||||
description?: string,
|
||||
args?: string[],
|
||||
): SlashCommandWithSource {
|
||||
return {
|
||||
name,
|
||||
description: description ?? "MCP Prompt",
|
||||
source: "mcp-prompt",
|
||||
params: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function stringifyMcpPrompt(
|
||||
prompt: Awaited<ReturnType<typeof Client.prototype.getPrompt>>,
|
||||
): string {
|
||||
const { messages } = prompt;
|
||||
let stringified = "";
|
||||
for (const message of messages) {
|
||||
if (message.content.type === "text") {
|
||||
stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`;
|
||||
} else {
|
||||
console.warn(
|
||||
`MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return stringified;
|
||||
}
|
||||
13
core/commands/slash/promptBlockSlashCommand.ts
Normal file
13
core/commands/slash/promptBlockSlashCommand.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { Prompt } from "@continuedev/config-yaml";
|
||||
import { SlashCommandWithSource } from "../..";
|
||||
|
||||
export function convertPromptBlockToSlashCommand(
|
||||
prompt: Prompt,
|
||||
): SlashCommandWithSource {
|
||||
return {
|
||||
name: prompt.name,
|
||||
description: prompt.description ?? "",
|
||||
prompt: prompt.prompt,
|
||||
source: "yaml-prompt-block",
|
||||
};
|
||||
}
|
||||
21
core/commands/slash/promptFileSlashCommand.ts
Normal file
21
core/commands/slash/promptFileSlashCommand.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { SlashCommandWithSource } from "../..";
|
||||
import { parsePromptFile } from "../../promptFiles/parsePromptFile";
|
||||
|
||||
export function slashCommandFromPromptFile(
|
||||
path: string,
|
||||
content: string,
|
||||
): SlashCommandWithSource | null {
|
||||
const { name, description, systemMessage, prompt, version } = parsePromptFile(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
prompt,
|
||||
source: version === 1 ? "prompt-file-v1" : "prompt-file-v2",
|
||||
promptFile: path,
|
||||
overrideSystemMessage: systemMessage,
|
||||
};
|
||||
}
|
||||
|
|
@ -16,7 +16,7 @@ export function rifWithContentsToContextItem(
|
|||
return {
|
||||
content: rif.contents,
|
||||
name: `${basename} ${rangeStr}`,
|
||||
description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
|
||||
description: `${relativePathOrBasename} ${rangeStr}`,
|
||||
id: {
|
||||
providerTitle: "code",
|
||||
itemId: uuidv4(),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { testConfigHandler } from "../test/fixtures";
|
||||
import { TEST_DIR } from "../test/testDir";
|
||||
import { getConfigTsPath } from "../util/paths";
|
||||
|
|
@ -24,7 +25,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
|||
);
|
||||
});
|
||||
|
||||
test.skip("should add a system message from config.ts", async () => {
|
||||
test("should add a system message from config.ts", async () => {
|
||||
const configTs = `export function modifyConfig(config: Config): Config {
|
||||
config.systemMessage = "SYSTEM";
|
||||
return config;
|
||||
|
|
@ -39,7 +40,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
|||
expect(config.systemMessage).toBe("SYSTEM");
|
||||
});
|
||||
|
||||
test.skip("should acknowledge override from .continuerc.json", async () => {
|
||||
test("should acknowledge override from .continuerc.json", async () => {
|
||||
fs.writeFileSync(
|
||||
path.join(TEST_DIR, ".continuerc.json"),
|
||||
JSON.stringify({ systemMessage: "SYSTEM2" }),
|
||||
|
|
@ -30,14 +30,12 @@ import {
|
|||
ModelDescription,
|
||||
RerankerDescription,
|
||||
SerializedContinueConfig,
|
||||
SlashCommand,
|
||||
SlashCommandWithSource,
|
||||
} from "..";
|
||||
import {
|
||||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
} from "../commands/index";
|
||||
import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy";
|
||||
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
|
||||
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import FileContextProvider from "../context/providers/FileContextProvider";
|
||||
|
|
@ -48,8 +46,7 @@ import { LLMClasses, llmFromDescription } from "../llm/llms";
|
|||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
import { LLMReranker } from "../llm/llms/llm";
|
||||
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
|
||||
import { getAllPromptFiles } from "../promptFiles/getPromptFiles";
|
||||
import { copyOf } from "../util";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import mergeJson from "../util/merge";
|
||||
|
|
@ -65,7 +62,8 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { baseToolDefinitions } from "../tools";
|
||||
import { getToolsForIde } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import {
|
||||
getModelByRole,
|
||||
|
|
@ -174,15 +172,15 @@ async function serializedToIntermediateConfig(
|
|||
ide: IDE,
|
||||
): Promise<Config> {
|
||||
// DEPRECATED - load custom slash commands
|
||||
const slashCommands: SlashCommand[] = [];
|
||||
const slashCommands: SlashCommandWithSource[] = [];
|
||||
for (const command of initial.slashCommands || []) {
|
||||
const newCommand = slashCommandFromDescription(command);
|
||||
const newCommand = getLegacyBuiltInSlashCommandFromDescription(command);
|
||||
if (newCommand) {
|
||||
slashCommands.push(newCommand);
|
||||
}
|
||||
}
|
||||
for (const command of initial.customCommands || []) {
|
||||
slashCommands.push(slashFromCustomCommand(command));
|
||||
slashCommands.push(convertCustomCommandToSlashCommand(command));
|
||||
}
|
||||
|
||||
// DEPRECATED - load slash commands from v1 prompt files
|
||||
|
|
@ -194,7 +192,7 @@ async function serializedToIntermediateConfig(
|
|||
);
|
||||
|
||||
for (const file of promptFiles) {
|
||||
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
|
||||
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
|
||||
if (slashCommand) {
|
||||
slashCommands.push(slashCommand);
|
||||
}
|
||||
|
|
@ -254,7 +252,10 @@ async function intermediateToFinalConfig({
|
|||
loadPromptFiles?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
const getUriFromPath = (path: string) => {
|
||||
return resolveRelativePathInDir(path, ide, workspaceDirs);
|
||||
};
|
||||
// Auto-detect models
|
||||
let models: BaseLLM[] = [];
|
||||
await Promise.all(
|
||||
|
|
@ -263,6 +264,7 @@ async function intermediateToFinalConfig({
|
|||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -284,6 +286,7 @@ async function intermediateToFinalConfig({
|
|||
title: modelName,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -360,6 +363,7 @@ async function intermediateToFinalConfig({
|
|||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -393,13 +397,7 @@ async function intermediateToFinalConfig({
|
|||
| undefined
|
||||
)?.params || {};
|
||||
|
||||
const DEFAULT_CONTEXT_PROVIDERS = [
|
||||
new FileContextProvider({}),
|
||||
// Add codebase provider if indexing is enabled
|
||||
...(!config.disableIndexing
|
||||
? [new CodebaseContextProvider(codebaseContextParams)]
|
||||
: []),
|
||||
];
|
||||
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
|
||||
|
||||
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
|
||||
({ description: { title } }) => title,
|
||||
|
|
@ -527,9 +525,9 @@ async function intermediateToFinalConfig({
|
|||
const continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
tools: [...baseToolDefinitions],
|
||||
tools: await getToolsForIde(ide),
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: config.slashCommands ?? [],
|
||||
slashCommands: [],
|
||||
modelsByRole: {
|
||||
chat: models,
|
||||
edit: models,
|
||||
|
|
@ -551,6 +549,17 @@ async function intermediateToFinalConfig({
|
|||
rules: [],
|
||||
};
|
||||
|
||||
for (const cmd of config.slashCommands ?? []) {
|
||||
if ("source" in cmd) {
|
||||
continueConfig.slashCommands.push(cmd);
|
||||
} else {
|
||||
continueConfig.slashCommands.push({
|
||||
...cmd,
|
||||
source: "config-ts-slash-command",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (config.systemMessage) {
|
||||
continueConfig.rules.unshift({
|
||||
rule: config.systemMessage,
|
||||
|
|
@ -651,9 +660,10 @@ async function finalToBrowserConfig(
|
|||
return {
|
||||
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
|
||||
completionOptions: final.completionOptions,
|
||||
slashCommands: final.slashCommands?.map(
|
||||
({ run, ...slashCommandDescription }) => slashCommandDescription,
|
||||
),
|
||||
slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
|
||||
...rest,
|
||||
isLegacy: !!run,
|
||||
})),
|
||||
contextProviders: final.contextProviders?.map((c) => c.description),
|
||||
disableIndexing: final.disableIndexing,
|
||||
disableSessionTitles: final.disableSessionTitles,
|
||||
|
|
@ -975,7 +985,6 @@ async function loadContinueConfigFromJson(
|
|||
|
||||
export {
|
||||
finalToBrowserConfig,
|
||||
intermediateToFinalConfig,
|
||||
loadContinueConfigFromJson,
|
||||
type BrowserSerializedContinueConfig,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { walkDirCache } from "../indexing/walkDir";
|
||||
import { testIde } from "../test/fixtures";
|
||||
import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";
|
||||
|
|
@ -33,7 +33,7 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
|
|||
const content = await ide.readFile(filePath);
|
||||
const rule = markdownToRule(content, { uriType: "file", filePath });
|
||||
|
||||
rules.push({ ...rule, source: "rules-block" });
|
||||
rules.push({ ...rule, source: "rules-block", ruleFile: filePath });
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
|
|||
uriType: "file",
|
||||
filePath: file.path,
|
||||
});
|
||||
rules.push({ ...rule, source: "rules-block" });
|
||||
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
|
|
|
|||
|
|
@ -16,9 +16,9 @@ import {
|
|||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
SerializedContinueConfig,
|
||||
SlashCommandDescWithSource,
|
||||
Tool,
|
||||
} from "../../";
|
||||
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import MCPContextProvider from "../../context/providers/MCPContextProvider";
|
||||
import RulesContextProvider from "../../context/providers/RulesContextProvider";
|
||||
|
|
@ -190,14 +190,15 @@ export default async function doLoadConfig(options: {
|
|||
}));
|
||||
newConfig.tools.push(...serverTools);
|
||||
|
||||
const serverSlashCommands = server.prompts.map((prompt) =>
|
||||
constructMcpSlashCommand(
|
||||
server.client,
|
||||
prompt.name,
|
||||
prompt.description,
|
||||
prompt.arguments?.map((a: any) => a.name),
|
||||
),
|
||||
);
|
||||
const serverSlashCommands: SlashCommandDescWithSource[] =
|
||||
server.prompts.map((prompt) => ({
|
||||
name: prompt.name,
|
||||
description: prompt.description ?? "MCP Prompt",
|
||||
source: "mcp-prompt",
|
||||
isLegacy: false,
|
||||
mcpServerName: server.name, // Used in client to retrieve prompt
|
||||
mcpArgs: prompt.arguments,
|
||||
}));
|
||||
newConfig.slashCommands.push(...serverSlashCommands);
|
||||
|
||||
const submenuItems = server.resources
|
||||
|
|
@ -229,6 +230,8 @@ export default async function doLoadConfig(options: {
|
|||
newConfig.tools.push(
|
||||
...getConfigDependentToolDefinitions({
|
||||
rules: newConfig.rules,
|
||||
enableExperimentalTools:
|
||||
newConfig.experimental?.enableExperimentalTools ?? false,
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -19,6 +19,10 @@ export const sharedConfigSchema = z
|
|||
readResponseTTS: z.boolean(),
|
||||
promptPath: z.string(),
|
||||
useCurrentFileAsContext: z.boolean(),
|
||||
logEditingData: z.boolean(),
|
||||
optInNextEditFeature: z.boolean(),
|
||||
enableExperimentalTools: z.boolean(),
|
||||
codebaseToolCallingOnly: z.boolean(),
|
||||
|
||||
// `ui` in `ContinueConfig`
|
||||
showSessionTabs: z.boolean(),
|
||||
|
|
@ -157,6 +161,12 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.experimental = {
|
||||
...configCopy.experimental,
|
||||
};
|
||||
|
||||
if (sharedConfig.enableExperimentalTools !== undefined) {
|
||||
configCopy.experimental.enableExperimentalTools =
|
||||
sharedConfig.enableExperimentalTools;
|
||||
}
|
||||
|
||||
if (sharedConfig.promptPath !== undefined) {
|
||||
configCopy.experimental.promptPath = sharedConfig.promptPath;
|
||||
}
|
||||
|
|
@ -171,6 +181,17 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.experimental.useCurrentFileAsContext =
|
||||
sharedConfig.useCurrentFileAsContext;
|
||||
}
|
||||
if (sharedConfig.logEditingData !== undefined) {
|
||||
configCopy.experimental.logEditingData = sharedConfig.logEditingData;
|
||||
}
|
||||
if (sharedConfig.optInNextEditFeature !== undefined) {
|
||||
configCopy.experimental.optInNextEditFeature =
|
||||
sharedConfig.optInNextEditFeature;
|
||||
}
|
||||
if (sharedConfig.codebaseToolCallingOnly !== undefined) {
|
||||
configCopy.experimental.codebaseToolCallingOnly =
|
||||
sharedConfig.codebaseToolCallingOnly;
|
||||
}
|
||||
|
||||
return configCopy;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,344 +0,0 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { BrowserSerializedContinueConfig } from "..";
|
||||
|
||||
// Create the mock before importing anything else
|
||||
const mockDecodeSecretLocation = jest.fn();
|
||||
|
||||
// Mock the module
|
||||
jest.unstable_mockModule("@continuedev/config-yaml", () => ({
|
||||
SecretType: {
|
||||
User: "user",
|
||||
Organization: "organization",
|
||||
FreeTrial: "free_trial",
|
||||
},
|
||||
decodeSecretLocation: mockDecodeSecretLocation,
|
||||
}));
|
||||
|
||||
// Import after mocking
|
||||
const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey");
|
||||
const { SecretType } = await import("@continuedev/config-yaml");
|
||||
|
||||
beforeEach(() => {
|
||||
mockDecodeSecretLocation.mockReset();
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false when config is null", () => {
|
||||
const result = usesFreeTrialApiKey(null);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false when config is undefined", () => {
|
||||
const result = usesFreeTrialApiKey(undefined as any);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
{
|
||||
title: "Model 2",
|
||||
provider: "test",
|
||||
model: "test-model-2",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
apiKeyLocation: "user:testuser/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [
|
||||
{
|
||||
title: "Model 2",
|
||||
provider: "test",
|
||||
model: "test-model-2",
|
||||
apiKeyLocation: "organization:testorg/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
mockDecodeSecretLocation
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.User,
|
||||
userSlug: "testuser",
|
||||
secretName: "api-key",
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.Organization,
|
||||
orgSlug: "testorg",
|
||||
secretName: "api-key",
|
||||
});
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(false);
|
||||
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
apiKeyLocation: "user:testuser/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
{
|
||||
title: "Free Trial Model",
|
||||
provider: "test",
|
||||
model: "free-trial-model",
|
||||
apiKeyLocation: "free_trial:owner/package/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
mockDecodeSecretLocation
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.User,
|
||||
userSlug: "testuser",
|
||||
secretName: "api-key",
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.FreeTrial,
|
||||
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
|
||||
secretName: "api-key",
|
||||
});
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(true);
|
||||
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
apiKeyLocation: "user:testuser/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [
|
||||
{
|
||||
title: "Free Trial Edit Model",
|
||||
provider: "test",
|
||||
model: "free-trial-edit-model",
|
||||
apiKeyLocation: "free_trial:owner/package/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
mockDecodeSecretLocation
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.User,
|
||||
userSlug: "testuser",
|
||||
secretName: "api-key",
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.FreeTrial,
|
||||
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
|
||||
secretName: "api-key",
|
||||
});
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
|
||||
const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {});
|
||||
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
apiKeyLocation: "invalid-secret-location",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
mockDecodeSecretLocation.mockImplementation(() => {
|
||||
throw new Error("Invalid secret location format");
|
||||
});
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(false);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"Error checking for free trial API key:",
|
||||
expect.any(Error),
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [],
|
||||
edit: [],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(false);
|
||||
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
|
||||
});
|
||||
348
core/config/usesFreeTrialApiKey.vitest.ts
Normal file
348
core/config/usesFreeTrialApiKey.vitest.ts
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { BrowserSerializedContinueConfig } from "..";
|
||||
|
||||
// Create the mock before importing anything else
|
||||
const mockDecodeSecretLocation = vi.fn();
|
||||
|
||||
// Mock the module
|
||||
vi.mock("@continuedev/config-yaml", () => ({
|
||||
SecretType: {
|
||||
User: "user",
|
||||
Organization: "organization",
|
||||
FreeTrial: "free_trial",
|
||||
},
|
||||
decodeSecretLocation: mockDecodeSecretLocation,
|
||||
}));
|
||||
|
||||
describe("usesFreeTrialApiKey", () => {
|
||||
let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey;
|
||||
let SecretType: typeof import("@continuedev/config-yaml").SecretType;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockDecodeSecretLocation.mockReset();
|
||||
usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
|
||||
.usesFreeTrialApiKey;
|
||||
SecretType = (await import("@continuedev/config-yaml")).SecretType;
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false when config is null", () => {
|
||||
const result = usesFreeTrialApiKey(null);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false when config is undefined", () => {
|
||||
const result = usesFreeTrialApiKey(undefined as any);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
{
|
||||
title: "Model 2",
|
||||
provider: "test",
|
||||
model: "test-model-2",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
apiKeyLocation: "user:testuser/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [
|
||||
{
|
||||
title: "Model 2",
|
||||
provider: "test",
|
||||
model: "test-model-2",
|
||||
apiKeyLocation: "organization:testorg/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
mockDecodeSecretLocation
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.User,
|
||||
userSlug: "testuser",
|
||||
secretName: "api-key",
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.Organization,
|
||||
orgSlug: "testorg",
|
||||
secretName: "api-key",
|
||||
});
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(false);
|
||||
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
apiKeyLocation: "user:testuser/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
{
|
||||
title: "Free Trial Model",
|
||||
provider: "test",
|
||||
model: "free-trial-model",
|
||||
apiKeyLocation: "free_trial:owner/package/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
mockDecodeSecretLocation
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.User,
|
||||
userSlug: "testuser",
|
||||
secretName: "api-key",
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.FreeTrial,
|
||||
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
|
||||
secretName: "api-key",
|
||||
});
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(true);
|
||||
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
apiKeyLocation: "user:testuser/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [
|
||||
{
|
||||
title: "Free Trial Edit Model",
|
||||
provider: "test",
|
||||
model: "free-trial-edit-model",
|
||||
apiKeyLocation: "free_trial:owner/package/api-key",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
mockDecodeSecretLocation
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.User,
|
||||
userSlug: "testuser",
|
||||
secretName: "api-key",
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
secretType: SecretType.FreeTrial,
|
||||
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
|
||||
secretName: "api-key",
|
||||
});
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
|
||||
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [
|
||||
{
|
||||
title: "Model 1",
|
||||
provider: "test",
|
||||
model: "test-model",
|
||||
apiKeyLocation: "invalid-secret-location",
|
||||
underlyingProviderName: "test",
|
||||
},
|
||||
],
|
||||
edit: [],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
mockDecodeSecretLocation.mockImplementation(() => {
|
||||
throw new Error("Invalid secret location format");
|
||||
});
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(false);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"Error checking for free trial API key:",
|
||||
expect.any(Error),
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
|
||||
const config: BrowserSerializedContinueConfig = {
|
||||
modelsByRole: {
|
||||
chat: [],
|
||||
edit: [],
|
||||
apply: [],
|
||||
summarize: [],
|
||||
autocomplete: [],
|
||||
rerank: [],
|
||||
embed: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null,
|
||||
edit: null,
|
||||
apply: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
contextProviders: [],
|
||||
slashCommands: [],
|
||||
tools: [],
|
||||
mcpServerStatuses: [],
|
||||
usePlatform: false,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
const result = usesFreeTrialApiKey(config);
|
||||
expect(result).toBe(false);
|
||||
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
@ -10,7 +10,7 @@ import {
|
|||
JSONModelDescription,
|
||||
PromptTemplate,
|
||||
} from "../";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigFile } from "../util/paths";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { PromptTemplate } from "..";
|
||||
import { serializePromptTemplates } from "./util";
|
||||
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
|
||||
import { describe, expect, test } from "@jest/globals";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
|
||||
|
||||
describe("getFileContent", () => {
|
||||
|
|
@ -25,19 +25,18 @@ import {
|
|||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
} from "../..";
|
||||
import { slashFromCustomCommand } from "../../commands";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
|
||||
import DocsContextProvider from "../../context/providers/DocsContextProvider";
|
||||
import FileContextProvider from "../../context/providers/FileContextProvider";
|
||||
import { contextProviderClassFromName } from "../../context/providers/index";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { getToolsForIde } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
|
|
@ -263,7 +262,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
promptFiles.forEach((file) => {
|
||||
try {
|
||||
const slashCommand = slashCommandFromPromptFileV1(
|
||||
const slashCommand = slashCommandFromPromptFile(
|
||||
file.path,
|
||||
file.content,
|
||||
);
|
||||
|
|
@ -286,7 +285,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
config.prompts?.forEach((prompt) => {
|
||||
try {
|
||||
const slashCommand = slashFromCustomCommand(prompt);
|
||||
const slashCommand = convertPromptBlockToSlashCommand(prompt);
|
||||
continueConfig.slashCommands?.push(slashCommand);
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
|
|
@ -385,13 +384,7 @@ async function configYamlToContinueConfig(options: {
|
|||
}
|
||||
|
||||
// Context providers
|
||||
const codebaseContextParams: IContextProvider[] =
|
||||
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
|
||||
{};
|
||||
const DEFAULT_CONTEXT_PROVIDERS = [
|
||||
new FileContextProvider({}),
|
||||
new CodebaseContextProvider(codebaseContextParams),
|
||||
];
|
||||
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
|
||||
|
||||
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
|
||||
({ description: { title } }) => title,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import MCPConnection from "./MCPConnection";
|
||||
|
||||
describe("MCPConnection", () => {
|
||||
beforeEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("constructor", () => {
|
||||
|
|
@ -131,10 +131,10 @@ describe("MCPConnection", () => {
|
|||
|
||||
it("should connect successfully", async () => {
|
||||
const conn = new MCPConnection(options);
|
||||
const mockConnect = jest
|
||||
const mockConnect = vi
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockResolvedValue(undefined);
|
||||
const mockGetServerCapabilities = jest
|
||||
const mockGetServerCapabilities = vi
|
||||
.spyOn(Client.prototype, "getServerCapabilities")
|
||||
.mockReturnValue({
|
||||
resources: {},
|
||||
|
|
@ -142,12 +142,12 @@ describe("MCPConnection", () => {
|
|||
prompts: {},
|
||||
});
|
||||
|
||||
const mockListResources = jest
|
||||
const mockListResources = vi
|
||||
.spyOn(Client.prototype, "listResources")
|
||||
.mockResolvedValue({
|
||||
resources: [{ name: "test-resource", uri: "test-uri" }],
|
||||
});
|
||||
const mockListTools = jest
|
||||
const mockListTools = vi
|
||||
.spyOn(Client.prototype, "listTools")
|
||||
.mockResolvedValue({
|
||||
tools: [
|
||||
|
|
@ -159,7 +159,7 @@ describe("MCPConnection", () => {
|
|||
},
|
||||
],
|
||||
});
|
||||
const mockListPrompts = jest
|
||||
const mockListPrompts = vi
|
||||
.spyOn(Client.prototype, "listPrompts")
|
||||
.mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
|
||||
|
||||
|
|
@ -175,7 +175,7 @@ describe("MCPConnection", () => {
|
|||
|
||||
it("should handle custom connection timeout", async () => {
|
||||
const conn = new MCPConnection({ ...options, timeout: 1500 });
|
||||
const mockConnect = jest
|
||||
const mockConnect = vi
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(resolve, 1000)),
|
||||
|
|
@ -190,7 +190,7 @@ describe("MCPConnection", () => {
|
|||
|
||||
it("should handle connection timeout", async () => {
|
||||
const conn = new MCPConnection({ ...options, timeout: 1 });
|
||||
const mockConnect = jest
|
||||
const mockConnect = vi
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(resolve, 100)),
|
||||
|
|
@ -208,7 +208,7 @@ describe("MCPConnection", () => {
|
|||
const conn = new MCPConnection(options);
|
||||
conn.status = "connected";
|
||||
|
||||
const mockConnect = jest.spyOn(Client.prototype, "connect");
|
||||
const mockConnect = vi.spyOn(Client.prototype, "connect");
|
||||
const abortController = new AbortController();
|
||||
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
|
|
@ -219,7 +219,7 @@ describe("MCPConnection", () => {
|
|||
|
||||
it("should handle transport errors", async () => {
|
||||
const conn = new MCPConnection(options);
|
||||
const mockConnect = jest
|
||||
const mockConnect = vi
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockRejectedValue(new Error("spawn test-cmd ENOENT"));
|
||||
|
||||
|
|
@ -233,7 +233,7 @@ describe("MCPConnection", () => {
|
|||
|
||||
it.skip("should include stderr output in error message when stdio command fails", async () => {
|
||||
// Clear any existing mocks to ensure we get real behavior
|
||||
jest.restoreAllMocks();
|
||||
vi.restoreAllMocks();
|
||||
|
||||
// Use a command that will definitely fail and produce stderr output
|
||||
const failingOptions = {
|
||||
|
|
@ -161,4 +161,21 @@ export class MCPManagerSingleton {
|
|||
client: connection.client,
|
||||
}));
|
||||
}
|
||||
|
||||
async getPrompt(
|
||||
serverName: string,
|
||||
promptName: string,
|
||||
args: Record<string, string> = {},
|
||||
) {
|
||||
const connection = this.connections.get(serverName);
|
||||
if (!connection) {
|
||||
throw new Error(
|
||||
`Error getting prompt: MCP Connection ${serverName} not found`,
|
||||
);
|
||||
}
|
||||
return await connection.client.getPrompt({
|
||||
name: promptName,
|
||||
arguments: args,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MCPOptions } from "../..";
|
||||
import MCPConnection from "./MCPConnection";
|
||||
import { MCPManagerSingleton } from "./MCPManagerSingleton";
|
||||
|
|
@ -18,8 +19,8 @@ class TestMCPConnection extends MCPConnection {
|
|||
} as any;
|
||||
|
||||
this.abortController = new AbortController();
|
||||
this.connectClient = jest.fn().mockResolvedValue(undefined);
|
||||
this.getStatus = jest
|
||||
this.connectClient = vi.fn().mockResolvedValue(undefined);
|
||||
this.getStatus = vi
|
||||
.fn()
|
||||
.mockReturnValue({ status: "connected", errors: [] });
|
||||
}
|
||||
|
|
@ -54,13 +55,12 @@ describe("MCPManagerSingleton", () => {
|
|||
id: string,
|
||||
options: MCPOptions,
|
||||
): MCPConnection {
|
||||
if (!this.connections.has(id)) {
|
||||
const connection = new TestMCPConnection(options);
|
||||
this.connections.set(id, connection);
|
||||
return connection;
|
||||
} else {
|
||||
if (this.connections.has(id)) {
|
||||
return this.connections.get(id)!;
|
||||
}
|
||||
const connection = new TestMCPConnection(options);
|
||||
this.connections.set(id, connection);
|
||||
return connection;
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -103,7 +103,7 @@ describe("MCPManagerSingleton", () => {
|
|||
"test-id",
|
||||
testOptions,
|
||||
) as TestMCPConnection;
|
||||
const closeSpy = jest.spyOn(connection.client, "close");
|
||||
const closeSpy = vi.spyOn(connection.client, "close");
|
||||
|
||||
await manager.removeConnection("test-id");
|
||||
|
||||
|
|
@ -133,8 +133,8 @@ describe("MCPManagerSingleton", () => {
|
|||
"test-id",
|
||||
testOptions,
|
||||
) as TestMCPConnection;
|
||||
const abortSpy = jest.spyOn(connection.abortController, "abort");
|
||||
const closeSpy = jest.spyOn(connection.client, "close");
|
||||
const abortSpy = vi.spyOn(connection.abortController, "abort");
|
||||
const closeSpy = vi.spyOn(connection.client, "close");
|
||||
|
||||
// Remove it by setting empty server list
|
||||
manager.setConnections([], false);
|
||||
|
|
@ -192,7 +192,7 @@ describe("MCPManagerSingleton", () => {
|
|||
});
|
||||
|
||||
it("should call onConnectionsRefreshed if defined", async () => {
|
||||
const mockCallback = jest.fn();
|
||||
const mockCallback = vi.fn();
|
||||
manager.onConnectionsRefreshed = mockCallback;
|
||||
manager.createConnection("test-id", testOptions);
|
||||
|
||||
|
|
@ -209,7 +209,7 @@ describe("MCPManagerSingleton", () => {
|
|||
testOptions,
|
||||
) as TestMCPConnection;
|
||||
const mockStatus = { status: "connected", errors: [] };
|
||||
connection.getStatus = jest.fn().mockReturnValue(mockStatus);
|
||||
connection.getStatus = vi.fn().mockReturnValue(mockStatus);
|
||||
|
||||
const statuses = manager.getStatuses();
|
||||
expect(statuses).toHaveLength(1);
|
||||
|
|
@ -21,7 +21,9 @@ class TerminalContextProvider extends BaseContextProvider {
|
|||
return [
|
||||
{
|
||||
description: "The contents of the terminal",
|
||||
content: `Current terminal contents:\n\n${content}`,
|
||||
content: `Current terminal contents:\n\n${
|
||||
content || "The terminal is empty."
|
||||
}`,
|
||||
name: "Terminal",
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import fetch from "node-fetch";
|
||||
|
||||
import { afterAll, describe, expect, test } from "vitest";
|
||||
import { contextProviderClassFromName } from ".";
|
||||
import {
|
||||
ContextProviderExtras,
|
||||
|
|
@ -8,7 +9,7 @@ import {
|
|||
} from "../..";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { LLMLogger } from "../../llm/logger";
|
||||
import { TEST_DIR } from "../../test/testDir";
|
||||
import { setUpTestDir, tearDownTestDir, TEST_DIR } from "../../test/testDir";
|
||||
import FileSystemIde from "../../util/filesystem";
|
||||
|
||||
const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
|
||||
|
|
@ -25,6 +26,7 @@ const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
|
|||
async function getContextProviderExtras(
|
||||
fullInput: string,
|
||||
): Promise<ContextProviderExtras> {
|
||||
setUpTestDir();
|
||||
const ide = new FileSystemIde(TEST_DIR);
|
||||
const ideSettingsPromise = ide.getIdeSettings();
|
||||
const llmLogger = new LLMLogger();
|
||||
|
|
@ -52,6 +54,10 @@ async function getContextProviderExtras(
|
|||
}
|
||||
|
||||
describe.skip("Should successfully run all context providers", () => {
|
||||
afterAll(() => {
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
const extrasPromise = getContextProviderExtras("Test");
|
||||
|
||||
CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {
|
||||
|
|
@ -1,7 +1,9 @@
|
|||
import { BaseContextProvider } from "../";
|
||||
import { ContextProviderName } from "../../";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
|
||||
import ClipboardContextProvider from "./ClipboardContextProvider";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider";
|
||||
import CodeContextProvider from "./CodeContextProvider";
|
||||
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
|
||||
import CurrentFileContextProvider from "./CurrentFileContextProvider";
|
||||
|
|
@ -56,6 +58,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
|
|||
JiraIssuesContextProvider,
|
||||
PostgresContextProvider,
|
||||
DatabaseContextProvider,
|
||||
CodebaseContextProvider,
|
||||
CodeContextProvider,
|
||||
CurrentFileContextProvider,
|
||||
URLContextProvider,
|
||||
|
|
@ -73,5 +76,12 @@ export const Providers: (typeof BaseContextProvider)[] = [
|
|||
export function contextProviderClassFromName(
|
||||
name: ContextProviderName,
|
||||
): typeof BaseContextProvider | undefined {
|
||||
return Providers.find((cls) => cls.description.title === name);
|
||||
const provider = Providers.find((cls) => cls.description.title === name);
|
||||
|
||||
void Telemetry.capture("context_provider_load", {
|
||||
providerName: name,
|
||||
found: !!provider, // also capture those which user expected to be present
|
||||
});
|
||||
|
||||
return provider;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,40 @@
|
|||
// @ts-ignore
|
||||
import nlp from "wink-nlp-utils";
|
||||
|
||||
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
|
||||
import {
|
||||
BranchAndDir,
|
||||
Chunk,
|
||||
ContextItem,
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
ILLM,
|
||||
Tool,
|
||||
ToolExtras,
|
||||
} from "../../../";
|
||||
import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
|
||||
import { chunkDocument } from "../../../indexing/chunk/chunk";
|
||||
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
|
||||
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
|
||||
import { BuiltInToolNames } from "../../../tools/builtIn";
|
||||
import { callBuiltInTool } from "../../../tools/callTool";
|
||||
import { globSearchTool } from "../../../tools/definitions/globSearch";
|
||||
import { grepSearchTool } from "../../../tools/definitions/grepSearch";
|
||||
import { lsTool } from "../../../tools/definitions/lsTool";
|
||||
import { readFileTool } from "../../../tools/definitions/readFile";
|
||||
import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
|
||||
import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
|
||||
|
||||
const DEFAULT_CHUNK_SIZE = 384;
|
||||
|
||||
const AVAILABLE_TOOLS: Tool[] = [
|
||||
globSearchTool,
|
||||
grepSearchTool,
|
||||
lsTool,
|
||||
readFileTool,
|
||||
viewRepoMapTool,
|
||||
viewSubdirectoryTool,
|
||||
];
|
||||
|
||||
export interface RetrievalPipelineOptions {
|
||||
llm: ILLM;
|
||||
config: ContinueConfig;
|
||||
|
|
@ -155,4 +181,105 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
|
||||
protected async retrieveWithTools(input: string): Promise<Chunk[]> {
|
||||
const toolSelectionPrompt = `Given the following user input: "${input}"
|
||||
|
||||
Available tools:
|
||||
${AVAILABLE_TOOLS.map((tool) => {
|
||||
const requiredParams = tool.function.parameters?.required || [];
|
||||
const properties = tool.function.parameters?.properties || {};
|
||||
const paramDescriptions = requiredParams
|
||||
.map(
|
||||
(param: any) => `${param}: ${properties[param]?.description || "string"}`,
|
||||
)
|
||||
.join(", ");
|
||||
|
||||
return `- ${tool.function.name}: ${tool.function.description}
|
||||
Required arguments: ${paramDescriptions || "none"}`;
|
||||
}).join("\n")}
|
||||
|
||||
Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else:
|
||||
{
|
||||
"tools": [
|
||||
{
|
||||
"name": "<tool_name>",
|
||||
"args": { "<required_parameter_name>": "<required_parameter_value>" }
|
||||
}
|
||||
]
|
||||
}`;
|
||||
|
||||
// Get LLM response for tool selection
|
||||
const toolSelectionResponse = await this.options.llm.chat(
|
||||
[{ role: "user", content: toolSelectionPrompt }],
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
let toolCalls: { name: string; args: any }[] = [];
|
||||
try {
|
||||
const responseContent =
|
||||
typeof toolSelectionResponse.content === "string"
|
||||
? toolSelectionResponse.content
|
||||
: toolSelectionResponse.content
|
||||
.map((part) => (part.type === "text" ? part.text : ""))
|
||||
.join("");
|
||||
const parsed = JSON.parse(responseContent);
|
||||
toolCalls = parsed.tools || [];
|
||||
console.log("retrieveWithTools", toolCalls);
|
||||
} catch (e) {
|
||||
console.log("Failed to parse tool selection response", e);
|
||||
return [];
|
||||
}
|
||||
|
||||
// Execute tools and collect results
|
||||
const allContextItems: ContextItem[] = [];
|
||||
|
||||
const toolExtras: ToolExtras = {
|
||||
ide: this.options.ide,
|
||||
llm: this.options.llm,
|
||||
fetch: fetch,
|
||||
tool: grepSearchTool,
|
||||
config: this.options.config,
|
||||
};
|
||||
|
||||
for (const toolCall of toolCalls) {
|
||||
const tool = AVAILABLE_TOOLS.find(
|
||||
(t) => t.function.name === toolCall.name,
|
||||
)!;
|
||||
|
||||
const args = toolCall.args;
|
||||
if (toolCall.name === BuiltInToolNames.GrepSearch) {
|
||||
args.splitByFile = true;
|
||||
}
|
||||
|
||||
toolExtras.tool = tool;
|
||||
const contextItems = await callBuiltInTool(
|
||||
toolCall.name,
|
||||
args,
|
||||
toolExtras,
|
||||
);
|
||||
allContextItems.push(...contextItems);
|
||||
}
|
||||
|
||||
const chunks: Chunk[] = [];
|
||||
|
||||
// Transform ContextItem[] to Chunk[]
|
||||
for (let i = 0; i < allContextItems.length; i++) {
|
||||
const contextItem = allContextItems[i];
|
||||
const filepath = contextItem.uri?.value || contextItem.name || "unknown";
|
||||
const cleanedFilepath = filepath.replace(/^file:\/\/\//, "");
|
||||
|
||||
chunks.push({
|
||||
content: contextItem.content,
|
||||
startLine: -1,
|
||||
endLine: -1,
|
||||
digest: `file:///${cleanedFilepath}`,
|
||||
filepath: `file:///${cleanedFilepath}`,
|
||||
index: i,
|
||||
});
|
||||
}
|
||||
|
||||
console.log("retrieveWithTools chunks", chunks);
|
||||
return chunks;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -64,12 +64,22 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
console.error("Error retrieving repo map chunks:", error);
|
||||
}
|
||||
|
||||
retrievalResults.push(
|
||||
...recentlyEditedFilesChunks,
|
||||
...ftsChunks,
|
||||
...embeddingsChunks,
|
||||
...repoMapChunks,
|
||||
);
|
||||
if (this.options.config.experimental?.codebaseToolCallingOnly) {
|
||||
let toolBasedChunks: Chunk[] = [];
|
||||
try {
|
||||
toolBasedChunks = await this.retrieveWithTools(input);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving tool based chunks:", error);
|
||||
}
|
||||
retrievalResults.push(...toolBasedChunks);
|
||||
} else {
|
||||
retrievalResults.push(
|
||||
...recentlyEditedFilesChunks,
|
||||
...ftsChunks,
|
||||
...embeddingsChunks,
|
||||
...repoMapChunks,
|
||||
);
|
||||
}
|
||||
|
||||
if (filterDirectory) {
|
||||
// Backup if the individual retrieval methods don't listen
|
||||
|
|
|
|||
|
|
@ -58,12 +58,22 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
console.error("Error retrieving repo map chunks:", error);
|
||||
}
|
||||
|
||||
retrievalResults.push(
|
||||
...recentlyEditedFilesChunks,
|
||||
...ftsChunks,
|
||||
...embeddingsChunks,
|
||||
...repoMapChunks,
|
||||
);
|
||||
if (config.experimental?.codebaseToolCallingOnly) {
|
||||
let toolBasedChunks: Chunk[] = [];
|
||||
try {
|
||||
toolBasedChunks = await this.retrieveWithTools(input);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving tool based chunks:", error);
|
||||
}
|
||||
retrievalResults.push(...toolBasedChunks);
|
||||
} else {
|
||||
retrievalResults.push(
|
||||
...recentlyEditedFilesChunks,
|
||||
...ftsChunks,
|
||||
...embeddingsChunks,
|
||||
...repoMapChunks,
|
||||
);
|
||||
}
|
||||
|
||||
if (filterDirectory) {
|
||||
// Backup if the individual retrieval methods don't listen
|
||||
|
|
@ -107,7 +117,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
|
||||
|
||||
results.sort(
|
||||
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
|
||||
(a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
|
||||
);
|
||||
results = results.slice(-this.options.nFinal);
|
||||
return results;
|
||||
|
|
|
|||
|
|
@ -108,7 +108,11 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
}
|
||||
|
||||
return {
|
||||
name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
|
||||
// Don't show line numbers for tool calls where startLine = -1
|
||||
name:
|
||||
r.startLine === -1
|
||||
? baseName
|
||||
: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
|
||||
description: last2Parts,
|
||||
content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``,
|
||||
uri: {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// Generated by Continue
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Chunk } from "../../index";
|
||||
|
||||
import { deduplicateChunks } from "./util";
|
||||
|
||||
describe("deduplicateChunks", () => {
|
||||
95
core/core.ts
95
core/core.ts
|
|
@ -10,7 +10,6 @@ import {
|
|||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
|
||||
import { addModel, deleteModel } from "./config/util";
|
||||
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
|
||||
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
|
||||
import { ContinueServerClient } from "./continueServer/stubs/client";
|
||||
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
||||
|
|
@ -21,7 +20,8 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
|
|||
import DocsService from "./indexing/docs/DocsService";
|
||||
import { countTokens } from "./llm/countTokens";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
|
||||
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
|
||||
import { callTool } from "./tools/callTool";
|
||||
import { ChatDescriber } from "./util/chatDescriber";
|
||||
import { clipboardCache } from "./util/clipboardCache";
|
||||
|
|
@ -38,18 +38,20 @@ import { TTS } from "./util/tts";
|
|||
|
||||
import {
|
||||
CompleteOnboardingPayload,
|
||||
ContextItemId,
|
||||
ContextItemWithId,
|
||||
IdeSettings,
|
||||
ModelDescription,
|
||||
Position,
|
||||
RangeInFile,
|
||||
ToolCall,
|
||||
type ContextItem,
|
||||
type ContextItemId,
|
||||
type IDE,
|
||||
} from ".";
|
||||
|
||||
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
|
||||
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
|
||||
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
|
||||
import {
|
||||
setupLocalConfig,
|
||||
|
|
@ -66,6 +68,8 @@ import { walkDirCache } from "./indexing/walkDir";
|
|||
import { LLMLogger } from "./llm/logger";
|
||||
import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
|
||||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
|
||||
import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { OnboardingModes } from "./protocol/core";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
|
@ -381,6 +385,19 @@ export class Core {
|
|||
on("mcp/reloadServer", async (msg) => {
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
});
|
||||
on("mcp/getPrompt", async (msg) => {
|
||||
const { serverName, promptName, args } = msg.data;
|
||||
const prompt = await MCPManagerSingleton.getInstance().getPrompt(
|
||||
serverName,
|
||||
promptName,
|
||||
args,
|
||||
);
|
||||
const stringifiedPrompt = stringifyMcpPrompt(prompt);
|
||||
return {
|
||||
prompt: stringifiedPrompt,
|
||||
description: prompt.description,
|
||||
};
|
||||
});
|
||||
// Context providers
|
||||
on("context/addDocs", async (msg) => {
|
||||
void this.docsService.indexAndAdd(msg.data);
|
||||
|
|
@ -541,7 +558,6 @@ export class Core {
|
|||
: undefined,
|
||||
input: data.input,
|
||||
language: data.language,
|
||||
onlyOneInsertion: false,
|
||||
overridePrompt: undefined,
|
||||
abortController,
|
||||
});
|
||||
|
|
@ -702,6 +718,52 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
on("files/smallEdit", async ({ data }) => {
|
||||
const EDIT_AGGREGATION_OPTIONS = {
|
||||
deltaT: 1.0,
|
||||
deltaL: 5,
|
||||
maxEdits: 500,
|
||||
maxDuration: 120.0,
|
||||
contextSize: 5,
|
||||
};
|
||||
|
||||
EditAggregator.getInstance(
|
||||
EDIT_AGGREGATION_OPTIONS,
|
||||
(
|
||||
beforeAfterdiff: BeforeAfterDiff,
|
||||
cursorPosBeforeEdit: Position,
|
||||
cursorPosAfterPrevEdit: Position,
|
||||
) => {
|
||||
void processSmallEdit(
|
||||
beforeAfterdiff,
|
||||
cursorPosBeforeEdit,
|
||||
cursorPosAfterPrevEdit,
|
||||
data.configHandler,
|
||||
data.getDefsFromLspFunction,
|
||||
this.ide,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const workspaceDir =
|
||||
data.actions.length > 0 ? data.actions[0].workspaceDir : undefined;
|
||||
|
||||
// Store the latest context data
|
||||
const instance = EditAggregator.getInstance();
|
||||
(instance as any).latestContextData = {
|
||||
configHandler: data.configHandler,
|
||||
getDefsFromLspFunction: data.getDefsFromLspFunction,
|
||||
recentlyEditedRanges: data.recentlyEditedRanges,
|
||||
recentlyVisitedRanges: data.recentlyVisitedRanges,
|
||||
workspaceDir: workspaceDir,
|
||||
};
|
||||
|
||||
// queueMicrotask prevents blocking the UI thread during typing
|
||||
queueMicrotask(() => {
|
||||
void EditAggregator.getInstance().processEdits(data.actions);
|
||||
});
|
||||
});
|
||||
|
||||
// Docs, etc. indexing
|
||||
on("indexing/reindex", async (msg) => {
|
||||
if (msg.data.type === "docs") {
|
||||
|
|
@ -809,7 +871,7 @@ export class Core {
|
|||
this.messenger.send("toolCallPartialOutput", params);
|
||||
};
|
||||
|
||||
return await callTool(tool, toolCall, {
|
||||
const result = await callTool(tool, toolCall, {
|
||||
config,
|
||||
ide: this.ide,
|
||||
llm: config.selectedModelByRole.chat,
|
||||
|
|
@ -820,6 +882,8 @@ export class Core {
|
|||
onPartialOutput,
|
||||
codeBaseIndexer: this.codeBaseIndexer,
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async isItemTooBig(item: ContextItemWithId) {
|
||||
|
|
@ -1031,18 +1095,15 @@ export class Core {
|
|||
// user doesn't need these in their config.json for the shortcuts to work
|
||||
// option+enter
|
||||
new CurrentFileContextProvider({}),
|
||||
// cmd+enter
|
||||
new CodebaseContextProvider({}),
|
||||
].find((provider) => provider.description.title === name);
|
||||
if (!provider) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const id: ContextItemId = {
|
||||
providerTitle: provider.description.title,
|
||||
itemId: uuidv4(),
|
||||
};
|
||||
void Telemetry.capture("context_provider_get_context_items", {
|
||||
name: provider.description.title,
|
||||
});
|
||||
|
||||
const items = await provider.getContextItems(query, {
|
||||
config,
|
||||
|
|
@ -1064,10 +1125,14 @@ export class Core {
|
|||
true,
|
||||
);
|
||||
|
||||
return items.map((item) => ({
|
||||
...item,
|
||||
id,
|
||||
}));
|
||||
return items.map((item) => {
|
||||
const id: ContextItemId = {
|
||||
providerTitle: provider.description.title,
|
||||
itemId: uuidv4(),
|
||||
};
|
||||
|
||||
return { ...item, id };
|
||||
});
|
||||
} catch (e) {
|
||||
let knownError = false;
|
||||
|
||||
|
|
|
|||
386
core/edit/searchAndReplace/findSearchMatch.test.ts
Normal file
386
core/edit/searchAndReplace/findSearchMatch.test.ts
Normal file
|
|
@ -0,0 +1,386 @@
|
|||
import { findSearchMatch } from "./findSearchMatch";
|
||||
|
||||
describe("findSearchMatch", () => {
|
||||
describe("Exact matches", () => {
|
||||
it("should find exact match at the beginning of file", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: fileContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should find exact match in the middle of file", () => {
|
||||
const fileContent = `const a = 1;
|
||||
function hello() {
|
||||
console.log("world");
|
||||
}
|
||||
const b = 2;`;
|
||||
const searchContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 13, // After "const a = 1;\n"
|
||||
endIndex: 13 + searchContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should find exact match at the end of file", () => {
|
||||
const fileContent = `const a = 1;
|
||||
function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 13, // After "const a = 1;\n"
|
||||
endIndex: fileContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should find exact match with single line", () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
const searchContent = `const b = 2;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 13, // After "const a = 1;\n"
|
||||
endIndex: 13 + searchContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should find exact match with whitespace preserved", () => {
|
||||
const fileContent = `function test() {
|
||||
const x = 1;
|
||||
const y = 2;
|
||||
}`;
|
||||
const searchContent = ` const x = 1;
|
||||
const y = 2;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// The actual indexOf result is 18, not 17
|
||||
expect(result).toEqual({
|
||||
startIndex: 18,
|
||||
endIndex: 18 + searchContent.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Trimmed matches", () => {
|
||||
it("should find trimmed match when exact match fails due to leading newlines", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `\n\nfunction hello() {
|
||||
console.log("world");
|
||||
}\n\n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: fileContent.length, // Uses trimmed length
|
||||
});
|
||||
});
|
||||
|
||||
it("should find trimmed match when exact match fails due to trailing newlines", () => {
|
||||
const fileContent = `const a = 1;
|
||||
function hello() {
|
||||
return "world";
|
||||
}
|
||||
const b = 2;`;
|
||||
const searchContent = `\nfunction hello() {
|
||||
return "world";
|
||||
}\n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// The function finds the exact match first (at index 12), not the trimmed match
|
||||
expect(result).toEqual({
|
||||
startIndex: 12,
|
||||
endIndex: 12 + searchContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should find trimmed match for single line with extra whitespace", () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
const searchContent = `\n const b = 2; \n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const trimmedSearchContent = searchContent.trim();
|
||||
const expectedStart = fileContent.indexOf(trimmedSearchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + trimmedSearchContent.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Empty search content", () => {
|
||||
it("should match at beginning for empty search content", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = "";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("should match at beginning for whitespace-only search content", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = "\n\n \t \n";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("should match at beginning for empty file and empty search", () => {
|
||||
const fileContent = "";
|
||||
const searchContent = "";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("No matches", () => {
|
||||
it("should return null when search content is not found", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `function goodbye() {
|
||||
console.log("world");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null when trimmed search content is not found", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `\n\nfunction goodbye() {
|
||||
console.log("world");
|
||||
}\n\n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null for non-existent single line", () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
const searchContent = `const d = 4;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null for partial match", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `function hello() {
|
||||
console.log("universe");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
it("should handle empty file with non-empty search", () => {
|
||||
const fileContent = "";
|
||||
const searchContent = "function hello() {}";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle very large content", () => {
|
||||
const repeatedLine = "const x = 1;\n";
|
||||
const fileContent =
|
||||
repeatedLine.repeat(1000) +
|
||||
"const target = 2;\n" +
|
||||
repeatedLine.repeat(1000);
|
||||
const searchContent = "const target = 2;";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const expectedStart = repeatedLine.length * 1000;
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + searchContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle special characters and symbols", () => {
|
||||
const fileContent = `const regex = /[a-zA-Z]+/g;
|
||||
const symbols = !@#$%^&*();
|
||||
const unicode = "🚀 Hello 世界";`;
|
||||
const searchContent = `const symbols = !@#$%^&*();`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const expectedStart = fileContent.indexOf(searchContent);
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + searchContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should prefer exact match over trimmed match", () => {
|
||||
const fileContent = `function test() {
|
||||
const x = 1;
|
||||
}
|
||||
|
||||
function test() {
|
||||
const x = 1;
|
||||
}`;
|
||||
const searchContent = `function test() {
|
||||
const x = 1;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// Should find the first exact match, not a trimmed version
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: searchContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle multiple occurrences and return first match", () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const a = 1;`;
|
||||
const searchContent = `const a = 1;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: searchContent.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Real-world scenarios", () => {
|
||||
it("should match typical function replacement", () => {
|
||||
const fileContent = `class Calculator {
|
||||
constructor() {
|
||||
this.result = 0;
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
add(value) {
|
||||
this.result += value;
|
||||
return this;
|
||||
}
|
||||
}`;
|
||||
const searchContent = ` reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const expectedStart = fileContent.indexOf(searchContent);
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + searchContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should match import statement", () => {
|
||||
const fileContent = `import React from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
return <div>Hello World</div>;
|
||||
}`;
|
||||
const searchContent = `import { useState, useEffect } from 'react';`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const expectedStart = fileContent.indexOf(searchContent);
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + searchContent.length,
|
||||
});
|
||||
});
|
||||
|
||||
it("should match comment block", () => {
|
||||
const fileContent = `/**
|
||||
* This is a comment
|
||||
* that spans multiple lines
|
||||
*/
|
||||
function test() {
|
||||
// Single line comment
|
||||
return true;
|
||||
}`;
|
||||
const searchContent = `/**
|
||||
* This is a comment
|
||||
* that spans multiple lines
|
||||
*/`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: searchContent.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
55
core/edit/searchAndReplace/findSearchMatch.ts
Normal file
55
core/edit/searchAndReplace/findSearchMatch.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
/**
|
||||
* Represents a match result with start and end character positions
|
||||
*/
|
||||
export interface SearchMatchResult {
|
||||
/** The starting character index of the match in the file content */
|
||||
startIndex: number;
|
||||
/** The ending character index of the match in the file content */
|
||||
endIndex: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the exact match position for search content in file content.
|
||||
* Uses simple exact matching with trimmed newlines for MVP.
|
||||
*
|
||||
* Matching Strategy:
|
||||
* 1. If search content is empty, matches at the beginning of file (position 0)
|
||||
* 2. Try exact string match first
|
||||
* 3. Fallback to trimmed content match if exact match fails
|
||||
*
|
||||
* @param fileContent - The complete content of the file to search in
|
||||
* @param searchContent - The content to search for
|
||||
* @returns Match result with character positions, or null if no match found
|
||||
*/
|
||||
export function findSearchMatch(
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
): SearchMatchResult | null {
|
||||
// Strip leading/trailing newlines for basic matching strategy
|
||||
const trimmedSearchContent = searchContent.trim();
|
||||
|
||||
if (trimmedSearchContent === "") {
|
||||
// Empty search content matches the beginning of the file
|
||||
return { startIndex: 0, endIndex: 0 };
|
||||
}
|
||||
|
||||
// Try exact match first
|
||||
const exactIndex = fileContent.indexOf(searchContent);
|
||||
if (exactIndex !== -1) {
|
||||
return {
|
||||
startIndex: exactIndex,
|
||||
endIndex: exactIndex + searchContent.length,
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback: try trimmed content match
|
||||
const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
|
||||
if (trimmedIndex !== -1) {
|
||||
return {
|
||||
startIndex: trimmedIndex,
|
||||
endIndex: trimmedIndex + trimmedSearchContent.length,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
390
core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts
Normal file
390
core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts
Normal file
|
|
@ -0,0 +1,390 @@
|
|||
import {
|
||||
parseAllSearchReplaceBlocks,
|
||||
parseSearchReplaceBlock,
|
||||
} from "./parseSearchReplaceBlock";
|
||||
|
||||
describe("parseSearchReplaceBlock", () => {
|
||||
describe("Complete blocks", () => {
|
||||
it("should parse a complete basic search/replace block", () => {
|
||||
const content = `------- SEARCH
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}
|
||||
=======
|
||||
// Resets the calculator result to 0 and returns the instance for method chaining
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe(`reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}`);
|
||||
expect(result.replaceContent)
|
||||
.toBe(`// Resets the calculator result to 0 and returns the instance for method chaining
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}`);
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle different marker lengths", () => {
|
||||
const content = `------- SEARCH
|
||||
old content
|
||||
=========
|
||||
new content
|
||||
+++++++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("old content");
|
||||
expect(result.replaceContent).toBe("new content");
|
||||
});
|
||||
|
||||
it("should handle empty search content", () => {
|
||||
const content = `------- SEARCH
|
||||
=======
|
||||
new content
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("");
|
||||
expect(result.replaceContent).toBe("new content");
|
||||
});
|
||||
|
||||
it("should handle empty replace content (deletion)", () => {
|
||||
const content = `------- SEARCH
|
||||
old content to delete
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("old content to delete");
|
||||
expect(result.replaceContent).toBe("");
|
||||
});
|
||||
|
||||
it("should handle both empty search and replace content", () => {
|
||||
const content = `------- SEARCH
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("");
|
||||
expect(result.replaceContent).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Incomplete blocks", () => {
|
||||
it("should handle incomplete search block", () => {
|
||||
const content = `------- SEARCH
|
||||
some content`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.searchContent).toBe("some content");
|
||||
expect(result.replaceContent).toBe("");
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle incomplete replace block", () => {
|
||||
const content = `------- SEARCH
|
||||
old content
|
||||
=======
|
||||
new content`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.searchContent).toBe("old content");
|
||||
expect(result.replaceContent).toBe("new content");
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error cases", () => {
|
||||
it("should error on search end without start", () => {
|
||||
const content = `=======
|
||||
some content
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.error).toBe(
|
||||
"Found search block end marker without matching start marker",
|
||||
);
|
||||
});
|
||||
|
||||
it("should error on replace end without replace start", () => {
|
||||
const content = `+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.error).toBe(
|
||||
"Found replace block end marker without matching replace start marker",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Regex pattern validation", () => {
|
||||
it("should match various search start patterns", () => {
|
||||
const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"];
|
||||
|
||||
patterns.forEach((pattern) => {
|
||||
const content = `${pattern}
|
||||
content
|
||||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should match various search end patterns", () => {
|
||||
const patterns = ["===", "=======", "=============="];
|
||||
|
||||
patterns.forEach((pattern) => {
|
||||
const content = `------- SEARCH
|
||||
content
|
||||
${pattern}
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should match various replace end patterns", () => {
|
||||
const patterns = [
|
||||
"+++ REPLACE",
|
||||
"+++++++ REPLACE",
|
||||
"+++++++++++ REPLACE",
|
||||
];
|
||||
|
||||
patterns.forEach((pattern) => {
|
||||
const content = `------- SEARCH
|
||||
content
|
||||
=======
|
||||
replacement
|
||||
${pattern}`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not match invalid patterns", () => {
|
||||
const invalidPatterns = [
|
||||
"-- SEARCH", // Too few dashes
|
||||
"SEARCH", // No markers
|
||||
"== SEARCH", // Wrong markers
|
||||
"=== REPLACE", // Wrong end marker
|
||||
"++++ SEARCH", // Wrong markers for search
|
||||
];
|
||||
|
||||
invalidPatterns.forEach((pattern) => {
|
||||
const content = `${pattern}
|
||||
content`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.searchContent).toBe(""); // Should not enter search mode
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseAllSearchReplaceBlocks", () => {
|
||||
it("should parse multiple complete blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
old code 1
|
||||
=======
|
||||
new code 1
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
old code 2
|
||||
=======
|
||||
new code 2
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("old code 1");
|
||||
expect(blocks[0].replaceContent).toBe("new code 1");
|
||||
expect(blocks[1].searchContent).toBe("old code 2");
|
||||
expect(blocks[1].replaceContent).toBe("new code 2");
|
||||
});
|
||||
|
||||
it("should handle blocks with different content", () => {
|
||||
const content = `------- SEARCH
|
||||
function old() {
|
||||
return 1;
|
||||
}
|
||||
=======
|
||||
function new() {
|
||||
return 2;
|
||||
}
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
const x = 'old';
|
||||
=======
|
||||
const x = 'new';
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe(`function old() {
|
||||
return 1;
|
||||
}`);
|
||||
expect(blocks[0].replaceContent).toBe(`function new() {
|
||||
return 2;
|
||||
}`);
|
||||
expect(blocks[1].searchContent).toBe(`const x = 'old';`);
|
||||
expect(blocks[1].replaceContent).toBe(`const x = 'new';`);
|
||||
});
|
||||
|
||||
it("should handle deletion blocks (empty replace content)", () => {
|
||||
const content = `------- SEARCH
|
||||
code to keep
|
||||
=======
|
||||
modified code
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
code to delete
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("code to keep");
|
||||
expect(blocks[0].replaceContent).toBe("modified code");
|
||||
expect(blocks[1].searchContent).toBe("code to delete");
|
||||
expect(blocks[1].replaceContent).toBe(""); // Deletion
|
||||
});
|
||||
|
||||
it("should handle insertion blocks (empty search content)", () => {
|
||||
const content = `------- SEARCH
|
||||
existing code
|
||||
=======
|
||||
modified existing code
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
=======
|
||||
new code to insert
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("existing code");
|
||||
expect(blocks[0].replaceContent).toBe("modified existing code");
|
||||
expect(blocks[1].searchContent).toBe(""); // Insertion
|
||||
expect(blocks[1].replaceContent).toBe("new code to insert");
|
||||
});
|
||||
|
||||
it("should skip incomplete blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
incomplete block
|
||||
|
||||
------- SEARCH
|
||||
complete block
|
||||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(1);
|
||||
expect(blocks[0].searchContent).toBe("complete block");
|
||||
expect(blocks[0].replaceContent).toBe("replacement");
|
||||
});
|
||||
|
||||
it("should handle single block", () => {
|
||||
const content = `------- SEARCH
|
||||
single block
|
||||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(1);
|
||||
expect(blocks[0].searchContent).toBe("single block");
|
||||
expect(blocks[0].replaceContent).toBe("replacement");
|
||||
});
|
||||
|
||||
it("should return empty array when no complete blocks found", () => {
|
||||
const content = `------- SEARCH
|
||||
incomplete
|
||||
=======
|
||||
missing replace marker`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle blocks with extra content between them", () => {
|
||||
const content = `Some other content here
|
||||
|
||||
------- SEARCH
|
||||
block 1
|
||||
=======
|
||||
replacement 1
|
||||
+++++++ REPLACE
|
||||
|
||||
More content in between
|
||||
|
||||
------- SEARCH
|
||||
block 2
|
||||
=======
|
||||
replacement 2
|
||||
+++++++ REPLACE
|
||||
|
||||
Trailing content`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("block 1");
|
||||
expect(blocks[0].replaceContent).toBe("replacement 1");
|
||||
expect(blocks[1].searchContent).toBe("block 2");
|
||||
expect(blocks[1].replaceContent).toBe("replacement 2");
|
||||
});
|
||||
|
||||
it("should throw error for malformed blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
content
|
||||
+++++++ REPLACE`; // Missing =======
|
||||
|
||||
expect(() => parseAllSearchReplaceBlocks(content)).toThrow(
|
||||
"Found replace block end marker without matching replace start marker",
|
||||
);
|
||||
});
|
||||
});
|
||||
147
core/edit/searchAndReplace/parseSearchReplaceBlock.ts
Normal file
147
core/edit/searchAndReplace/parseSearchReplaceBlock.ts
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
// Search and replace block markers using flexible regex patterns
|
||||
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/;
|
||||
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/;
|
||||
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/;
|
||||
|
||||
export interface SearchReplaceBlockResult {
|
||||
/** Whether a complete search/replace block has been parsed */
|
||||
isComplete: boolean;
|
||||
/** The content to search for in the file */
|
||||
searchContent?: string;
|
||||
/** The content to replace the search content with */
|
||||
replaceContent?: string;
|
||||
/** Error message if parsing failed */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a search and replace block from content.
|
||||
*
|
||||
* Expected format:
|
||||
* ------- SEARCH
|
||||
* [content to find]
|
||||
* =======
|
||||
* [content to replace with]
|
||||
* +++++++ REPLACE
|
||||
*
|
||||
* @param content - The content to parse
|
||||
* @returns ParseResult with completion status and extracted content
|
||||
*/
|
||||
export function parseSearchReplaceBlock(
|
||||
content: string,
|
||||
): SearchReplaceBlockResult {
|
||||
const lines = content.split("\n");
|
||||
|
||||
let currentSearchContent = "";
|
||||
let currentReplaceContent = "";
|
||||
let inSearch = false;
|
||||
let inReplace = false;
|
||||
|
||||
for (const line of lines) {
|
||||
if (SEARCH_BLOCK_START_REGEX.test(line)) {
|
||||
inSearch = true;
|
||||
inReplace = false;
|
||||
currentSearchContent = "";
|
||||
currentReplaceContent = "";
|
||||
continue;
|
||||
}
|
||||
|
||||
if (SEARCH_BLOCK_END_REGEX.test(line)) {
|
||||
if (!inSearch) {
|
||||
return {
|
||||
isComplete: false,
|
||||
error: "Found search block end marker without matching start marker",
|
||||
};
|
||||
}
|
||||
inSearch = false;
|
||||
inReplace = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (REPLACE_BLOCK_END_REGEX.test(line)) {
|
||||
if (!inReplace) {
|
||||
return {
|
||||
isComplete: false,
|
||||
error:
|
||||
"Found replace block end marker without matching replace start marker",
|
||||
};
|
||||
}
|
||||
|
||||
// Complete block found
|
||||
return {
|
||||
isComplete: true,
|
||||
searchContent: currentSearchContent.trim(),
|
||||
replaceContent: currentReplaceContent.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
// Accumulate content
|
||||
if (inSearch) {
|
||||
currentSearchContent += line + "\n";
|
||||
} else if (inReplace) {
|
||||
currentReplaceContent += line + "\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Block is not yet complete
|
||||
return {
|
||||
isComplete: false,
|
||||
searchContent: currentSearchContent.trim(),
|
||||
replaceContent: currentReplaceContent.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses all complete search and replace blocks from content.
|
||||
*
|
||||
* @param content - The content containing multiple search/replace blocks
|
||||
* @returns Array of complete search/replace blocks found
|
||||
* @throws Error if any malformed blocks are encountered
|
||||
*/
|
||||
export function parseAllSearchReplaceBlocks(
|
||||
content: string,
|
||||
): SearchReplaceBlockResult[] {
|
||||
const blocks: SearchReplaceBlockResult[] = [];
|
||||
const lines = content.split("\n");
|
||||
|
||||
let currentBlockLines: string[] = [];
|
||||
let inBlock = false;
|
||||
|
||||
for (const line of lines) {
|
||||
if (SEARCH_BLOCK_START_REGEX.test(line)) {
|
||||
// Start of new block
|
||||
if (inBlock && currentBlockLines.length > 0) {
|
||||
// Process previous incomplete block if any
|
||||
const blockContent = currentBlockLines.join("\n");
|
||||
const result = parseSearchReplaceBlock(blockContent);
|
||||
if (result.isComplete) {
|
||||
blocks.push(result);
|
||||
} else if (result.error) {
|
||||
// Fail fast on any parsing error
|
||||
throw new Error(result.error);
|
||||
}
|
||||
// If incomplete but no error, it's just a partial block - continue processing
|
||||
}
|
||||
currentBlockLines = [line];
|
||||
inBlock = true;
|
||||
} else if (inBlock) {
|
||||
currentBlockLines.push(line);
|
||||
|
||||
// Check if this line completes the current block
|
||||
if (REPLACE_BLOCK_END_REGEX.test(line)) {
|
||||
const blockContent = currentBlockLines.join("\n");
|
||||
const result = parseSearchReplaceBlock(blockContent);
|
||||
if (result.isComplete) {
|
||||
blocks.push(result);
|
||||
} else if (result.error) {
|
||||
// Fail fast on any parsing error
|
||||
throw new Error(result.error);
|
||||
}
|
||||
currentBlockLines = [];
|
||||
inBlock = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
|
@ -66,7 +66,6 @@ export async function* streamDiffLines({
|
|||
abortController,
|
||||
input,
|
||||
language,
|
||||
onlyOneInsertion,
|
||||
overridePrompt,
|
||||
rulesToInclude,
|
||||
}: {
|
||||
|
|
@ -77,7 +76,6 @@ export async function* streamDiffLines({
|
|||
abortController: AbortController;
|
||||
input: string;
|
||||
language: string | undefined;
|
||||
onlyOneInsertion: boolean;
|
||||
overridePrompt: ChatMessage[] | undefined;
|
||||
rulesToInclude: RuleWithSource[] | undefined;
|
||||
}): AsyncGenerator<DiffLine> {
|
||||
|
|
@ -112,7 +110,7 @@ export async function* streamDiffLines({
|
|||
// If any rules are present this will result in using chat instead of legacy completion
|
||||
const systemMessage = rulesToInclude
|
||||
? getSystemMessageWithRules({
|
||||
rules: rulesToInclude,
|
||||
availableRules: rulesToInclude,
|
||||
userMessage:
|
||||
typeof prompt === "string"
|
||||
? ({
|
||||
|
|
@ -125,7 +123,7 @@ export async function* streamDiffLines({
|
|||
) as UserChatMessage | ToolResultChatMessage | undefined),
|
||||
baseSystemMessage: undefined,
|
||||
contextItems: [],
|
||||
})
|
||||
}).systemMessage
|
||||
: undefined;
|
||||
|
||||
if (systemMessage) {
|
||||
|
|
@ -182,13 +180,7 @@ export async function* streamDiffLines({
|
|||
diffLines = addIndentation(diffLines, indentation);
|
||||
}
|
||||
|
||||
let seenGreen = false;
|
||||
for await (const diffLine of diffLines) {
|
||||
yield diffLine;
|
||||
if (diffLine.type === "new") {
|
||||
seenGreen = true;
|
||||
} else if (onlyOneInsertion && seenGreen && diffLine.type === "same") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
92
core/index.d.ts
vendored
92
core/index.d.ts
vendored
|
|
@ -57,6 +57,7 @@ export interface IndexingProgressUpdate {
|
|||
| "disabled"
|
||||
| "cancelled";
|
||||
debugInfo?: string;
|
||||
warnings?: string[];
|
||||
}
|
||||
|
||||
// This is more or less a V2 of IndexingProgressUpdate for docs etc.
|
||||
|
|
@ -443,6 +444,7 @@ interface ToolCallState {
|
|||
status: ToolStatus;
|
||||
parsedArgs: any;
|
||||
output?: ContextItem[];
|
||||
tool?: Tool;
|
||||
}
|
||||
|
||||
interface Reasoning {
|
||||
|
|
@ -838,15 +840,44 @@ export interface ContinueSDK {
|
|||
abortController: AbortController;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */
|
||||
export interface SlashCommandDescription {
|
||||
name: string;
|
||||
description: string;
|
||||
prompt?: string;
|
||||
params?: { [key: string]: any };
|
||||
promptFile?: string;
|
||||
}
|
||||
|
||||
export interface SlashCommand extends SlashCommandDescription {
|
||||
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
|
||||
}
|
||||
|
||||
export interface SlashCommandWithSource extends SlashCommandDescription {
|
||||
run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy
|
||||
source: SlashCommandSource;
|
||||
promptFile?: string;
|
||||
overrideSystemMessage?: string;
|
||||
}
|
||||
|
||||
export type SlashCommandSource =
|
||||
| "built-in-legacy"
|
||||
| "built-in"
|
||||
| "json-custom-command"
|
||||
| "config-ts-slash-command"
|
||||
| "yaml-prompt-block"
|
||||
| "mcp-prompt"
|
||||
| "prompt-file-v1"
|
||||
| "prompt-file-v2"
|
||||
| "invokable-rule";
|
||||
|
||||
export interface SlashCommandDescWithSource extends SlashCommandDescription {
|
||||
isLegacy: boolean; // Maps to if slashcommand.run exists
|
||||
source: SlashCommandSource;
|
||||
promptFile?: string;
|
||||
mcpServerName?: string;
|
||||
mcpArgs?: MCPPromptArgs;
|
||||
}
|
||||
|
||||
// Config
|
||||
|
||||
export type StepName =
|
||||
|
|
@ -947,8 +978,6 @@ export interface ContextProviderWithParams {
|
|||
params: { [key: string]: any };
|
||||
}
|
||||
|
||||
export type SlashCommandDescription = Omit<SlashCommand, "run">;
|
||||
|
||||
export interface CustomCommand {
|
||||
name: string;
|
||||
prompt: string;
|
||||
|
|
@ -1009,6 +1038,7 @@ interface ToolChoice {
|
|||
|
||||
export interface ConfigDependentToolParams {
|
||||
rules: RuleWithSource[];
|
||||
enableExperimentalTools: boolean;
|
||||
}
|
||||
|
||||
export type GetTool = (params: ConfigDependentToolParams) => Tool;
|
||||
|
|
@ -1172,14 +1202,16 @@ export type MCPConnectionStatus =
|
|||
| "error"
|
||||
| "not-connected";
|
||||
|
||||
export type MCPPromptArgs = {
|
||||
name: string;
|
||||
description?: string;
|
||||
required?: boolean;
|
||||
}[];
|
||||
|
||||
export interface MCPPrompt {
|
||||
name: string;
|
||||
description?: string;
|
||||
arguments?: {
|
||||
name: string;
|
||||
description?: string;
|
||||
required?: boolean;
|
||||
}[];
|
||||
arguments?: MCPPromptArgs;
|
||||
}
|
||||
|
||||
// Leaving here to ideate on
|
||||
|
|
@ -1228,6 +1260,7 @@ export interface ContinueUIConfig {
|
|||
codeWrap?: boolean;
|
||||
showSessionTabs?: boolean;
|
||||
autoAcceptEditToolDiffs?: boolean;
|
||||
logEditingData?: boolean;
|
||||
}
|
||||
|
||||
export interface ContextMenuConfig {
|
||||
|
|
@ -1291,6 +1324,14 @@ export interface ShowFilePayload {
|
|||
filepath: string;
|
||||
}
|
||||
|
||||
export interface ApplyToFilePayload {
|
||||
streamId: string;
|
||||
filepath?: string;
|
||||
text: string;
|
||||
toolCallId?: string;
|
||||
isSearchAndReplace?: boolean;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
filepath: string;
|
||||
range: {
|
||||
|
|
@ -1300,6 +1341,16 @@ export interface RangeInFileWithContents {
|
|||
contents: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithNextEditInfo {
|
||||
filepath: string;
|
||||
range: Range;
|
||||
fileContents: string;
|
||||
editText: string;
|
||||
afterCursorPos: Position;
|
||||
beforeCursorPos: Position;
|
||||
workspaceDir: string;
|
||||
}
|
||||
|
||||
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
|
||||
|
||||
/**
|
||||
|
|
@ -1336,6 +1387,7 @@ export interface ExperimentalConfig {
|
|||
modelRoles?: ExperimentalModelRoles;
|
||||
defaultContext?: DefaultContextProvider[];
|
||||
promptPath?: string;
|
||||
enableExperimentalTools?: boolean;
|
||||
|
||||
/**
|
||||
* Quick actions are a way to add custom commands to the Code Lens of
|
||||
|
|
@ -1360,6 +1412,22 @@ export interface ExperimentalConfig {
|
|||
* If enabled, will add the current file as context.
|
||||
*/
|
||||
useCurrentFileAsContext?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, will save data on the user's editing processes
|
||||
*/
|
||||
logEditingData?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, will enable next edit in place of autocomplete
|
||||
*/
|
||||
optInNextEditFeature?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, @codebase will only use tool calling
|
||||
* instead of embeddings, FTS, recently edited files, etc.
|
||||
*/
|
||||
codebaseToolCallingOnly?: boolean;
|
||||
}
|
||||
|
||||
export interface AnalyticsConfig {
|
||||
|
|
@ -1444,7 +1512,7 @@ export interface Config {
|
|||
/** Request options that will be applied to all models and context providers */
|
||||
requestOptions?: RequestOptions;
|
||||
/** The list of slash commands that will be available in the sidebar */
|
||||
slashCommands?: SlashCommand[];
|
||||
slashCommands?: (SlashCommand | SlashCommandWithSource)[];
|
||||
/** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders.
|
||||
* A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title <query>', Continue will call `getContextItems(query)`.
|
||||
*/
|
||||
|
|
@ -1481,7 +1549,7 @@ export interface ContinueConfig {
|
|||
// systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
slashCommands: SlashCommand[];
|
||||
slashCommands: SlashCommandWithSource[];
|
||||
contextProviders: IContextProvider[];
|
||||
disableSessionTitles?: boolean;
|
||||
disableIndexing?: boolean;
|
||||
|
|
@ -1504,7 +1572,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
// systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
slashCommands: SlashCommandDescription[];
|
||||
slashCommands: SlashCommandDescWithSource[];
|
||||
contextProviders: ContextProviderDescription[];
|
||||
disableIndexing?: boolean;
|
||||
disableSessionTitles?: boolean;
|
||||
|
|
|
|||
|
|
@ -35,7 +35,8 @@ type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
|
|||
|
||||
export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
||||
relativeExpectedTime: number = 1;
|
||||
artifactId = "codeSnippets";
|
||||
static artifactId = "codeSnippets";
|
||||
artifactId: string = CodeSnippetsCodebaseIndex.artifactId;
|
||||
|
||||
constructor(private readonly ide: IDE) {}
|
||||
|
||||
|
|
@ -220,7 +221,6 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
// Compute
|
||||
for (let i = 0; i < results.compute.length; i++) {
|
||||
const compute = results.compute[i];
|
||||
|
||||
let snippets: SnippetChunk[] = [];
|
||||
try {
|
||||
snippets = await this.getSnippetsInFile(
|
||||
|
|
|
|||
|
|
@ -48,6 +48,16 @@ export class CodebaseIndexer {
|
|||
private codebaseIndexingState: IndexingProgressUpdate;
|
||||
private readonly pauseToken: PauseToken;
|
||||
|
||||
private getUserFriendlyIndexName(artifactId: string): string {
|
||||
if (artifactId === FullTextSearchCodebaseIndex.artifactId)
|
||||
return "Full text search";
|
||||
if (artifactId === CodeSnippetsCodebaseIndex.artifactId)
|
||||
return "Code snippets";
|
||||
if (artifactId === ChunkCodebaseIndex.artifactId) return "Chunking";
|
||||
if (artifactId.startsWith("vectordb")) return "Embedding";
|
||||
return artifactId; // fallback to original
|
||||
}
|
||||
|
||||
// Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
|
||||
// e.g. a `SQLITE_BUSY` error.
|
||||
errorsRegexesToClearIndexesOn = [
|
||||
|
|
@ -314,6 +324,7 @@ export class CodebaseIndexer {
|
|||
status: "loading",
|
||||
};
|
||||
const beginTime = Date.now();
|
||||
let collectedWarnings: string[] = [];
|
||||
|
||||
for (const directory of dirs) {
|
||||
const dirBasename = getUriPathBasename(directory);
|
||||
|
|
@ -344,45 +355,52 @@ export class CodebaseIndexer {
|
|||
const repoName = await this.ide.getRepoName(directory);
|
||||
let nextLogThreshold = 0;
|
||||
|
||||
try {
|
||||
for await (const updateDesc of this.indexFiles(
|
||||
directory,
|
||||
directoryFiles,
|
||||
branch,
|
||||
repoName,
|
||||
)) {
|
||||
// Handle pausing in this loop because it's the only one really taking time
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
progress: 0,
|
||||
desc: "Indexing cancelled",
|
||||
status: "cancelled",
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (this.pauseToken.paused) {
|
||||
yield* this.yieldUpdateAndPause();
|
||||
}
|
||||
yield updateDesc;
|
||||
if (updateDesc.progress >= nextLogThreshold) {
|
||||
// log progress every 2.5%
|
||||
nextLogThreshold += 0.025;
|
||||
this.logProgress(
|
||||
beginTime,
|
||||
Math.floor(directoryFiles.length * updateDesc.progress),
|
||||
updateDesc.progress,
|
||||
);
|
||||
}
|
||||
for await (const updateDesc of this.indexFiles(
|
||||
directory,
|
||||
directoryFiles,
|
||||
branch,
|
||||
repoName,
|
||||
)) {
|
||||
// Handle pausing in this loop because it's the only one really taking time
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
progress: 0,
|
||||
desc: "Indexing cancelled",
|
||||
status: "cancelled",
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (this.pauseToken.paused) {
|
||||
yield* this.yieldUpdateAndPause();
|
||||
}
|
||||
|
||||
// Collect warnings from indexFiles
|
||||
if (updateDesc.warnings && updateDesc.warnings.length > 0) {
|
||||
collectedWarnings = [...updateDesc.warnings];
|
||||
}
|
||||
|
||||
yield updateDesc;
|
||||
if (updateDesc.progress >= nextLogThreshold) {
|
||||
// log progress every 2.5%
|
||||
nextLogThreshold += 0.025;
|
||||
this.logProgress(
|
||||
beginTime,
|
||||
Math.floor(directoryFiles.length * updateDesc.progress),
|
||||
updateDesc.progress,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
yield this.handleErrorAndGetProgressUpdate(err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Final completion message with preserved warnings
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: "Indexing Complete",
|
||||
desc:
|
||||
collectedWarnings.length > 0
|
||||
? `Indexing completed with ${collectedWarnings.length} warning(s)`
|
||||
: "Indexing Complete",
|
||||
status: "done",
|
||||
warnings: collectedWarnings.length > 0 ? collectedWarnings : undefined,
|
||||
};
|
||||
this.logProgress(beginTime, 0, 1);
|
||||
}
|
||||
|
|
@ -490,6 +508,8 @@ export class CodebaseIndexer {
|
|||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
let completedIndexCount = 0;
|
||||
let progress = 0;
|
||||
const warnings: string[] = [];
|
||||
|
||||
for (const codebaseIndex of indexesToBuild) {
|
||||
const tag: IndexTag = {
|
||||
directory,
|
||||
|
|
@ -500,45 +520,101 @@ export class CodebaseIndexer {
|
|||
progress: progress,
|
||||
desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
|
||||
status: "indexing",
|
||||
warnings: warnings.length > 0 ? [...warnings] : undefined,
|
||||
};
|
||||
const [results, lastUpdated, markComplete] =
|
||||
await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
{ ...stats },
|
||||
(filepath) => this.ide.readFile(filepath),
|
||||
repoName,
|
||||
);
|
||||
const totalOps = this.totalIndexOps(results);
|
||||
let completedOps = 0;
|
||||
|
||||
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
|
||||
if (totalOps > 0) {
|
||||
for (const subResult of this.batchRefreshIndexResults(results)) {
|
||||
for await (const { desc } of codebaseIndex.update(
|
||||
try {
|
||||
const [results, lastUpdated, markComplete] =
|
||||
await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
subResult,
|
||||
markComplete,
|
||||
{ ...stats },
|
||||
(filepath) => this.ide.readFile(filepath),
|
||||
repoName,
|
||||
)) {
|
||||
yield {
|
||||
progress,
|
||||
desc,
|
||||
status: "indexing",
|
||||
};
|
||||
}
|
||||
completedOps +=
|
||||
subResult.compute.length +
|
||||
subResult.del.length +
|
||||
subResult.addTag.length +
|
||||
subResult.removeTag.length;
|
||||
progress =
|
||||
(completedIndexCount + completedOps / totalOps) *
|
||||
(1 / indexesToBuild.length);
|
||||
}
|
||||
}
|
||||
);
|
||||
const totalOps = this.totalIndexOps(results);
|
||||
let completedOps = 0;
|
||||
|
||||
await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
|
||||
completedIndexCount += 1;
|
||||
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
|
||||
if (totalOps > 0) {
|
||||
for (const subResult of this.batchRefreshIndexResults(results)) {
|
||||
try {
|
||||
for await (const { desc } of codebaseIndex.update(
|
||||
tag,
|
||||
subResult,
|
||||
markComplete,
|
||||
repoName,
|
||||
)) {
|
||||
yield {
|
||||
progress,
|
||||
desc,
|
||||
status: "indexing",
|
||||
warnings: warnings.length > 0 ? [...warnings] : undefined,
|
||||
};
|
||||
}
|
||||
completedOps +=
|
||||
subResult.compute.length +
|
||||
subResult.del.length +
|
||||
subResult.addTag.length +
|
||||
subResult.removeTag.length;
|
||||
progress =
|
||||
(completedIndexCount + completedOps / totalOps) *
|
||||
(1 / indexesToBuild.length);
|
||||
} catch (err) {
|
||||
// Collect non-fatal errors as warnings and continue
|
||||
const warningMsg =
|
||||
err instanceof Error ? err.message : String(err);
|
||||
const friendlyName = this.getUserFriendlyIndexName(
|
||||
codebaseIndex.artifactId,
|
||||
);
|
||||
warnings.push(`${friendlyName}: ${warningMsg}`);
|
||||
console.warn(`${friendlyName}: ${warningMsg}`, err);
|
||||
|
||||
// Complete this batch and continue with next
|
||||
completedOps +=
|
||||
subResult.compute.length +
|
||||
subResult.del.length +
|
||||
subResult.addTag.length +
|
||||
subResult.removeTag.length;
|
||||
progress =
|
||||
(completedIndexCount + completedOps / totalOps) *
|
||||
(1 / indexesToBuild.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
|
||||
completedIndexCount += 1;
|
||||
} catch (err) {
|
||||
// Handle errors during planning phase
|
||||
const cause = getRootCause(err as Error);
|
||||
if (cause instanceof LLMError) {
|
||||
// LLM errors are critical, re-throw them
|
||||
throw cause;
|
||||
}
|
||||
|
||||
// Collect planning errors as warnings and continue to next index
|
||||
const errorMsg = err instanceof Error ? err.message : String(err);
|
||||
const friendlyName = this.getUserFriendlyIndexName(
|
||||
codebaseIndex.artifactId,
|
||||
);
|
||||
warnings.push(`${friendlyName}: ${errorMsg}`);
|
||||
console.warn(
|
||||
`Warning during ${codebaseIndex.artifactId} planning:`,
|
||||
err,
|
||||
);
|
||||
completedIndexCount += 1;
|
||||
progress = completedIndexCount * (1 / indexesToBuild.length);
|
||||
}
|
||||
}
|
||||
|
||||
// Final update with any collected warnings
|
||||
if (warnings.length > 0) {
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: `Indexing completed with ${warnings.length} warning(s)`,
|
||||
status: "done",
|
||||
warnings: [...warnings],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -55,7 +55,6 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
for (let i = 0; i < results.compute.length; i++) {
|
||||
const item = results.compute[i];
|
||||
|
||||
// Insert chunks
|
||||
const chunks = await db.all(
|
||||
"SELECT * FROM chunks WHERE path = ? AND cacheKey = ?",
|
||||
|
|
@ -68,7 +67,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
[item.path, chunk.content],
|
||||
);
|
||||
await db.run(
|
||||
`INSERT INTO fts_metadata (id, path, cacheKey, chunkId)
|
||||
`INSERT INTO fts_metadata (id, path, cacheKey, chunkId)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
path = excluded.path,
|
||||
|
|
|
|||
|
|
@ -20,10 +20,10 @@ The indexing process does the following:
|
|||
|
||||
All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.ts) if they are to be used.
|
||||
|
||||
`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
|
||||
`CodeSnippetsIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
|
||||
`FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5
|
||||
`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex`
|
||||
`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.
|
||||
`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbIndex`
|
||||
`LanceDbIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.
|
||||
|
||||
## Known problems
|
||||
|
||||
|
|
|
|||
|
|
@ -981,17 +981,11 @@ export default class DocsService {
|
|||
// Otherwise sync the index based on config changes
|
||||
const oldConfigDocs = oldConfig?.docs || [];
|
||||
const newConfigDocs = newConfig.docs || [];
|
||||
const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl);
|
||||
|
||||
// NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here
|
||||
const currentlyIndexedDocs = await this.listMetadata();
|
||||
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
|
||||
|
||||
// Anything found in sqlite but not in new config should be deleted
|
||||
const deletedDocs = currentlyIndexedDocs.filter(
|
||||
(doc) => !newConfigStartUrls.includes(doc.startUrl),
|
||||
);
|
||||
|
||||
// Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
|
||||
// TODO if only favicon and title change, only update, don't embed
|
||||
// Otherwise anything found in new config that isn't in sqlite should be added/indexed
|
||||
|
|
@ -1038,10 +1032,6 @@ export default class DocsService {
|
|||
...changedDocs.map((doc) => this.indexAndAdd(doc, true)),
|
||||
...addedDocs.map((doc) => this.indexAndAdd(doc)),
|
||||
]);
|
||||
|
||||
for (const doc of deletedDocs) {
|
||||
await this.deleteIndexes(doc.startUrl);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error syncing docs index on config update", e);
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -187,7 +187,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
|
|||
lower.includes("gemini") ||
|
||||
lower.includes("grok") ||
|
||||
lower.includes("moonshot") ||
|
||||
lower.includes("mercury")
|
||||
lower.includes("mercury") ||
|
||||
/^o\d/.test(lower)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
|
|
|||
190
core/llm/autodetect.vitest.ts
Normal file
190
core/llm/autodetect.vitest.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import { expect, test } from "vitest";
|
||||
import { autodetectTemplateType } from "./autodetect";
|
||||
|
||||
test("autodetectTemplateType returns 'codellama-70b' for CodeLlama 70B models", () => {
|
||||
expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b");
|
||||
expect(autodetectTemplateType("CodeLlama-70B")).toBe("codellama-70b");
|
||||
expect(autodetectTemplateType("codellama-70b-instruct")).toBe(
|
||||
"codellama-70b",
|
||||
);
|
||||
expect(autodetectTemplateType("CodeLlama-70B-Python")).toBe("codellama-70b");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns undefined for models that don't need templates", () => {
|
||||
expect(autodetectTemplateType("gpt-4")).toBe(undefined);
|
||||
expect(autodetectTemplateType("gpt-3.5-turbo")).toBe(undefined);
|
||||
expect(autodetectTemplateType("GPT-4")).toBe(undefined);
|
||||
expect(autodetectTemplateType("command-r")).toBe(undefined);
|
||||
expect(autodetectTemplateType("aya-23")).toBe(undefined);
|
||||
expect(autodetectTemplateType("chat-bison")).toBe(undefined);
|
||||
expect(autodetectTemplateType("pplx-70b")).toBe(undefined);
|
||||
expect(autodetectTemplateType("gemini-pro")).toBe(undefined);
|
||||
expect(autodetectTemplateType("grok-beta")).toBe(undefined);
|
||||
expect(autodetectTemplateType("moonshot-v1")).toBe(undefined);
|
||||
expect(autodetectTemplateType("mercury-chat")).toBe(undefined);
|
||||
expect(autodetectTemplateType("mercury-chat")).toBe(undefined);
|
||||
expect(autodetectTemplateType("o3-mini")).toBe(undefined);
|
||||
expect(autodetectTemplateType("o4")).toBe(undefined);
|
||||
expect(autodetectTemplateType("claude-sonnet-4-20250514")).toBe("none");
|
||||
expect(autodetectTemplateType("claude-3-7-sonnet-latest")).toBe("none");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'llama3' for Llama 3 models", () => {
|
||||
expect(autodetectTemplateType("llama3")).toBe("llama3");
|
||||
expect(autodetectTemplateType("llama-3")).toBe("llama3");
|
||||
expect(autodetectTemplateType("Llama3-8B")).toBe("llama3");
|
||||
expect(autodetectTemplateType("llama-3:70b")).toBe("llama3");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'llava' for LLaVA models", () => {
|
||||
expect(autodetectTemplateType("llava")).toBe("llava");
|
||||
expect(autodetectTemplateType("LLaVA")).toBe("llava");
|
||||
expect(autodetectTemplateType("llava-1.5")).toBe("llava");
|
||||
expect(autodetectTemplateType("llava-v1.6")).toBe("llava");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'zephyr' for TinyLlama models", () => {
|
||||
expect(autodetectTemplateType("tinyllama")).toBe("zephyr");
|
||||
expect(autodetectTemplateType("TinyLlama")).toBe("zephyr");
|
||||
expect(autodetectTemplateType("tinyllama-1.1b")).toBe("zephyr");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'xwin-coder' for XWin models", () => {
|
||||
expect(autodetectTemplateType("xwin")).toBe("xwin-coder");
|
||||
expect(autodetectTemplateType("XWin")).toBe("xwin-coder");
|
||||
expect(autodetectTemplateType("xwin-coder")).toBe("xwin-coder");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'chatml' for Dolphin models", () => {
|
||||
expect(autodetectTemplateType("dolphin")).toBe("chatml");
|
||||
expect(autodetectTemplateType("Dolphin")).toBe("chatml");
|
||||
expect(autodetectTemplateType("dolphin-2.1")).toBe("chatml");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'gemma' for Gemma models", () => {
|
||||
expect(autodetectTemplateType("gemma")).toBe("gemma");
|
||||
expect(autodetectTemplateType("Gemma")).toBe("gemma");
|
||||
expect(autodetectTemplateType("gemma-7b")).toBe("gemma");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'phi2' for Phi-2 models", () => {
|
||||
expect(autodetectTemplateType("phi2")).toBe("phi2");
|
||||
expect(autodetectTemplateType("Phi2")).toBe("phi2");
|
||||
expect(autodetectTemplateType("microsoft-phi2")).toBe("phi2");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'phind' for Phind models", () => {
|
||||
expect(autodetectTemplateType("phind")).toBe("phind");
|
||||
expect(autodetectTemplateType("Phind")).toBe("phind");
|
||||
expect(autodetectTemplateType("phind-codellama")).toBe("phind");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'llama2' for general Llama models", () => {
|
||||
expect(autodetectTemplateType("llama")).toBe("llama2");
|
||||
expect(autodetectTemplateType("Llama")).toBe("llama2");
|
||||
expect(autodetectTemplateType("llama2")).toBe("llama2");
|
||||
expect(autodetectTemplateType("llama-2")).toBe("llama2");
|
||||
expect(autodetectTemplateType("codellama")).toBe("llama2");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'zephyr' for Zephyr models", () => {
|
||||
expect(autodetectTemplateType("zephyr")).toBe("zephyr");
|
||||
expect(autodetectTemplateType("Zephyr")).toBe("zephyr");
|
||||
expect(autodetectTemplateType("zephyr-7b")).toBe("zephyr");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'none' for Claude models", () => {
|
||||
expect(autodetectTemplateType("claude")).toBe("none");
|
||||
expect(autodetectTemplateType("Claude")).toBe("none");
|
||||
expect(autodetectTemplateType("claude-3")).toBe("none");
|
||||
expect(autodetectTemplateType("claude-3-opus")).toBe("none");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'none' for Codestral models", () => {
|
||||
expect(autodetectTemplateType("codestral")).toBe("none");
|
||||
expect(autodetectTemplateType("Codestral")).toBe("none");
|
||||
expect(autodetectTemplateType("codestral-22b")).toBe("none");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'alpaca' for Alpaca and Wizard models", () => {
|
||||
expect(autodetectTemplateType("alpaca")).toBe("alpaca");
|
||||
expect(autodetectTemplateType("Alpaca")).toBe("alpaca");
|
||||
expect(autodetectTemplateType("wizard")).toBe("alpaca");
|
||||
expect(autodetectTemplateType("Wizard")).toBe("alpaca");
|
||||
expect(autodetectTemplateType("wizardlm")).toBe("alpaca");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'llama2' for Mistral and Mixtral models", () => {
|
||||
expect(autodetectTemplateType("mistral")).toBe("llama2");
|
||||
expect(autodetectTemplateType("Mistral")).toBe("llama2");
|
||||
expect(autodetectTemplateType("mixtral")).toBe("llama2");
|
||||
expect(autodetectTemplateType("Mixtral")).toBe("llama2");
|
||||
expect(autodetectTemplateType("mistral-7b")).toBe("llama2");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'deepseek' for DeepSeek models", () => {
|
||||
expect(autodetectTemplateType("deepseek")).toBe("deepseek");
|
||||
expect(autodetectTemplateType("DeepSeek")).toBe("deepseek");
|
||||
expect(autodetectTemplateType("deepseek-coder")).toBe("deepseek");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'openchat' for Ninja and OpenChat models", () => {
|
||||
expect(autodetectTemplateType("ninja")).toBe("openchat");
|
||||
expect(autodetectTemplateType("Ninja")).toBe("openchat");
|
||||
expect(autodetectTemplateType("openchat")).toBe("openchat");
|
||||
expect(autodetectTemplateType("OpenChat")).toBe("openchat");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'neural-chat' for Neural Chat models", () => {
|
||||
expect(autodetectTemplateType("neural-chat")).toBe("neural-chat");
|
||||
expect(autodetectTemplateType("Neural-Chat")).toBe("neural-chat");
|
||||
expect(autodetectTemplateType("intel-neural-chat")).toBe("neural-chat");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns 'granite' for Granite models", () => {
|
||||
expect(autodetectTemplateType("granite")).toBe("granite");
|
||||
expect(autodetectTemplateType("granite2:8b")).toBe("granite");
|
||||
expect(autodetectTemplateType("Granite")).toBe("granite");
|
||||
expect(autodetectTemplateType("granite-code")).toBe("granite");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType returns chatml for other models", () => {
|
||||
expect(autodetectTemplateType("unknown-model")).toBe("chatml");
|
||||
expect(autodetectTemplateType("random-ai")).toBe("chatml");
|
||||
expect(autodetectTemplateType("")).toBe("chatml");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType handles case sensitivity correctly", () => {
|
||||
expect(autodetectTemplateType("LLAMA3")).toBe("llama3");
|
||||
expect(autodetectTemplateType("gpt-4")).toBe(undefined);
|
||||
expect(autodetectTemplateType("GPT-4")).toBe(undefined);
|
||||
expect(autodetectTemplateType("CLAUDE")).toBe("none");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType follows correct precedence order", () => {
|
||||
// CodeLlama 70B should be detected before general llama
|
||||
expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b");
|
||||
|
||||
// Llama3 should be detected before general llama
|
||||
expect(autodetectTemplateType("llama3")).toBe("llama3");
|
||||
|
||||
// General llama should be detected after specific cases
|
||||
expect(autodetectTemplateType("llama2")).toBe("llama2");
|
||||
|
||||
// TinyLlama should be detected as zephyr, not llama
|
||||
expect(autodetectTemplateType("tinyllama")).toBe("zephyr");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType handles edge cases with special characters", () => {
|
||||
expect(autodetectTemplateType("llama-3-8b-instruct")).toBe("llama3");
|
||||
expect(autodetectTemplateType("gpt-4-turbo-preview")).toBe(undefined);
|
||||
expect(autodetectTemplateType("claude-3-opus-20240229")).toBe("none");
|
||||
expect(autodetectTemplateType("mistral-7b-instruct-v0.1")).toBe("llama2");
|
||||
});
|
||||
|
||||
test("autodetectTemplateType handles models with mixed keywords", () => {
|
||||
// Should match the first applicable pattern
|
||||
expect(autodetectTemplateType("llama3-chat")).toBe("llama3"); // llama3 comes before general patterns
|
||||
expect(autodetectTemplateType("gpt-llama")).toBe(undefined); // gpt comes first, returns undefined
|
||||
expect(autodetectTemplateType("claude-llama")).toBe("llama2"); // llama comes first, returns llama2
|
||||
});
|
||||
|
|
@ -1,184 +0,0 @@
|
|||
import {
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
ContextItemWithId,
|
||||
RuleWithSource,
|
||||
TextMessagePart,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
} from "../";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { normalizeToMessageParts } from "../util/messageContent";
|
||||
import { isUserOrToolMsg } from "./messages";
|
||||
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
|
||||
import { RulePolicies } from "./rules/types";
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
||||
const EDIT_MESSAGE = `\
|
||||
Always include the language and file name in the info string when you write code blocks.
|
||||
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
|
||||
|
||||
When addressing code modification requests, present a concise code snippet that
|
||||
emphasizes only the necessary changes and uses abbreviated placeholders for
|
||||
unmodified sections. For example:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... existing code ...
|
||||
|
||||
{{ another modification }}
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
In existing files, you should always restate the function or class that the snippet belongs to:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... existing code ...
|
||||
|
||||
function exampleFunction() {
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of function ...
|
||||
}
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
Since users have access to their complete file, they prefer reading only the
|
||||
relevant modifications. It's perfectly acceptable to omit unmodified portions
|
||||
at the beginning, middle, or end of files using these "lazy" comments. Only
|
||||
provide the complete file when explicitly requested. Include a concise explanation
|
||||
of changes unless the user specifically asks for code only.
|
||||
`;
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in chat mode.
|
||||
|
||||
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
|
||||
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
|
||||
|
||||
${EDIT_MESSAGE}
|
||||
</important_rules>`;
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in agent mode.
|
||||
|
||||
${EDIT_MESSAGE}
|
||||
</important_rules>`;
|
||||
|
||||
/**
|
||||
* Helper function to get the context items for a user message
|
||||
*/
|
||||
function getUserContextItems(
|
||||
userMsg: UserChatMessage | ToolResultChatMessage | undefined,
|
||||
history: ChatHistoryItem[],
|
||||
): ContextItemWithId[] {
|
||||
if (!userMsg) return [];
|
||||
|
||||
// Find the history item that contains the userMsg
|
||||
const historyItem = history.find((item) => {
|
||||
// Check if the message ID matches
|
||||
if ("id" in userMsg && "id" in item.message) {
|
||||
return (item.message as any).id === (userMsg as any).id;
|
||||
}
|
||||
// Fallback to content comparison
|
||||
return (
|
||||
item.message.content === userMsg.content &&
|
||||
item.message.role === userMsg.role
|
||||
);
|
||||
});
|
||||
|
||||
return historyItem?.contextItems || [];
|
||||
}
|
||||
|
||||
export function constructMessages(
|
||||
messageMode: string,
|
||||
history: ChatHistoryItem[],
|
||||
baseChatOrAgentSystemMessage: string | undefined,
|
||||
rules: RuleWithSource[],
|
||||
rulePolicies?: RulePolicies,
|
||||
): ChatMessage[] {
|
||||
const filteredHistory = history.filter(
|
||||
(item) => item.message.role !== "system",
|
||||
);
|
||||
const msgs: ChatMessage[] = [];
|
||||
|
||||
for (let i = 0; i < filteredHistory.length; i++) {
|
||||
const historyItem = filteredHistory[i];
|
||||
|
||||
if (messageMode === "chat") {
|
||||
const toolMessage: ToolResultChatMessage =
|
||||
historyItem.message as ToolResultChatMessage;
|
||||
if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
|
||||
// remove all tool calls from the history
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (historyItem.message.role === "user") {
|
||||
// Gather context items for user messages
|
||||
let content = normalizeToMessageParts(historyItem.message);
|
||||
|
||||
const ctxItems = historyItem.contextItems
|
||||
.map((ctxItem) => {
|
||||
return {
|
||||
type: "text",
|
||||
text: `${ctxItem.content}\n`,
|
||||
} as TextMessagePart;
|
||||
})
|
||||
.filter((part) => !!part.text.trim());
|
||||
|
||||
content = [...ctxItems, ...content];
|
||||
msgs.push({
|
||||
...historyItem.message,
|
||||
content,
|
||||
});
|
||||
} else {
|
||||
msgs.push(historyItem.message);
|
||||
}
|
||||
}
|
||||
|
||||
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
|
||||
| UserChatMessage
|
||||
| ToolResultChatMessage
|
||||
| undefined;
|
||||
|
||||
// Get context items for the last user message
|
||||
const lastUserContextItems = getUserContextItems(
|
||||
lastUserMsg,
|
||||
filteredHistory,
|
||||
);
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
baseSystemMessage: baseChatOrAgentSystemMessage,
|
||||
rules,
|
||||
userMessage: lastUserMsg,
|
||||
contextItems: lastUserContextItems,
|
||||
rulePolicies,
|
||||
});
|
||||
|
||||
if (systemMessage.trim()) {
|
||||
msgs.unshift({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
|
||||
// Remove the "id" from all of the messages
|
||||
return msgs.map((msg) => {
|
||||
const { id, ...rest } = msg as any;
|
||||
return rest;
|
||||
});
|
||||
}
|
||||
68
core/llm/defaultSystemMessages.ts
Normal file
68
core/llm/defaultSystemMessages.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
|
||||
|
||||
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
|
||||
Always include the language and file name in the info string when you write code blocks.
|
||||
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
|
||||
`;
|
||||
|
||||
export const EDIT_CODE_INSTRUCTIONS = `\
|
||||
When addressing code modification requests, present a concise code snippet that
|
||||
emphasizes only the necessary changes and uses abbreviated placeholders for
|
||||
unmodified sections. For example:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... existing code ...
|
||||
|
||||
{{ another modification }}
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
In existing files, you should always restate the function or class that the snippet belongs to:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... existing code ...
|
||||
|
||||
function exampleFunction() {
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of function ...
|
||||
}
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
Since users have access to their complete file, they prefer reading only the
|
||||
relevant modifications. It's perfectly acceptable to omit unmodified portions
|
||||
at the beginning, middle, or end of files using these "lazy" comments. Only
|
||||
provide the complete file when explicitly requested. Include a concise explanation
|
||||
of changes unless the user specifically asks for code only.
|
||||
`;
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in chat mode.
|
||||
|
||||
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
|
||||
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
${EDIT_CODE_INSTRUCTIONS}
|
||||
</important_rules>`;
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in agent mode.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
</important_rules>`;
|
||||
|
|
@ -384,6 +384,50 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
}
|
||||
|
||||
private async parseError(resp: any): Promise<Error> {
|
||||
let text = await resp.text();
|
||||
|
||||
if (resp.status === 404 && !resp.url.includes("/v1")) {
|
||||
const parsedError = JSON.parse(text);
|
||||
const errorMessageRaw = parsedError?.error ?? parsedError?.message;
|
||||
const error =
|
||||
typeof errorMessageRaw === "string"
|
||||
? errorMessageRaw.replace(/"/g, "'")
|
||||
: undefined;
|
||||
let model = error?.match(/model '(.*)' not found/)?.[1];
|
||||
if (model && resp.url.match("127.0.0.1:11434")) {
|
||||
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
|
||||
return new LLMError(text, this); // No need to add HTTP status details
|
||||
} else if (text.includes("/api/chat")) {
|
||||
text =
|
||||
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
|
||||
} else {
|
||||
text =
|
||||
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
|
||||
}
|
||||
} else if (resp.status === 404 && resp.url.includes("api.openai.com")) {
|
||||
text =
|
||||
"You may need to add pre-paid credits before using the OpenAI API.";
|
||||
} else if (
|
||||
resp.status === 401 &&
|
||||
(resp.url.includes("api.mistral.ai") ||
|
||||
resp.url.includes("codestral.mistral.ai"))
|
||||
) {
|
||||
if (resp.url.includes("codestral.mistral.ai")) {
|
||||
return new Error(
|
||||
"You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.",
|
||||
);
|
||||
} else {
|
||||
return new Error(
|
||||
"You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.",
|
||||
);
|
||||
}
|
||||
}
|
||||
return new Error(
|
||||
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
|
||||
);
|
||||
}
|
||||
|
||||
fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
// Custom Node.js fetch
|
||||
const customFetch = async (input: URL | RequestInfo, init: any) => {
|
||||
|
|
@ -399,44 +443,9 @@ export abstract class BaseLLM implements ILLM {
|
|||
if (resp.status === 499) {
|
||||
return resp; // client side cancellation
|
||||
}
|
||||
let text = await resp.text();
|
||||
if (resp.status === 404 && !resp.url.includes("/v1")) {
|
||||
const error = JSON.parse(text)?.error?.replace(/"/g, "'");
|
||||
let model = error?.match(/model '(.*)' not found/)?.[1];
|
||||
if (model && resp.url.match("127.0.0.1:11434")) {
|
||||
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
|
||||
throw new LLMError(text, this); // No need to add HTTP status details
|
||||
} else if (text.includes("/api/chat")) {
|
||||
text =
|
||||
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
|
||||
} else {
|
||||
text =
|
||||
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
|
||||
}
|
||||
} else if (
|
||||
resp.status === 404 &&
|
||||
resp.url.includes("api.openai.com")
|
||||
) {
|
||||
text =
|
||||
"You may need to add pre-paid credits before using the OpenAI API.";
|
||||
} else if (
|
||||
resp.status === 401 &&
|
||||
(resp.url.includes("api.mistral.ai") ||
|
||||
resp.url.includes("codestral.mistral.ai"))
|
||||
) {
|
||||
if (resp.url.includes("codestral.mistral.ai")) {
|
||||
throw new Error(
|
||||
"You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.",
|
||||
);
|
||||
} else {
|
||||
throw new Error(
|
||||
"You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.",
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
|
||||
);
|
||||
|
||||
const error = await this.parseError(resp);
|
||||
throw error;
|
||||
}
|
||||
|
||||
return resp;
|
||||
|
|
@ -492,28 +501,32 @@ export abstract class BaseLLM implements ILLM {
|
|||
const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : [];
|
||||
let formatted = "";
|
||||
for (const msg of msgsCopy) {
|
||||
let contentToShow = "";
|
||||
if (msg.role === "tool") {
|
||||
contentToShow = msg.content;
|
||||
} else if (msg.role === "assistant" && msg.toolCalls) {
|
||||
contentToShow = msg.toolCalls
|
||||
?.map(
|
||||
(toolCall) =>
|
||||
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
|
||||
)
|
||||
.join("\n");
|
||||
} else if ("content" in msg) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
msg.content = renderChatMessage(msg);
|
||||
}
|
||||
contentToShow = msg.content;
|
||||
}
|
||||
|
||||
formatted += `<${msg.role}>\n${contentToShow}\n\n`;
|
||||
formatted += this._formatChatMessage(msg);
|
||||
}
|
||||
return formatted;
|
||||
}
|
||||
|
||||
private _formatChatMessage(msg: ChatMessage): string {
|
||||
let contentToShow = "";
|
||||
if (msg.role === "tool") {
|
||||
contentToShow = msg.content;
|
||||
} else if (msg.role === "assistant" && msg.toolCalls) {
|
||||
contentToShow = msg.toolCalls
|
||||
?.map(
|
||||
(toolCall) =>
|
||||
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
|
||||
)
|
||||
.join("\n");
|
||||
} else if ("content" in msg) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
msg.content = renderChatMessage(msg);
|
||||
}
|
||||
contentToShow = msg.content;
|
||||
}
|
||||
|
||||
return `<${msg.role}>\n${contentToShow}\n\n`;
|
||||
}
|
||||
|
||||
protected async *_streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
|
|
@ -569,11 +582,12 @@ export abstract class BaseLLM implements ILLM {
|
|||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
const content = renderChatMessage(result);
|
||||
const formattedContent = this._formatChatMessage(result);
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: content,
|
||||
chunk: formattedContent,
|
||||
});
|
||||
completion += content;
|
||||
completion += formattedContent;
|
||||
yield content;
|
||||
}
|
||||
}
|
||||
|
|
@ -932,7 +946,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
);
|
||||
const msg = fromChatResponse(response);
|
||||
yield msg;
|
||||
completion = renderChatMessage(msg);
|
||||
completion = this._formatChatMessage(msg);
|
||||
} else {
|
||||
// Stream true
|
||||
const stream = this.openaiAdapter.chatCompletionStream(
|
||||
|
|
@ -945,7 +959,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
for await (const chunk of stream) {
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
completion += result.content;
|
||||
completion += this._formatChatMessage(result);
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: result,
|
||||
|
|
@ -961,7 +975,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completionOptions,
|
||||
)) {
|
||||
if (chunk.role === "assistant") {
|
||||
completion += chunk.content;
|
||||
completion += this._formatChatMessage(chunk);
|
||||
} else if (chunk.role === "thinking") {
|
||||
thinking += chunk.content;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
import Bedrock from "./Bedrock.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
UserChatMessage,
|
||||
} from "../../index.js";
|
||||
import Bedrock from "./Bedrock.js";
|
||||
|
||||
// Mock AWS SDK
|
||||
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
|
||||
|
|
@ -317,96 +315,266 @@ describe("Bedrock", () => {
|
|||
});
|
||||
});
|
||||
|
||||
it("should convert text messages correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content: "Hello",
|
||||
} as UserChatMessage;
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [{ text: "Hello" }],
|
||||
});
|
||||
it("should convert simple user and assistant messages correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello" } as UserChatMessage,
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Hello" }] },
|
||||
{ role: "assistant", content: [{ text: "Hi there" }] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should convert tool responses correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "tool",
|
||||
content: "Tool result",
|
||||
toolCallId: "tool-1",
|
||||
};
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
toolResult: {
|
||||
toolUseId: "tool-1",
|
||||
content: [{ text: "Tool result" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("should convert tool calls correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
toolUse: {
|
||||
toolUseId: "tool-1",
|
||||
name: "test_tool",
|
||||
input: { arg: "value" },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle multimodal content correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Look at this image:" },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
|
||||
},
|
||||
},
|
||||
],
|
||||
} as UserChatMessage;
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [
|
||||
{ text: "Look at this image:" },
|
||||
{
|
||||
image: {
|
||||
format: "jpeg",
|
||||
source: {
|
||||
bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
|
||||
it("should handle tool responses correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Use a tool" } as UserChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "tool",
|
||||
content: "Tool result",
|
||||
toolCallId: "tool-1",
|
||||
},
|
||||
];
|
||||
|
||||
const availableTools = new Set(["test_tool"]);
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Use a tool" }] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
toolUse: {
|
||||
toolUseId: "tool-1",
|
||||
name: "test_tool",
|
||||
input: { arg: "value" },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
toolResult: {
|
||||
toolUseId: "tool-1",
|
||||
content: [{ text: "Tool result" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle tool calls with unavailable tools as text", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Use a tool" } as UserChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "unavailable_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Empty set means no tools are available
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Use a tool" }] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
text: expect.stringContaining("Assistant tool call:"),
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle thinking messages correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Think about this" } as UserChatMessage,
|
||||
{ role: "thinking", content: "I am thinking about the solution" },
|
||||
{ role: "assistant", content: "Here's my answer" },
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Think about this" }] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: "I am thinking about the solution",
|
||||
signature: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
{ text: "Here's my answer" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle redacted thinking messages", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Think about this" } as UserChatMessage,
|
||||
{
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: "redacted-content-bytes",
|
||||
},
|
||||
{ role: "assistant", content: "Here's my answer" },
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Think about this" }] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
reasoningContent: {
|
||||
redactedContent: expect.any(Uint8Array),
|
||||
},
|
||||
},
|
||||
{ text: "Here's my answer" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
// Check that the Uint8Array contains the expected bytes
|
||||
const redactedContent =
|
||||
converted[1].content?.[0].reasoningContent?.redactedContent;
|
||||
expect(redactedContent).toBeInstanceOf(Uint8Array);
|
||||
expect(Buffer.from(redactedContent!).toString()).toBe(
|
||||
"redacted-content-bytes",
|
||||
);
|
||||
});
|
||||
|
||||
it("should convert multimodal content correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Look at this image:" },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
|
||||
},
|
||||
},
|
||||
],
|
||||
} as UserChatMessage,
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ text: "Look at this image:" },
|
||||
{
|
||||
image: {
|
||||
format: "jpeg",
|
||||
source: {
|
||||
bytes: expect.any(Uint8Array),
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
// Check that the image bytes were processed correctly
|
||||
const imageBytes = converted[0].content?.[1].image?.source?.bytes;
|
||||
expect(imageBytes).toBeInstanceOf(Uint8Array);
|
||||
expect(Buffer.from(imageBytes!).toString("base64")).toBe(
|
||||
"/9j/4AAQSkZJRg==",
|
||||
);
|
||||
});
|
||||
|
||||
it("should add cache points for prompt caching when needed", () => {
|
||||
// Create a test instance with caching behavior enabled
|
||||
const bedrockWithCaching = new TestBedrock({
|
||||
apiKey: "test-key",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
region: "us-east-1",
|
||||
});
|
||||
|
||||
// Set caching behavior
|
||||
bedrockWithCaching.cacheBehavior = {
|
||||
cacheConversation: true,
|
||||
cacheSystemMessage: true,
|
||||
};
|
||||
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "system", content: "You are a helpful assistant" },
|
||||
{ role: "user", content: "First message" } as UserChatMessage,
|
||||
{ role: "assistant", content: "First response" },
|
||||
{ role: "user", content: "Second message" } as UserChatMessage,
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrockWithCaching["_convertMessages"](
|
||||
messages,
|
||||
availableTools,
|
||||
);
|
||||
|
||||
// The last two user messages should have cache points
|
||||
// But we're not testing the system message here since it's handled separately
|
||||
expect(converted.length).toBe(3);
|
||||
expect(converted[0].role).toBe("user");
|
||||
expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(converted[1].role).toBe("assistant");
|
||||
expect(converted[2].role).toBe("user");
|
||||
expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// Verify that text content includes a cache ID suffix
|
||||
const userMessageText = converted[0].content?.[0].text;
|
||||
expect(userMessageText).toMatch(/First message.+/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import {
|
||||
BedrockRuntimeClient,
|
||||
ContentBlock,
|
||||
ConversationRole,
|
||||
ConverseStreamCommand,
|
||||
ConverseStreamCommandOutput,
|
||||
ImageFormat,
|
||||
InvokeModelCommand,
|
||||
Message,
|
||||
ToolConfiguration,
|
||||
|
|
@ -14,6 +16,7 @@ import {
|
|||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessageContent,
|
||||
} from "../../index.js";
|
||||
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
|
|
@ -289,8 +292,8 @@ class Bedrock extends BaseLLM {
|
|||
const systemMessage = stripImages(
|
||||
messages.find((m) => m.role === "system")?.content ?? "",
|
||||
);
|
||||
const convertedMessages = this._convertMessages(messages);
|
||||
|
||||
// Prompt and system message caching settings
|
||||
const shouldCacheSystemMessage =
|
||||
(!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
|
||||
this.completionOptions.promptCaching;
|
||||
|
|
@ -298,9 +301,7 @@ class Bedrock extends BaseLLM {
|
|||
shouldCacheSystemMessage ||
|
||||
this.cacheBehavior?.cacheConversation ||
|
||||
this.completionOptions.promptCaching;
|
||||
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
|
||||
|
||||
// Add header for prompt caching
|
||||
if (enablePromptCaching) {
|
||||
this.requestOptions.headers = {
|
||||
...this.requestOptions.headers,
|
||||
|
|
@ -308,30 +309,37 @@ class Bedrock extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
// First get tools
|
||||
const supportsTools =
|
||||
(this.capabilities?.tools ||
|
||||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
|
||||
false;
|
||||
|
||||
let toolConfig =
|
||||
supportsTools && options.tools
|
||||
? ({
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
} as ToolConfiguration)
|
||||
: undefined;
|
||||
|
||||
if (toolConfig?.tools && shouldCacheToolsConfig) {
|
||||
toolConfig.tools.push({ cachePoint: { type: "default" } });
|
||||
let toolConfig: undefined | ToolConfiguration = undefined;
|
||||
const availableTools = new Set<string>();
|
||||
if (supportsTools && options.tools && options.tools.length > 0) {
|
||||
toolConfig = {
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
} as ToolConfiguration;
|
||||
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
|
||||
if (shouldCacheToolsConfig) {
|
||||
toolConfig.tools!.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
options.tools.forEach((tool) => {
|
||||
availableTools.add(tool.function.name);
|
||||
});
|
||||
}
|
||||
|
||||
const convertedMessages = this._convertMessages(messages, availableTools);
|
||||
|
||||
return {
|
||||
modelId: options.model,
|
||||
system: systemMessage
|
||||
|
|
@ -368,167 +376,236 @@ class Bedrock extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
private _convertMessage(
|
||||
message: ChatMessage,
|
||||
addCaching: boolean = false,
|
||||
): Message | null {
|
||||
// Handle system messages explicitly
|
||||
if (message.role === "system") {
|
||||
return null;
|
||||
}
|
||||
/*
|
||||
Converts the messages to the format expected by the Bedrock API.
|
||||
|
||||
*/
|
||||
private _convertMessages(
|
||||
messages: ChatMessage[],
|
||||
availableTools: Set<string>,
|
||||
): Message[] {
|
||||
let currentRole: "user" | "assistant" = "user";
|
||||
let currentBlocks: ContentBlock[] = [];
|
||||
|
||||
const cachePoint = addCaching
|
||||
? { cachePoint: { type: "default" } }
|
||||
: undefined;
|
||||
|
||||
// Tool response handling
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
toolResult: {
|
||||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: message.content || "",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// Tool calls handling
|
||||
if (message.role === "assistant" && message.toolCalls) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: message.toolCalls.map((toolCall) => ({
|
||||
toolUse: {
|
||||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: safeParseToolCallArgs(toolCall),
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (message.role === "thinking") {
|
||||
if (message.redactedThinking) {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
redactedContent: new Uint8Array(
|
||||
Buffer.from(message.redactedThinking),
|
||||
),
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content],
|
||||
};
|
||||
} else {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: (message.content as string) || "",
|
||||
signature: message.signature,
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content],
|
||||
};
|
||||
const converted: Message[] = [];
|
||||
const pushCurrentMessage = () => {
|
||||
if (currentBlocks.length === 0 && converted.length > 1) {
|
||||
throw new Error(
|
||||
`Bedrock: no content in ${currentRole} message before conversational turn change`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Standard text message
|
||||
if (typeof message.content === "string") {
|
||||
if (addCaching) {
|
||||
message.content += getSecureID();
|
||||
if (currentBlocks.length > 0) {
|
||||
converted.push({
|
||||
role: currentRole,
|
||||
content: currentBlocks,
|
||||
});
|
||||
}
|
||||
const content: any[] = [{ text: message.content }];
|
||||
if (addCaching) {
|
||||
content.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
return {
|
||||
role: message.role,
|
||||
content,
|
||||
};
|
||||
}
|
||||
currentBlocks = [];
|
||||
};
|
||||
|
||||
// Improved multimodal content handling
|
||||
if (Array.isArray(message.content)) {
|
||||
const content: any[] = [];
|
||||
const nonSystemMessages = messages.filter((m) => m.role !== "system");
|
||||
const hasAddedToolCallIds = new Set<string>();
|
||||
|
||||
// Process all parts first
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "text") {
|
||||
if (addCaching) {
|
||||
part.text += getSecureID();
|
||||
for (let idx = 0; idx < nonSystemMessages.length; idx++) {
|
||||
const message = nonSystemMessages[idx];
|
||||
|
||||
if (message.role === "user" || message.role === "tool") {
|
||||
// Detect conversational turn change
|
||||
if (currentRole !== ConversationRole.USER) {
|
||||
pushCurrentMessage();
|
||||
currentRole = ConversationRole.USER;
|
||||
}
|
||||
|
||||
// USER messages:
|
||||
// Non-empty user message content is converted to "text" and "image" blocks
|
||||
// If ANY user message part is cached, we add a single cache point block when we push the message
|
||||
if (message.role === "user") {
|
||||
const trimmedContent =
|
||||
typeof message.content === "string"
|
||||
? message.content.trim()
|
||||
: message.content;
|
||||
if (trimmedContent) {
|
||||
currentBlocks.push(
|
||||
...this._convertMessageContentToBlocks(trimmedContent),
|
||||
);
|
||||
}
|
||||
content.push({ text: part.text });
|
||||
}
|
||||
// TOOL messages:
|
||||
// Tool messages are represented by "toolResult" blocks
|
||||
// toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig)
|
||||
// If it doesn't, we convert it to a text block
|
||||
else if (message.role === "tool") {
|
||||
const trimmedContent = message.content.trim() || "No tool output";
|
||||
if (hasAddedToolCallIds.has(message.toolCallId)) {
|
||||
currentBlocks.push({
|
||||
toolResult: {
|
||||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: trimmedContent,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
currentBlocks.push({
|
||||
text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (message.role === "assistant" || message.role === "thinking") {
|
||||
// Detect conversational turn change
|
||||
if (currentRole !== ConversationRole.ASSISTANT) {
|
||||
pushCurrentMessage();
|
||||
currentRole = ConversationRole.ASSISTANT;
|
||||
}
|
||||
|
||||
// ASSISTANT messages:
|
||||
// Non-empty assistant message content is converted to "text" and "image" blocks
|
||||
if (message.role === "assistant") {
|
||||
const trimmedContent =
|
||||
typeof message.content === "string"
|
||||
? message.content.trim()
|
||||
: message.content;
|
||||
if (trimmedContent) {
|
||||
currentBlocks.push(
|
||||
...this._convertMessageContentToBlocks(trimmedContent),
|
||||
);
|
||||
}
|
||||
// TOOL CALLS:
|
||||
// Tool calls are represented by "toolUse" blocks
|
||||
// Each tool call must have an id and a function name
|
||||
// The function name must match one of the available tools
|
||||
// Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools)
|
||||
if (message.toolCalls) {
|
||||
for (const toolCall of message.toolCalls) {
|
||||
if (toolCall.id && toolCall.function?.name) {
|
||||
if (availableTools.has(toolCall.function.name)) {
|
||||
currentBlocks.push({
|
||||
toolUse: {
|
||||
toolUseId: toolCall.id,
|
||||
name: toolCall.function.name,
|
||||
input: safeParseToolCallArgs(toolCall),
|
||||
},
|
||||
});
|
||||
hasAddedToolCallIds.add(toolCall.id);
|
||||
} else {
|
||||
const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
|
||||
currentBlocks.push({
|
||||
text: toolCallText,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn(
|
||||
`Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (message.role === "thinking") {
|
||||
// THINKING:
|
||||
// Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content
|
||||
if (message.redactedThinking) {
|
||||
const block: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
redactedContent: new Uint8Array(
|
||||
Buffer.from(message.redactedThinking),
|
||||
),
|
||||
},
|
||||
};
|
||||
currentBlocks.push(block);
|
||||
} else {
|
||||
const block: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: (message.content as string) || "",
|
||||
signature: message.signature,
|
||||
},
|
||||
},
|
||||
};
|
||||
currentBlocks.push(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (currentBlocks.length > 0) {
|
||||
pushCurrentMessage();
|
||||
}
|
||||
|
||||
// If caching is enabled, we add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
|
||||
if (this.cacheBehavior?.cacheConversation) {
|
||||
this._addCachingToLastTwoUserMessages(converted);
|
||||
}
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
||||
private _addCachingToLastTwoUserMessages(converted: Message[]) {
|
||||
let numCached = 0;
|
||||
for (let i = converted.length - 1; i >= 0; i--) {
|
||||
const message = converted[i];
|
||||
if (message.role === "user") {
|
||||
message.content?.forEach((block) => {
|
||||
if (block.text) {
|
||||
block.text += getSecureID();
|
||||
}
|
||||
});
|
||||
message.content?.push({ cachePoint: { type: "default" } });
|
||||
numCached++;
|
||||
}
|
||||
if (numCached === 2) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Converts Continue message content (string/parts) to Bedrock ContentBlock format.
|
||||
// Unsupported/problematic image formats are skipped with a warning.
|
||||
private _convertMessageContentToBlocks(
|
||||
content: MessageContent,
|
||||
): ContentBlock[] {
|
||||
const blocks: ContentBlock[] = [];
|
||||
if (typeof content === "string") {
|
||||
blocks.push({ text: content });
|
||||
} else {
|
||||
for (const part of content) {
|
||||
if (part.type === "text") {
|
||||
blocks.push({ text: part.text });
|
||||
} else if (part.type === "imageUrl" && part.imageUrl) {
|
||||
try {
|
||||
const [mimeType, base64Data] = part.imageUrl.url.split(",");
|
||||
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
|
||||
content.push({
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Buffer.from(base64Data, "base64"),
|
||||
if (
|
||||
format === ImageFormat.JPEG ||
|
||||
format === ImageFormat.PNG ||
|
||||
format === ImageFormat.WEBP ||
|
||||
format === ImageFormat.GIF
|
||||
) {
|
||||
blocks.push({
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
} else {
|
||||
console.warn(
|
||||
`Bedrock: skipping unsupported image part format: ${format}`,
|
||||
part,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process image: ${error}`);
|
||||
console.warn("Bedrock: failed to process image part", error, part);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Add cache point as a separate block at the end if needed
|
||||
if (addCaching && content.length > 0) {
|
||||
content.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
|
||||
return {
|
||||
role: message.role,
|
||||
content,
|
||||
} as Message;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private _convertMessages(messages: ChatMessage[]): any[] {
|
||||
const filteredmessages = messages.filter(
|
||||
(m) => m.role !== "system" && !!m.content,
|
||||
);
|
||||
const lastTwoUserMsgIndices = filteredmessages
|
||||
.map((msg, index) => (msg.role === "user" ? index : -1))
|
||||
.filter((index) => index !== -1)
|
||||
.slice(-2);
|
||||
|
||||
const converted = filteredmessages
|
||||
.map((message, filteredMsgIdx) => {
|
||||
// Add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
|
||||
const addCaching =
|
||||
this.cacheBehavior?.cacheConversation &&
|
||||
lastTwoUserMsgIndices.includes(filteredMsgIdx);
|
||||
|
||||
try {
|
||||
return this._convertMessage(message, addCaching);
|
||||
} catch (error) {
|
||||
console.error(`Failed to convert message: ${error}`);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return converted;
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
|
|
|
|||
57
core/llm/llms/LlamaStack.ts
Normal file
57
core/llm/llms/LlamaStack.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { streamSse } from "@continuedev/fetch";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class LlamaStack extends OpenAI {
|
||||
static providerName = "llamastack";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:8321/v1/openai/v1/",
|
||||
model: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
|
||||
promptTemplates: {
|
||||
edit: osModelsEditPrompt,
|
||||
},
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
};
|
||||
maxStopWords: number | undefined = 16;
|
||||
|
||||
supportsFim(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
async *_streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const endpoint = new URL("completions", this.apiBase);
|
||||
const resp = await this.fetch(endpoint, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: options.model,
|
||||
prompt: prefix,
|
||||
suffix,
|
||||
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)) {
|
||||
yield chunk.choices[0].text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default LlamaStack;
|
||||
|
|
@ -2,6 +2,7 @@ import { ChatMessage, CompletionOptions } from "../../index.js";
|
|||
import { BaseLLM } from "../index.js";
|
||||
|
||||
const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE";
|
||||
const NEXT_EDIT_COMPLETION: string = "<|editable_region_start|>\nHELLO\n";
|
||||
|
||||
class TestLLM extends BaseLLM {
|
||||
static providerName = "test";
|
||||
|
|
@ -24,7 +25,15 @@ class TestLLM extends BaseLLM {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
|
||||
if (
|
||||
prompt === "NEXT_EDIT" ||
|
||||
prompt ===
|
||||
"<|im_start|>user\nNEXT_EDIT<|im_end|>\n<|im_start|>assistant\n"
|
||||
) {
|
||||
yield NEXT_EDIT_COMPLETION;
|
||||
} else {
|
||||
yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
|
||||
}
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import Handlebars from "handlebars";
|
||||
import {
|
||||
BaseCompletionOptions,
|
||||
IdeSettings,
|
||||
|
|
@ -6,10 +7,9 @@ import {
|
|||
JSONModelDescription,
|
||||
LLMOptions,
|
||||
} from "../..";
|
||||
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
|
||||
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages";
|
||||
import { BaseLLM } from "../index";
|
||||
|
||||
import Anthropic from "./Anthropic";
|
||||
import Asksage from "./Asksage";
|
||||
import Azure from "./Azure";
|
||||
|
|
@ -33,6 +33,7 @@ import Inception from "./Inception";
|
|||
import Kindo from "./Kindo";
|
||||
import LlamaCpp from "./LlamaCpp";
|
||||
import Llamafile from "./Llamafile";
|
||||
import LlamaStack from "./LlamaStack";
|
||||
import LMStudio from "./LMStudio";
|
||||
import Mistral from "./Mistral";
|
||||
import MockLLM from "./Mock";
|
||||
|
|
@ -62,7 +63,6 @@ import Vllm from "./Vllm";
|
|||
import Voyage from "./Voyage";
|
||||
import WatsonX from "./WatsonX";
|
||||
import xAI from "./xAI";
|
||||
|
||||
export const LLMClasses = [
|
||||
Anthropic,
|
||||
Cohere,
|
||||
|
|
@ -116,11 +116,13 @@ export const LLMClasses = [
|
|||
Relace,
|
||||
Inception,
|
||||
Voyage,
|
||||
LlamaStack,
|
||||
];
|
||||
|
||||
export async function llmFromDescription(
|
||||
desc: JSONModelDescription,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
getUriFromPath: (path: string) => Promise<string | undefined>,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
llmLogger: ILLMLogger,
|
||||
|
|
@ -142,9 +144,12 @@ export async function llmFromDescription(
|
|||
baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
|
||||
baseChatSystemMessage += "\n\n";
|
||||
baseChatSystemMessage += await renderTemplatedString(
|
||||
Handlebars,
|
||||
desc.systemMessage,
|
||||
readFile,
|
||||
{},
|
||||
[],
|
||||
readFile,
|
||||
getUriFromPath,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -327,27 +327,36 @@ export const getApplicableRules = (
|
|||
export const getSystemMessageWithRules = ({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules,
|
||||
availableRules,
|
||||
contextItems,
|
||||
rulePolicies = {},
|
||||
}: {
|
||||
baseSystemMessage?: string;
|
||||
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
|
||||
rules: RuleWithSource[];
|
||||
availableRules: RuleWithSource[];
|
||||
contextItems: ContextItemWithId[];
|
||||
rulePolicies?: RulePolicies;
|
||||
}) => {
|
||||
const applicableRules = getApplicableRules(
|
||||
}): {
|
||||
systemMessage: string;
|
||||
appliedRules: RuleWithSource[];
|
||||
} => {
|
||||
const appliedRules = getApplicableRules(
|
||||
userMessage,
|
||||
rules,
|
||||
availableRules,
|
||||
contextItems,
|
||||
rulePolicies,
|
||||
);
|
||||
let systemMessage = baseSystemMessage ?? "";
|
||||
|
||||
for (const rule of applicableRules) {
|
||||
systemMessage += `\n\n${rule.rule}`;
|
||||
for (const rule of appliedRules) {
|
||||
if (systemMessage) {
|
||||
systemMessage += "\n\n";
|
||||
}
|
||||
systemMessage += rule.rule;
|
||||
}
|
||||
|
||||
return systemMessage;
|
||||
return {
|
||||
systemMessage,
|
||||
appliedRules,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,114 +0,0 @@
|
|||
export async function* toAsyncIterable(
|
||||
nodeReadable: NodeJS.ReadableStream,
|
||||
): AsyncGenerator<Uint8Array> {
|
||||
for await (const chunk of nodeReadable) {
|
||||
// @ts-ignore
|
||||
yield chunk as Uint8Array;
|
||||
}
|
||||
}
|
||||
|
||||
export async function* streamResponse(
|
||||
response: Response,
|
||||
): AsyncGenerator<string> {
|
||||
if (response.status !== 200) {
|
||||
throw new Error(await response.text());
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("No response body returned.");
|
||||
}
|
||||
|
||||
// Get the major version of Node.js
|
||||
const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
|
||||
|
||||
if (nodeMajorVersion >= 20) {
|
||||
// Use the new API for Node 20 and above
|
||||
const stream = (ReadableStream as any).from(response.body);
|
||||
for await (const chunk of stream.pipeThrough(
|
||||
new TextDecoderStream("utf-8"),
|
||||
)) {
|
||||
yield chunk;
|
||||
}
|
||||
} else {
|
||||
// Fallback for Node versions below 20
|
||||
// Streaming with this method doesn't work as version 20+ does
|
||||
const decoder = new TextDecoder("utf-8");
|
||||
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
|
||||
for await (const chunk of toAsyncIterable(nodeStream)) {
|
||||
yield decoder.decode(chunk, { stream: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseDataLine(line: string): any {
|
||||
const json = line.startsWith("data: ")
|
||||
? line.slice("data: ".length)
|
||||
: line.slice("data:".length);
|
||||
|
||||
try {
|
||||
const data = JSON.parse(json);
|
||||
if (data.error) {
|
||||
throw new Error(`Error streaming response: ${data.error}`);
|
||||
}
|
||||
|
||||
return data;
|
||||
} catch (e) {
|
||||
throw new Error(`Malformed JSON sent from server: ${json}`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseSseLine(line: string): { done: boolean; data: any } {
|
||||
if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) {
|
||||
return { done: true, data: undefined };
|
||||
}
|
||||
if (line.startsWith("data:")) {
|
||||
return { done: false, data: parseDataLine(line) };
|
||||
}
|
||||
if (line.startsWith(": ping")) {
|
||||
return { done: true, data: undefined };
|
||||
}
|
||||
return { done: false, data: undefined };
|
||||
}
|
||||
|
||||
export async function* streamSse(response: Response): AsyncGenerator<any> {
|
||||
let buffer = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
buffer += value;
|
||||
|
||||
let position: number;
|
||||
while ((position = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, position);
|
||||
buffer = buffer.slice(position + 1);
|
||||
|
||||
const { done, data } = parseSseLine(line);
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
if (data) {
|
||||
yield data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (buffer.length > 0) {
|
||||
const { done, data } = parseSseLine(buffer);
|
||||
if (!done && data) {
|
||||
yield data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function* streamJSON(response: Response): AsyncGenerator<any> {
|
||||
let buffer = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
buffer += value;
|
||||
|
||||
let position;
|
||||
while ((position = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, position);
|
||||
const data = JSON.parse(line);
|
||||
yield data;
|
||||
buffer = buffer.slice(position + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -59,6 +59,12 @@ export async function* llmStreamChat(
|
|||
},
|
||||
true,
|
||||
);
|
||||
if (!slashCommand.run) {
|
||||
console.error(
|
||||
`Slash command ${command.name} (${command.source}) has no run function`,
|
||||
);
|
||||
throw new Error(`Slash command not found`);
|
||||
}
|
||||
|
||||
const gen = slashCommand.run({
|
||||
input,
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"gpt-4",
|
||||
"o3",
|
||||
"gemini",
|
||||
"claude-opus-4",
|
||||
].some((part) => model.toLowerCase().startsWith(part));
|
||||
},
|
||||
anthropic: (model) => {
|
||||
|
|
@ -32,6 +33,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"claude-3-7",
|
||||
"claude-3.7",
|
||||
"claude-sonnet-4",
|
||||
"claude-opus-4",
|
||||
].some((part) => model.toLowerCase().startsWith(part))
|
||||
) {
|
||||
return true;
|
||||
|
|
@ -86,15 +88,14 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
);
|
||||
},
|
||||
bedrock: (model) => {
|
||||
// For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
|
||||
if (
|
||||
model.toLowerCase().includes("sonnet") &&
|
||||
[
|
||||
"claude-3-5",
|
||||
"claude-3.5",
|
||||
"claude-3-7",
|
||||
"claude-3.7",
|
||||
"claude-3-5-sonnet",
|
||||
"claude-3.5-sonnet",
|
||||
"claude-3-7-sonnet",
|
||||
"claude-3.7-sonnet",
|
||||
"claude-sonnet-4",
|
||||
"claude-opus-4",
|
||||
].some((part) => model.toLowerCase().includes(part))
|
||||
) {
|
||||
return true;
|
||||
|
|
@ -179,7 +180,9 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
return false;
|
||||
},
|
||||
deepseek: (model) => {
|
||||
if (model !== "deepseek-reasoner") {
|
||||
// https://api-docs.deepseek.com/quick_start/pricing
|
||||
// https://api-docs.deepseek.com/guides/function_calling
|
||||
if (model === "deepseek-reasoner" || model === "deepseek-chat") {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,14 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { IDE, ILLM } from "../index.js";
|
||||
import { ChatMessage, IDE, ILLM } from "../index.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
||||
|
||||
import { shouldCompleteMultiline } from "../autocomplete/classification/shouldCompleteMultiline.js";
|
||||
import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
|
||||
|
||||
import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
|
||||
import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
|
||||
import { postprocessCompletion } from "../autocomplete/postprocessing/index.js";
|
||||
import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
|
||||
import { getAllSnippets } from "../autocomplete/snippets/index.js";
|
||||
import { renderPrompt } from "../autocomplete/templating/index.js";
|
||||
import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
|
||||
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
|
||||
import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
|
||||
import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js";
|
||||
|
|
@ -21,6 +18,14 @@ import {
|
|||
AutocompleteInput,
|
||||
AutocompleteOutcome,
|
||||
} from "../autocomplete/util/types.js";
|
||||
import { replaceEscapedCharacters } from "../util/text.js";
|
||||
import {
|
||||
Prompt,
|
||||
renderDefaultSystemPrompt,
|
||||
renderDefaultUserPrompt,
|
||||
renderPrompt,
|
||||
} from "./templating/NextEditPromptEngine.js";
|
||||
// import { renderPrompt } from "./templating/NextEditPromptEngine.js";
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
|
||||
|
|
@ -33,6 +38,8 @@ const ERRORS_TO_IGNORE = [
|
|||
];
|
||||
|
||||
export class NextEditProvider {
|
||||
private static instance: NextEditProvider | null = null;
|
||||
|
||||
private autocompleteCache = AutocompleteLruCache.get();
|
||||
public errorsShown: Set<string> = new Set();
|
||||
private bracketMatchingService = new BracketMatchingService();
|
||||
|
|
@ -40,16 +47,54 @@ export class NextEditProvider {
|
|||
private completionStreamer: CompletionStreamer;
|
||||
private loggingService = new AutocompleteLoggingService();
|
||||
private contextRetrievalService: ContextRetrievalService;
|
||||
private endpointType: "default" | "fineTuned";
|
||||
private diffContext: string = "";
|
||||
|
||||
constructor(
|
||||
private constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
|
||||
private readonly _onError: (e: any) => void,
|
||||
private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
|
||||
endpointType: "default" | "fineTuned",
|
||||
) {
|
||||
this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
|
||||
this.contextRetrievalService = new ContextRetrievalService(this.ide);
|
||||
this.endpointType = endpointType;
|
||||
}
|
||||
|
||||
public static initialize(
|
||||
configHandler: ConfigHandler,
|
||||
ide: IDE,
|
||||
injectedGetLlm: () => Promise<ILLM | undefined>,
|
||||
onError: (e: any) => void,
|
||||
getDefinitionsFromLsp: GetLspDefinitionsFunction,
|
||||
endpointType: "default" | "fineTuned",
|
||||
): NextEditProvider {
|
||||
if (!NextEditProvider.instance) {
|
||||
NextEditProvider.instance = new NextEditProvider(
|
||||
configHandler,
|
||||
ide,
|
||||
injectedGetLlm,
|
||||
onError,
|
||||
getDefinitionsFromLsp,
|
||||
endpointType,
|
||||
);
|
||||
}
|
||||
return NextEditProvider.instance;
|
||||
}
|
||||
|
||||
public static getInstance(): NextEditProvider {
|
||||
if (!NextEditProvider.instance) {
|
||||
throw new Error(
|
||||
"NextEditProvider has not been initialized. Call initialize() first.",
|
||||
);
|
||||
}
|
||||
return NextEditProvider.instance;
|
||||
}
|
||||
|
||||
public addDiffToContext(diff: string): void {
|
||||
this.diffContext = diff;
|
||||
}
|
||||
|
||||
private async _prepareLlm(): Promise<ILLM | undefined> {
|
||||
|
|
@ -174,7 +219,7 @@ export class NextEditProvider {
|
|||
}
|
||||
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippets({
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
ide: this.ide,
|
||||
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
|
||||
|
|
@ -183,100 +228,241 @@ export class NextEditProvider {
|
|||
this.ide.getWorkspaceDirs(),
|
||||
]);
|
||||
|
||||
const { prompt, prefix, suffix, completionOptions } = renderPrompt({
|
||||
snippetPayload,
|
||||
workspaceDirs,
|
||||
helper,
|
||||
});
|
||||
// TODO: Toggle between the default endpoint and the finetuned endpoint.
|
||||
const prompts: Prompt[] = [];
|
||||
|
||||
// Completion
|
||||
let completion: string | undefined = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cachedCompletion = helper.options.useCache
|
||||
? await cache.get(helper.prunedPrefix)
|
||||
: undefined;
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
if (this.endpointType === "default") {
|
||||
prompts.push(renderDefaultSystemPrompt());
|
||||
prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
|
||||
} else {
|
||||
const multiline =
|
||||
!helper.options.transform || shouldCompleteMultiline(helper);
|
||||
prompts.push(
|
||||
// await renderFineTunedUserPrompt(snippetPayload, this.ide, helper),
|
||||
// await renderFineTunedBasicUserPrompt(
|
||||
// snippetPayload,
|
||||
// this.ide,
|
||||
// helper,
|
||||
// this.diffContext,
|
||||
// ),
|
||||
renderPrompt(helper, this.diffContext),
|
||||
);
|
||||
}
|
||||
|
||||
const completionStream =
|
||||
this.completionStreamer.streamCompletionWithFilters(
|
||||
token,
|
||||
llm,
|
||||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
multiline,
|
||||
completionOptions,
|
||||
helper,
|
||||
);
|
||||
|
||||
for await (const update of completionStream) {
|
||||
completion += update;
|
||||
}
|
||||
|
||||
// Don't postprocess if aborted
|
||||
if (token.aborted) {
|
||||
if (this.endpointType === "default") {
|
||||
const msg: ChatMessage = await llm.chat(prompts, token);
|
||||
if (typeof msg.content === "string") {
|
||||
const nextCompletion = JSON.parse(msg.content).newCode;
|
||||
const outcomeNext: AutocompleteOutcome = {
|
||||
time: Date.now() - startTime,
|
||||
completion: nextCompletion,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
prompt: "",
|
||||
modelProvider: llm.underlyingProviderName,
|
||||
modelName: llm.model,
|
||||
completionOptions: null,
|
||||
cacheHit: false,
|
||||
filepath: helper.filepath,
|
||||
numLines: nextCompletion.split("\n").length,
|
||||
completionId: helper.input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(helper.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
timestamp: Date.now(),
|
||||
...helper.options,
|
||||
};
|
||||
return outcomeNext;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
// const body = {
|
||||
// model: defaultModel,
|
||||
// messages: prompts,
|
||||
// // max_tokens: 15000,
|
||||
// // stop: ["<|editable_region_end|>"],
|
||||
// };
|
||||
//
|
||||
// const resp = await fetch(defaultEndpoint, {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// Authorization: `Bearer ${mercuryToken} `,
|
||||
// "Content-Type": "application/json",
|
||||
// },
|
||||
// body: JSON.stringify(body),
|
||||
// });
|
||||
//
|
||||
// const respJson = await resp.json();
|
||||
|
||||
const processedCompletion = helper.options.transform
|
||||
? postprocessCompletion({
|
||||
completion,
|
||||
prefix: helper.prunedPrefix,
|
||||
suffix: helper.prunedSuffix,
|
||||
llm,
|
||||
})
|
||||
: completion;
|
||||
// TODO: Do some zod schema validation here if needed.
|
||||
} else {
|
||||
// const testController = new AbortController();
|
||||
// const msg: ChatMessage = await llm.chat(prompts, testController.signal);
|
||||
// const testToken = testController.signal;
|
||||
const msg: ChatMessage = await llm.chat(prompts, token);
|
||||
if (typeof msg.content === "string") {
|
||||
// TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
|
||||
const nextCompletion = replaceEscapedCharacters(
|
||||
msg.content.split("<|editable_region_start|>\n")[1],
|
||||
).replace(/\n$/, "");
|
||||
|
||||
completion = processedCompletion;
|
||||
// const diffLines = myersDiff(helper.fileContents, nextCompletion);
|
||||
|
||||
// const diff = getRenderableDiff(diffLines);
|
||||
const outcomeNext: AutocompleteOutcome = {
|
||||
time: Date.now() - startTime,
|
||||
completion: nextCompletion,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
prompt: "",
|
||||
modelProvider: llm.underlyingProviderName,
|
||||
modelName: llm.model,
|
||||
completionOptions: null,
|
||||
cacheHit: false,
|
||||
filepath: helper.filepath,
|
||||
numLines: nextCompletion.split("\n").length,
|
||||
completionId: helper.input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(helper.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
timestamp: Date.now(),
|
||||
...helper.options,
|
||||
};
|
||||
return outcomeNext;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
// const body = {
|
||||
// model: fineTunedModel,
|
||||
// messages: prompts,
|
||||
// max_tokens: 15000,
|
||||
// stop: ["<|editable_region_end|>"],
|
||||
// };
|
||||
//
|
||||
// const resp = await fetch(fineTunedEndpoint, {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// Authorization: `Bearer ${mercuryToken} `,
|
||||
// "Content-Type": "application/json",
|
||||
// },
|
||||
// body: JSON.stringify(body),
|
||||
// });
|
||||
//
|
||||
// const respJson = await resp.json();
|
||||
//
|
||||
// const nextCompletion = respJson.choices[0].message.content
|
||||
// .split("<|editable_region_start|>\n")[1]
|
||||
// .split("<|editable_region_end|>")[0]
|
||||
// .slice(1)
|
||||
// .slice(0, -1)
|
||||
// .replaceAll("\\n", "\n")
|
||||
// .replaceAll('\\"', '"');
|
||||
//
|
||||
// const outcomeNext: AutocompleteOutcome = {
|
||||
// time: Date.now() - startTime,
|
||||
// completion: nextCompletion,
|
||||
// prefix: "",
|
||||
// suffix: "",
|
||||
// prompt: "",
|
||||
// modelProvider: llm.underlyingProviderName,
|
||||
// modelName: llm.model,
|
||||
// completionOptions: null,
|
||||
// cacheHit: false,
|
||||
// filepath: helper.filepath,
|
||||
// numLines: nextCompletion.split("\n").length,
|
||||
// completionId: helper.input.completionId,
|
||||
// gitRepo: await this.ide.getRepoName(helper.filepath),
|
||||
// uniqueId: await this.ide.getUniqueId(),
|
||||
// timestamp: Date.now(),
|
||||
// ...helper.options,
|
||||
// };
|
||||
// return outcomeNext;
|
||||
}
|
||||
|
||||
if (!completion) {
|
||||
return undefined;
|
||||
}
|
||||
// // Completion
|
||||
// let completion: string | undefined = "";
|
||||
|
||||
const outcome: AutocompleteOutcome = {
|
||||
time: Date.now() - startTime,
|
||||
completion,
|
||||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
modelProvider: llm.underlyingProviderName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
filepath: helper.filepath,
|
||||
numLines: completion.split("\n").length,
|
||||
completionId: helper.input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(helper.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
timestamp: Date.now(),
|
||||
...helper.options,
|
||||
};
|
||||
// const cache = await autocompleteCache;
|
||||
// const cachedCompletion = helper.options.useCache
|
||||
// ? await cache.get(helper.prunedPrefix)
|
||||
// : undefined;
|
||||
// let cacheHit = false;
|
||||
// if (cachedCompletion) {
|
||||
// // Cache
|
||||
// cacheHit = true;
|
||||
// completion = cachedCompletion;
|
||||
// } else {
|
||||
// const multiline =
|
||||
// !helper.options.transform || shouldCompleteMultiline(helper);
|
||||
|
||||
//////////
|
||||
// const completionStream =
|
||||
// this.completionStreamer.streamCompletionWithFilters(
|
||||
// token,
|
||||
// llm,
|
||||
// prefix,
|
||||
// suffix,
|
||||
// prompt,
|
||||
// multiline,
|
||||
// completionOptions,
|
||||
// helper,
|
||||
// );
|
||||
|
||||
// Save to cache
|
||||
if (!outcome.cacheHit && helper.options.useCache) {
|
||||
(await this.autocompleteCache)
|
||||
.put(outcome.prefix, outcome.completion)
|
||||
.catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
|
||||
}
|
||||
// for await (const update of completionStream) {
|
||||
// completion += update;
|
||||
// }
|
||||
|
||||
// When using the JetBrains extension, Mark as displayed
|
||||
const ideType = (await this.ide.getIdeInfo()).ideType;
|
||||
if (ideType === "jetbrains") {
|
||||
this.markDisplayed(input.completionId, outcome);
|
||||
}
|
||||
// // Don't postprocess if aborted
|
||||
// if (token.aborted) {
|
||||
// return undefined;
|
||||
// }
|
||||
|
||||
return outcome;
|
||||
// const processedCompletion = helper.options.transform
|
||||
// ? postprocessCompletion({
|
||||
// completion,
|
||||
// prefix: helper.prunedPrefix,
|
||||
// suffix: helper.prunedSuffix,
|
||||
// llm,
|
||||
// })
|
||||
// : completion;
|
||||
|
||||
// completion = processedCompletion;
|
||||
// }
|
||||
|
||||
// if (!completion) {
|
||||
// return undefined;
|
||||
// }
|
||||
|
||||
// const outcome: AutocompleteOutcome = {
|
||||
// time: Date.now() - startTime,
|
||||
// completion,
|
||||
// prefix,
|
||||
// suffix,
|
||||
// prompt,
|
||||
// modelProvider: llm.underlyingProviderName,
|
||||
// modelName: llm.model,
|
||||
// completionOptions,
|
||||
// cacheHit,
|
||||
// filepath: helper.filepath,
|
||||
// numLines: completion.split("\n").length,
|
||||
// completionId: helper.input.completionId,
|
||||
// gitRepo: await this.ide.getRepoName(helper.filepath),
|
||||
// uniqueId: await this.ide.getUniqueId(),
|
||||
// timestamp: Date.now(),
|
||||
// ...helper.options,
|
||||
// };
|
||||
|
||||
// //////////
|
||||
|
||||
// // Save to cache
|
||||
// if (!outcome.cacheHit && helper.options.useCache) {
|
||||
// (await this.autocompleteCache)
|
||||
// .put(outcome.prefix, outcome.completion)
|
||||
// .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
|
||||
// }
|
||||
|
||||
// // When using the JetBrains extension, Mark as displayed
|
||||
// const ideType = (await this.ide.getIdeInfo()).ideType;
|
||||
// if (ideType === "jetbrains") {
|
||||
// this.markDisplayed(input.completionId, outcome);
|
||||
// }
|
||||
|
||||
// return outcome;
|
||||
} catch (e: any) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
|
|
|
|||
29
core/nextEdit/README.md
Normal file
29
core/nextEdit/README.md
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# Next Edit Prediction
|
||||
|
||||
## What is it?
|
||||
|
||||
## How is it different from autocomplete?
|
||||
|
||||
## Where are we right now?
|
||||
|
||||
- Users can decide to switch between autocomplete and next edit.
|
||||
- Next edit triggers at the same time autocomplete is triggered, via vscode's inline completion provider.
|
||||
- The following happens after the trigger:
|
||||
- User's current cursor position is captured.
|
||||
- We define an editable range, ±5 lines from the current cursor position.
|
||||
- User's most recent edit is captured as a unified diff. (this is currently buggy)
|
||||
- This is sent to the model, which returns a new editable range with next edit predictions.
|
||||
- We display this new editable range in a SVG decoration.
|
||||
- User can either tab to accept or esc to reject.
|
||||
- On accept, the old editable range will be replaced by the new editable region. The cursor will be moved to the last line containing some change.
|
||||
- On reject, nothing happens.
|
||||
|
||||
## What needs to be worked on?
|
||||
|
||||
- User edit captures.
|
||||
- Find a better way to trigger next edit (this links back to the diff capture problem).
|
||||
- We can see that next edit triggers as soon as the user accepts a change. This is because autocomplete runs the same way.
|
||||
- I think autocomplete has some filter logic that doesn't display the ghost text under some conditions, which I am guessing are the following:
|
||||
- The model does not have any more completions to create.
|
||||
- The prediction at the cursor location has been cached.
|
||||
- JetBrains integration.
|
||||
|
|
@ -1 +1,6 @@
|
|||
export const IS_NEXT_EDIT_ACTIVE = false;
|
||||
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5;
|
||||
export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
|
||||
export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
|
||||
export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
|
||||
export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
|
||||
|
|
|
|||
575
core/nextEdit/context/aggregateEdits.ts
Normal file
575
core/nextEdit/context/aggregateEdits.ts
Normal file
|
|
@ -0,0 +1,575 @@
|
|||
import { Position, RangeInFileWithNextEditInfo } from "../..";
|
||||
import {
|
||||
BeforeAfterDiff,
|
||||
DiffFormatType,
|
||||
createBeforeAfterDiff,
|
||||
createDiff,
|
||||
} from "./diffFormatting";
|
||||
|
||||
interface ClusterState {
|
||||
beforeState: string; // stores content of cluster before edit
|
||||
startRange: { minLine: number; maxLine: number };
|
||||
currentRange: { minLine: number; maxLine: number };
|
||||
edits: RangeInFileWithNextEditInfo[]; // store small edits that form the cluster
|
||||
firstTimestamp: number;
|
||||
lastTimestamp: number;
|
||||
lastLine: number;
|
||||
firstEditBeforeCursor: { line: number; character: number }; // cursor position before the first edit in the cluster
|
||||
lastEditAfterCursor: { line: number; character: number }; // cursor position after the last edit in the previous cluster
|
||||
}
|
||||
|
||||
interface FileState {
|
||||
activeClusters: ClusterState[]; // Stores active clusters for the file
|
||||
currentContent: string; // Stores the current content of the file
|
||||
priorComparisons: string[]; // Stores prior comparisons for the file (not currently used, but kept for future use)
|
||||
processingQueue: Array<() => Promise<void>>; // Stores a queue of small edits to be processed into clusters
|
||||
isProcessing: boolean;
|
||||
}
|
||||
|
||||
export interface EditClusterConfig {
|
||||
deltaT: number; // Time threshold in seconds; if exceeded, a new cluster is created
|
||||
deltaL: number; // Line threshold; if the user jumps more than this many lines, a new cluster is created
|
||||
maxEdits: number; // Maximum number of edits in a cluster
|
||||
maxDuration: number; // Maximum total duration of an edit in seconds
|
||||
contextSize: number; // Number of previous edits to store; not currently used but kept for future use
|
||||
contextLines: number; // Used for computations involving deltaL
|
||||
}
|
||||
|
||||
export class EditAggregator {
|
||||
private fileStates: Map<string, FileState> = new Map();
|
||||
public config: EditClusterConfig;
|
||||
private previousEditFinalCursorPosition: Position;
|
||||
private lastProcessedFilePath: string | null = null;
|
||||
public onComparisonFinalized: (
|
||||
diff: BeforeAfterDiff,
|
||||
beforeCursorPos: Position,
|
||||
afterPrevEditCursorPos: Position,
|
||||
) => void;
|
||||
|
||||
private static _instance: EditAggregator | null = null;
|
||||
|
||||
public static getInstance(
|
||||
config?: Partial<EditClusterConfig>,
|
||||
onComparisonFinalized?: (
|
||||
diff: BeforeAfterDiff,
|
||||
beforeCursorPos: Position,
|
||||
afterPrevEditCursorPos: Position,
|
||||
) => void,
|
||||
): EditAggregator {
|
||||
// Create instance if it doesn't exist
|
||||
if (!EditAggregator._instance) {
|
||||
EditAggregator._instance = new EditAggregator(
|
||||
config,
|
||||
onComparisonFinalized,
|
||||
);
|
||||
}
|
||||
// Update instance if new parameters are provided
|
||||
else if (config || onComparisonFinalized) {
|
||||
if (config) {
|
||||
EditAggregator._instance.config = {
|
||||
deltaT: config.deltaT ?? EditAggregator._instance.config.deltaT,
|
||||
deltaL: config.deltaL ?? EditAggregator._instance.config.deltaL,
|
||||
maxEdits: config.maxEdits ?? EditAggregator._instance.config.maxEdits,
|
||||
maxDuration:
|
||||
config.maxDuration ?? EditAggregator._instance.config.maxDuration,
|
||||
contextSize:
|
||||
config.contextSize ?? EditAggregator._instance.config.contextSize,
|
||||
contextLines:
|
||||
config.contextLines ?? EditAggregator._instance.config.contextLines,
|
||||
};
|
||||
}
|
||||
|
||||
if (onComparisonFinalized) {
|
||||
EditAggregator._instance.onComparisonFinalized = onComparisonFinalized;
|
||||
}
|
||||
}
|
||||
|
||||
return EditAggregator._instance;
|
||||
}
|
||||
|
||||
constructor(
|
||||
config: Partial<EditClusterConfig> = {},
|
||||
onComparisonFinalized: (
|
||||
diff: BeforeAfterDiff,
|
||||
beforeCursorPos: Position,
|
||||
afterPrevEditCursorPos: Position,
|
||||
) => void = () => {},
|
||||
) {
|
||||
this.config = {
|
||||
deltaT: config.deltaT ?? 1.0,
|
||||
deltaL: config.deltaL ?? 5,
|
||||
maxEdits: config.maxEdits ?? 500,
|
||||
maxDuration: config.maxDuration ?? 100.0,
|
||||
contextSize: config.contextSize ?? 5,
|
||||
contextLines: config.contextLines ?? 3,
|
||||
};
|
||||
this.onComparisonFinalized = onComparisonFinalized;
|
||||
this.previousEditFinalCursorPosition = { line: 0, character: 0 };
|
||||
}
|
||||
|
||||
async processEdit(
|
||||
edit: RangeInFileWithNextEditInfo,
|
||||
timestamp: number = Date.now(),
|
||||
): Promise<void> {
|
||||
const filePath = edit.filepath;
|
||||
|
||||
// If we're switching to a different file, finalize all clusters from the previous file
|
||||
if (this.lastProcessedFilePath && this.lastProcessedFilePath !== filePath) {
|
||||
await this.finalizeClustersForFile(this.lastProcessedFilePath);
|
||||
}
|
||||
|
||||
// Update the last processed file path
|
||||
this.lastProcessedFilePath = filePath;
|
||||
|
||||
if (!this.fileStates.has(filePath)) {
|
||||
this.fileStates.set(filePath, {
|
||||
activeClusters: [],
|
||||
currentContent: edit.fileContents,
|
||||
priorComparisons: [],
|
||||
processingQueue: [],
|
||||
isProcessing: false,
|
||||
});
|
||||
}
|
||||
|
||||
const fileState = this.fileStates.get(filePath)!;
|
||||
const task = async () => {
|
||||
await this._processEditInternal(edit, timestamp, fileState);
|
||||
};
|
||||
|
||||
fileState.processingQueue.push(task);
|
||||
|
||||
if (!fileState.isProcessing) {
|
||||
void this._processQueue(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
private async _processQueue(filePath: string): Promise<void> {
|
||||
const fileState = this.fileStates.get(filePath);
|
||||
if (!fileState) return;
|
||||
|
||||
fileState.isProcessing = true;
|
||||
|
||||
// Process chunks of (5) edits instead of one at a time
|
||||
while (fileState.processingQueue.length > 0) {
|
||||
const tasks = fileState.processingQueue.splice(0, 5);
|
||||
if (tasks.length > 0) {
|
||||
try {
|
||||
await Promise.all(tasks.map((task) => task()));
|
||||
} catch (error) {
|
||||
console.error(`Error processing edits in ${filePath}:`, error);
|
||||
}
|
||||
|
||||
// Yield to the event loop to prevent blocking
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
fileState.isProcessing = false;
|
||||
}
|
||||
|
||||
private async _processEditInternal(
|
||||
edit: RangeInFileWithNextEditInfo,
|
||||
timestamp: number,
|
||||
fileState: FileState,
|
||||
): Promise<void> {
|
||||
const filePath = edit.filepath;
|
||||
|
||||
const editLine = edit.range.start.line;
|
||||
const currentFileLines = fileState.currentContent.split("\n");
|
||||
|
||||
const clustersToFinalize = this.identifyClustersToFinalize(
|
||||
fileState,
|
||||
edit,
|
||||
timestamp,
|
||||
false,
|
||||
);
|
||||
|
||||
for (const cluster of clustersToFinalize) {
|
||||
await this.finalizeCluster(filePath, cluster, fileState);
|
||||
}
|
||||
|
||||
let suitableCluster = this.findSuitableCluster(
|
||||
fileState,
|
||||
editLine,
|
||||
timestamp,
|
||||
);
|
||||
|
||||
// Check if adding this edit would exceed deltaL lines for the cluster
|
||||
if (suitableCluster) {
|
||||
const potentialMinLine = Math.min(
|
||||
suitableCluster.currentRange.minLine,
|
||||
Math.max(0, editLine - this.config.contextLines),
|
||||
);
|
||||
const potentialMaxLine = Math.max(
|
||||
suitableCluster.currentRange.maxLine,
|
||||
Math.min(
|
||||
currentFileLines.length - 1,
|
||||
editLine + this.config.contextLines,
|
||||
),
|
||||
);
|
||||
const potentialLineSpan = potentialMaxLine - potentialMinLine + 1;
|
||||
|
||||
if (potentialLineSpan > this.config.deltaL * 2) {
|
||||
// Auto-finalize the current cluster before creating a new one
|
||||
await this.finalizeCluster(filePath, suitableCluster, fileState);
|
||||
suitableCluster = null;
|
||||
}
|
||||
}
|
||||
|
||||
// initialize a cluster
|
||||
if (!suitableCluster) {
|
||||
suitableCluster = {
|
||||
beforeState: fileState.currentContent,
|
||||
startRange: {
|
||||
minLine: Math.max(0, editLine - this.config.contextLines),
|
||||
maxLine: Math.min(
|
||||
currentFileLines.length - 1,
|
||||
editLine + this.config.contextLines,
|
||||
),
|
||||
},
|
||||
currentRange: {
|
||||
minLine: Math.max(0, editLine - this.config.contextLines),
|
||||
maxLine: Math.min(
|
||||
currentFileLines.length - 1,
|
||||
editLine + this.config.contextLines,
|
||||
),
|
||||
},
|
||||
edits: [],
|
||||
firstTimestamp: timestamp,
|
||||
lastTimestamp: timestamp,
|
||||
lastLine: editLine,
|
||||
firstEditBeforeCursor: edit.beforeCursorPos,
|
||||
lastEditAfterCursor: edit.afterCursorPos,
|
||||
};
|
||||
fileState.activeClusters.push(suitableCluster);
|
||||
}
|
||||
|
||||
suitableCluster.edits.push(edit);
|
||||
suitableCluster.lastTimestamp = timestamp;
|
||||
suitableCluster.lastLine = editLine;
|
||||
suitableCluster.lastEditAfterCursor = edit.afterCursorPos;
|
||||
|
||||
const isWhitespaceOnly = this.isWhitespaceOnlyEdit(
|
||||
edit,
|
||||
fileState.currentContent,
|
||||
);
|
||||
|
||||
if (!isWhitespaceOnly) {
|
||||
suitableCluster.currentRange.minLine = Math.min(
|
||||
suitableCluster.currentRange.minLine,
|
||||
Math.max(0, editLine - this.config.contextLines),
|
||||
);
|
||||
suitableCluster.currentRange.maxLine = Math.max(
|
||||
suitableCluster.currentRange.maxLine,
|
||||
Math.min(
|
||||
currentFileLines.length - 1,
|
||||
editLine + this.config.contextLines,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fileState.currentContent = edit.fileContents;
|
||||
|
||||
const isStructuralEdit =
|
||||
edit.editText.includes("\n") ||
|
||||
edit.range.start.line !== edit.range.end.line;
|
||||
|
||||
if (isStructuralEdit) {
|
||||
const additionalClustersToFinalize = fileState.activeClusters.filter(
|
||||
(c) =>
|
||||
c !== suitableCluster && this.clustersOverlap(c, suitableCluster),
|
||||
);
|
||||
|
||||
for (const cluster of additionalClustersToFinalize) {
|
||||
await this.finalizeCluster(filePath, cluster, fileState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private isWhitespaceOnlyEdit(
|
||||
edit: RangeInFileWithNextEditInfo,
|
||||
currentContent: string,
|
||||
): boolean {
|
||||
const lines = currentContent.split("\n");
|
||||
const line = edit.range.start.line;
|
||||
|
||||
if (line >= lines.length) return false;
|
||||
|
||||
if (edit.range.start.line === edit.range.end.line) {
|
||||
const beforeEdit = lines[line];
|
||||
const afterEdit =
|
||||
beforeEdit.substring(0, edit.range.start.character) +
|
||||
edit.editText +
|
||||
beforeEdit.substring(edit.range.end.character);
|
||||
|
||||
return beforeEdit.trim() === afterEdit.trim();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private clustersOverlap(
|
||||
cluster1: ClusterState,
|
||||
cluster2: ClusterState,
|
||||
): boolean {
|
||||
return (
|
||||
cluster1.currentRange.minLine <=
|
||||
cluster2.currentRange.maxLine + this.config.deltaL &&
|
||||
cluster1.currentRange.maxLine >=
|
||||
cluster2.currentRange.minLine - this.config.deltaL
|
||||
);
|
||||
}
|
||||
|
||||
async processEdits(edits: RangeInFileWithNextEditInfo[]): Promise<void> {
|
||||
const timestamp = Date.now();
|
||||
|
||||
// Only process the last edit during rapid typing
|
||||
if (this.getProcessingQueueSize() > 50) {
|
||||
if (edits.length > 0) {
|
||||
await this.processEdit(edits[edits.length - 1], timestamp);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (const edit of edits) {
|
||||
await this.processEdit(edit, timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalizes all clusters for a specific file
|
||||
*/
|
||||
private async finalizeClustersForFile(filePath: string): Promise<void> {
|
||||
const fileState = this.fileStates.get(filePath);
|
||||
if (!fileState) return;
|
||||
|
||||
// Create a copy of the clusters to finalize to avoid modifying array during iteration
|
||||
const clustersToFinalize = [...fileState.activeClusters];
|
||||
|
||||
for (const cluster of clustersToFinalize) {
|
||||
await this.finalizeCluster(filePath, cluster, fileState);
|
||||
}
|
||||
}
|
||||
|
||||
async finalizeAllClusters(): Promise<void> {
|
||||
const filePromises: Promise<void>[] = [];
|
||||
|
||||
this.fileStates.forEach((fileState, filePath) => {
|
||||
const filePromise = this.finalizeClustersForFile(filePath);
|
||||
filePromises.push(filePromise);
|
||||
});
|
||||
|
||||
await Promise.all(filePromises);
|
||||
}
|
||||
|
||||
private findSuitableCluster(
|
||||
fileState: FileState,
|
||||
editLine: number,
|
||||
timestamp: number,
|
||||
): ClusterState | null {
|
||||
const activeClusters = [...fileState.activeClusters];
|
||||
|
||||
for (const cluster of activeClusters) {
|
||||
// If we're outside the line range but within the time window,
|
||||
// we should finalize the current cluster
|
||||
const isOutsideLineRange =
|
||||
editLine < cluster.currentRange.minLine - this.config.deltaL ||
|
||||
editLine > cluster.currentRange.maxLine + this.config.deltaL;
|
||||
|
||||
const isWithinTimeWindow =
|
||||
(timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
|
||||
|
||||
// If user quickly jumped far away, finalize this cluster before continuing
|
||||
if (isOutsideLineRange && isWithinTimeWindow) {
|
||||
void this.finalizeCluster(
|
||||
cluster.edits[0].filepath,
|
||||
cluster,
|
||||
fileState,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Now look for a suitable cluster for the new edit
|
||||
for (const cluster of fileState.activeClusters) {
|
||||
const isOnSameLine = editLine === cluster.lastLine;
|
||||
const isWithinTimeWindow =
|
||||
(timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
|
||||
const isWithinLineRange =
|
||||
editLine >= cluster.currentRange.minLine - this.config.deltaL &&
|
||||
editLine <= cluster.currentRange.maxLine + this.config.deltaL;
|
||||
const isWithinEditLimit = cluster.edits.length < this.config.maxEdits;
|
||||
const isWithinDurationLimit =
|
||||
(timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration;
|
||||
|
||||
if (
|
||||
(isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) &&
|
||||
isWithinEditLimit &&
|
||||
isWithinDurationLimit
|
||||
) {
|
||||
return cluster;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private identifyClustersToFinalize(
|
||||
fileState: FileState,
|
||||
edit: RangeInFileWithNextEditInfo,
|
||||
timestamp: number,
|
||||
isStructuralEdit: boolean,
|
||||
): ClusterState[] {
|
||||
const clustersToFinalize: ClusterState[] = [];
|
||||
const editLine = edit.range.start.line;
|
||||
|
||||
fileState.activeClusters.forEach((cluster) => {
|
||||
const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000;
|
||||
|
||||
const isOnDifferentLineByNumber = cluster.lastLine !== editLine;
|
||||
|
||||
const isOnDifferentLineByNewline = edit.editText.includes("\n");
|
||||
|
||||
// Use different time thresholds for different types of line change detection
|
||||
const shouldFinalizeByLineNumber =
|
||||
isOnDifferentLineByNumber && timeSinceLastEdit > this.config.deltaT;
|
||||
|
||||
const shouldFinalizeByNewline =
|
||||
isOnDifferentLineByNewline &&
|
||||
timeSinceLastEdit > this.config.deltaT * 1.5;
|
||||
|
||||
// Finalize if we moved to a different line AND the time gap exceeds the respective threshold
|
||||
const shouldFinalizeByTime =
|
||||
shouldFinalizeByLineNumber || shouldFinalizeByNewline;
|
||||
const shouldFinalizeByCount =
|
||||
cluster.edits.length >= this.config.maxEdits;
|
||||
const shouldFinalizeByDuration =
|
||||
(timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration;
|
||||
|
||||
// For structural edits, use the combined line detection
|
||||
const isOnDifferentLine =
|
||||
isOnDifferentLineByNumber || isOnDifferentLineByNewline;
|
||||
const shouldFinalizeByStructuralEdit =
|
||||
isStructuralEdit && isOnDifferentLine;
|
||||
|
||||
if (
|
||||
shouldFinalizeByTime ||
|
||||
shouldFinalizeByCount ||
|
||||
shouldFinalizeByDuration ||
|
||||
shouldFinalizeByStructuralEdit
|
||||
) {
|
||||
clustersToFinalize.push(cluster);
|
||||
}
|
||||
});
|
||||
|
||||
return clustersToFinalize;
|
||||
}
|
||||
|
||||
private async finalizeCluster(
|
||||
filePath: string,
|
||||
cluster: ClusterState,
|
||||
fileState: FileState,
|
||||
): Promise<void> {
|
||||
const beforeContent = cluster.beforeState;
|
||||
const afterContent = fileState.currentContent;
|
||||
|
||||
// Skip whitespace-only diffs
|
||||
const isWhitespaceOnlyDiff =
|
||||
beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, "");
|
||||
|
||||
if (isWhitespaceOnlyDiff) {
|
||||
fileState.activeClusters = fileState.activeClusters.filter(
|
||||
(c) => c !== cluster,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const diff = createDiff(
|
||||
beforeContent,
|
||||
afterContent,
|
||||
filePath,
|
||||
DiffFormatType.Unified,
|
||||
); // Used for checks, not for final output
|
||||
|
||||
// Skip diffs with too many changed lines
|
||||
const changedLineCount = this.countChangedLines(diff);
|
||||
if (changedLineCount > this.config.deltaL * 2) {
|
||||
fileState.activeClusters = fileState.activeClusters.filter(
|
||||
(c) => c !== cluster,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
fileState.priorComparisons.push(diff);
|
||||
if (fileState.priorComparisons.length > this.config.contextSize) {
|
||||
fileState.priorComparisons.shift();
|
||||
}
|
||||
|
||||
fileState.activeClusters = fileState.activeClusters.filter(
|
||||
(c) => c !== cluster,
|
||||
);
|
||||
|
||||
// Give format-agnostic diff to the callback
|
||||
const fullFileVersionsDiff = createBeforeAfterDiff(
|
||||
beforeContent,
|
||||
afterContent,
|
||||
filePath,
|
||||
);
|
||||
|
||||
// Store this cluster's final cursor position for future reference
|
||||
this.previousEditFinalCursorPosition = cluster.lastEditAfterCursor;
|
||||
|
||||
this.onComparisonFinalized(
|
||||
fullFileVersionsDiff,
|
||||
cluster.firstEditBeforeCursor,
|
||||
this.previousEditFinalCursorPosition,
|
||||
);
|
||||
}
|
||||
|
||||
private countChangedLines(diff: string): number {
|
||||
let count = 0;
|
||||
let addedLines = new Set<number>();
|
||||
let removedLines = new Set<number>();
|
||||
|
||||
// Parse the diff lines
|
||||
const lines = diff.split("\n");
|
||||
for (const line of lines) {
|
||||
if (
|
||||
line.startsWith("+++ ") ||
|
||||
line.startsWith("--- ") ||
|
||||
line.startsWith("@@")
|
||||
) {
|
||||
continue; // Skip header lines
|
||||
}
|
||||
|
||||
if (line.startsWith("+")) {
|
||||
addedLines.add(count);
|
||||
count++;
|
||||
} else if (line.startsWith("-")) {
|
||||
removedLines.add(count);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return Math.max(addedLines.size, removedLines.size);
|
||||
}
|
||||
|
||||
getActiveClusterCount(): number {
|
||||
let count = 0;
|
||||
this.fileStates.forEach((fileState) => {
|
||||
count += fileState.activeClusters.length;
|
||||
});
|
||||
return count;
|
||||
}
|
||||
|
||||
getProcessingQueueSize(): number {
|
||||
let count = 0;
|
||||
this.fileStates.forEach((fileState) => {
|
||||
count += fileState.processingQueue.length;
|
||||
});
|
||||
return count;
|
||||
}
|
||||
|
||||
resetState(): void {
|
||||
this.fileStates.clear();
|
||||
this.lastProcessedFilePath = null;
|
||||
}
|
||||
}
|
||||
140
core/nextEdit/context/autocompleteContextFetching.ts
Normal file
140
core/nextEdit/context/autocompleteContextFetching.ts
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import { Position } from "../..";
|
||||
import { ContextRetrievalService } from "../../autocomplete/context/ContextRetrievalService";
|
||||
import { getAllSnippetsWithoutRace } from "../../autocomplete/snippets/getAllSnippets";
|
||||
import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
|
||||
import { renderPrompt } from "../../autocomplete/templating";
|
||||
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
|
||||
import { HelperVars } from "../../autocomplete/util/HelperVars";
|
||||
import {
|
||||
AutocompleteInput,
|
||||
RecentlyEditedRange,
|
||||
} from "../../autocomplete/util/types";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { IDE, ILLM } from "../../index";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
|
||||
|
||||
/**
|
||||
* Gets the formatted autocomplete context string that would be used for autocomplete at the given position.
|
||||
* This function mimics the context generation pipeline from the autocomplete system without triggering
|
||||
* an actual completion.
|
||||
*
|
||||
* @param filepath - The file path where context is being requested
|
||||
* @param pos - The position in the file where context is being requested
|
||||
* @param ide - The IDE interface for file system operations
|
||||
* @param configHandler - The config handler to load user configuration
|
||||
* @param getDefinitionsFromLsp - Function to get LSP definitions (can be a no-op function if not needed)
|
||||
* @param autocompleteModel - Optional autocomplete model to use (if not provided, uses configured autocomplete model)
|
||||
* @param recentlyEditedRanges - Recently edited ranges (defaults to empty array)
|
||||
* @param recentlyVisitedRanges - Recently visited ranges (if not provided, will fetch current live data like real autocomplete)
|
||||
* @param maxPromptTokens - Optional override for maximum number of tokens (if not provided, uses config)
|
||||
* @param manuallyPassFileContents - Optional file contents to use instead of reading from disk (should match current editor state)
|
||||
* @returns Promise that resolves to the formatted context string
|
||||
*/
|
||||
export const getAutocompleteContext = async (
|
||||
filepath: string,
|
||||
pos: Position,
|
||||
ide: IDE,
|
||||
configHandler: ConfigHandler,
|
||||
getDefinitionsFromLsp: GetLspDefinitionsFunction = async () => [],
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
recentlyVisitedRanges: AutocompleteCodeSnippet[],
|
||||
maxPromptTokens: number,
|
||||
manuallyPassFileContents: string,
|
||||
autocompleteModel?: ILLM | string,
|
||||
// eslint-disable-next-line max-params
|
||||
): Promise<string> => {
|
||||
if (!recentlyEditedRanges) recentlyEditedRanges = [];
|
||||
if (!recentlyVisitedRanges) recentlyVisitedRanges = [];
|
||||
|
||||
const input: AutocompleteInput = {
|
||||
isUntitledFile: false,
|
||||
completionId: `context-fetch-${Date.now()}`,
|
||||
filepath,
|
||||
pos,
|
||||
recentlyVisitedRanges,
|
||||
recentlyEditedRanges,
|
||||
manuallyPassFileContents,
|
||||
};
|
||||
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("No config available");
|
||||
}
|
||||
|
||||
// Use provided autocomplete model or fall back to configured autocomplete model
|
||||
let finalModel: ILLM;
|
||||
let modelNameForTemplating: string;
|
||||
|
||||
if (autocompleteModel) {
|
||||
if (typeof autocompleteModel === "string") {
|
||||
// Try to find the model in config first
|
||||
const foundModel = config.modelsByRole.autocomplete.find(
|
||||
(m) => m.title === autocompleteModel,
|
||||
);
|
||||
if (foundModel) {
|
||||
finalModel = foundModel;
|
||||
modelNameForTemplating = foundModel.model;
|
||||
} else {
|
||||
// Model not found in config, but we can still use it for template selection
|
||||
const configuredModel = config.selectedModelByRole.autocomplete;
|
||||
if (!configuredModel) {
|
||||
throw new Error(
|
||||
"No autocomplete model configured and provided model not found in config",
|
||||
);
|
||||
}
|
||||
finalModel = configuredModel;
|
||||
modelNameForTemplating = autocompleteModel; // Use the provided string for template selection
|
||||
}
|
||||
} else {
|
||||
finalModel = autocompleteModel;
|
||||
modelNameForTemplating = autocompleteModel.model;
|
||||
}
|
||||
} else {
|
||||
const configuredModel = config.selectedModelByRole.autocomplete;
|
||||
if (!configuredModel) {
|
||||
throw new Error("No autocomplete model configured and no model provided");
|
||||
}
|
||||
finalModel = configuredModel;
|
||||
modelNameForTemplating = configuredModel.model;
|
||||
}
|
||||
|
||||
const options = {
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
...config.tabAutocompleteOptions,
|
||||
...finalModel.autocompleteOptions,
|
||||
...(maxPromptTokens && { maxPromptTokens }),
|
||||
};
|
||||
|
||||
if (finalModel.promptTemplates?.autocomplete) {
|
||||
options.template = finalModel.promptTemplates.autocomplete as string;
|
||||
}
|
||||
|
||||
const helper = await HelperVars.create(
|
||||
input,
|
||||
options,
|
||||
modelNameForTemplating,
|
||||
ide,
|
||||
);
|
||||
|
||||
const contextRetrievalService = new ContextRetrievalService(ide);
|
||||
|
||||
await contextRetrievalService.initializeForFile(filepath);
|
||||
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
ide: ide,
|
||||
getDefinitionsFromLsp: getDefinitionsFromLsp,
|
||||
contextRetrievalService: contextRetrievalService,
|
||||
}),
|
||||
ide.getWorkspaceDirs(),
|
||||
]);
|
||||
|
||||
const { prompt, prefix, suffix, completionOptions } = renderPrompt({
|
||||
snippetPayload,
|
||||
workspaceDirs,
|
||||
helper,
|
||||
});
|
||||
|
||||
return prefix;
|
||||
};
|
||||
82
core/nextEdit/context/diffFormatting.ts
Normal file
82
core/nextEdit/context/diffFormatting.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { createPatch } from "diff";
|
||||
|
||||
export enum DiffFormatType {
|
||||
Unified = "unified",
|
||||
RawBeforeAfter = "beforeAfter",
|
||||
TokenLineDiff = "linediff",
|
||||
}
|
||||
|
||||
export type BeforeAfterDiff = {
|
||||
filePath: string;
|
||||
beforeContent: string;
|
||||
afterContent: string;
|
||||
};
|
||||
|
||||
export const createDiff = (
|
||||
beforeContent: string,
|
||||
afterContent: string,
|
||||
filePath: string,
|
||||
diffType: DiffFormatType,
|
||||
) => {
|
||||
switch (diffType) {
|
||||
case DiffFormatType.Unified:
|
||||
return createUnifiedDiff(beforeContent, afterContent, filePath);
|
||||
case DiffFormatType.TokenLineDiff:
|
||||
return createTokenLineDiff(beforeContent, afterContent, filePath);
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
const createUnifiedDiff = (
|
||||
beforeContent: string,
|
||||
afterContent: string,
|
||||
filePath: string,
|
||||
) => {
|
||||
const normalizedBefore = beforeContent.endsWith("\n")
|
||||
? beforeContent
|
||||
: beforeContent + "\n";
|
||||
const normalizedAfter = afterContent.endsWith("\n")
|
||||
? afterContent
|
||||
: afterContent + "\n";
|
||||
|
||||
const patch = createPatch(
|
||||
filePath,
|
||||
normalizedBefore,
|
||||
normalizedAfter,
|
||||
"before",
|
||||
"after",
|
||||
{ context: 3 },
|
||||
);
|
||||
|
||||
return patch;
|
||||
};
|
||||
|
||||
export const createBeforeAfterDiff = (
|
||||
beforeContent: string,
|
||||
afterContent: string,
|
||||
filePath: string,
|
||||
) => {
|
||||
const normalizedBefore = beforeContent.endsWith("\n")
|
||||
? beforeContent
|
||||
: beforeContent + "\n";
|
||||
const normalizedAfter = afterContent.endsWith("\n")
|
||||
? afterContent
|
||||
: afterContent + "\n";
|
||||
|
||||
const result: BeforeAfterDiff = {
|
||||
filePath: filePath,
|
||||
beforeContent: normalizedBefore,
|
||||
afterContent: normalizedAfter,
|
||||
};
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const createTokenLineDiff = (
|
||||
beforeContent: string,
|
||||
afterContent: string,
|
||||
filePath: string,
|
||||
) => {
|
||||
// TODO: Implement token line diff
|
||||
return "";
|
||||
};
|
||||
30
core/nextEdit/context/prevEditLruCache.ts
Normal file
30
core/nextEdit/context/prevEditLruCache.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import QuickLRU from "quick-lru";
|
||||
|
||||
export interface prevEdit {
|
||||
unidiff: string;
|
||||
fileUri: string;
|
||||
workspaceUri: string;
|
||||
timestamp: number;
|
||||
}
|
||||
const maxPrevEdits = 5;
|
||||
|
||||
export const prevEditLruCache = new QuickLRU<string, prevEdit>({
|
||||
maxSize: maxPrevEdits,
|
||||
});
|
||||
|
||||
export const setPrevEdit = (edit: prevEdit): void => {
|
||||
const uniqueSuffix = Math.random().toString(36).substring(2, 8);
|
||||
const key = `${edit.fileUri}:${edit.timestamp}:${uniqueSuffix}`;
|
||||
prevEditLruCache.set(key, edit);
|
||||
};
|
||||
|
||||
export const getPrevEditsDescending = (): prevEdit[] => {
|
||||
const edits: prevEdit[] = [];
|
||||
for (const [_, edit] of prevEditLruCache.entriesDescending()) {
|
||||
if (edits.length >= maxPrevEdits) {
|
||||
break;
|
||||
}
|
||||
edits.push(edit);
|
||||
}
|
||||
return edits;
|
||||
};
|
||||
142
core/nextEdit/context/processNextEditData.ts
Normal file
142
core/nextEdit/context/processNextEditData.ts
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
import { IDE, Position } from "../..";
|
||||
import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
|
||||
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { DataLogger } from "../../data/log";
|
||||
import { RecentlyEditedRange } from "../types";
|
||||
import { getAutocompleteContext } from "./autocompleteContextFetching";
|
||||
import { createDiff, DiffFormatType } from "./diffFormatting";
|
||||
import {
|
||||
getPrevEditsDescending,
|
||||
prevEdit,
|
||||
prevEditLruCache,
|
||||
setPrevEdit,
|
||||
} from "./prevEditLruCache";
|
||||
|
||||
const randomNumberBetween = (min: number, max: number) => {
|
||||
min = Math.ceil(min); // Ensure min is an integer
|
||||
max = Math.floor(max); // Ensure max is an integer
|
||||
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||||
};
|
||||
|
||||
interface ProcessNextEditDataParams {
|
||||
filePath: string;
|
||||
beforeContent: string;
|
||||
afterContent: string;
|
||||
cursorPosBeforeEdit: Position;
|
||||
cursorPosAfterPrevEdit: Position;
|
||||
ide: IDE;
|
||||
configHandler: ConfigHandler;
|
||||
getDefinitionsFromLsp: GetLspDefinitionsFunction;
|
||||
recentlyEditedRanges: RecentlyEditedRange[];
|
||||
recentlyVisitedRanges: AutocompleteCodeSnippet[];
|
||||
workspaceDir: string;
|
||||
modelNameOrInstance?: string | undefined;
|
||||
}
|
||||
|
||||
interface filenameAndDiff {
|
||||
filename: string;
|
||||
diff: string;
|
||||
}
|
||||
|
||||
export const processNextEditData = async ({
|
||||
filePath,
|
||||
beforeContent,
|
||||
afterContent,
|
||||
cursorPosBeforeEdit,
|
||||
cursorPosAfterPrevEdit,
|
||||
ide,
|
||||
configHandler,
|
||||
getDefinitionsFromLsp,
|
||||
recentlyEditedRanges,
|
||||
recentlyVisitedRanges,
|
||||
workspaceDir,
|
||||
modelNameOrInstance,
|
||||
}: ProcessNextEditDataParams) => {
|
||||
// To switch to the user's autocomplete model, uncomment the following lines
|
||||
// const { config } = await configHandler.loadConfig();
|
||||
// const autocompleteModel =
|
||||
// (modelNameOrInstance || config?.selectedModelByRole.autocomplete) ??
|
||||
// undefined;
|
||||
|
||||
const modelName = "Codestral";
|
||||
const maxPromptTokens = randomNumberBetween(500, 12000);
|
||||
|
||||
const autocompleteContext = await getAutocompleteContext(
|
||||
filePath,
|
||||
cursorPosBeforeEdit,
|
||||
ide,
|
||||
configHandler,
|
||||
getDefinitionsFromLsp,
|
||||
recentlyEditedRanges,
|
||||
recentlyVisitedRanges,
|
||||
maxPromptTokens,
|
||||
beforeContent,
|
||||
modelName,
|
||||
);
|
||||
|
||||
// console.log(
|
||||
// createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified),
|
||||
// );
|
||||
|
||||
let filenamesAndDiffs: filenameAndDiff[] = [];
|
||||
|
||||
const timestamp = Date.now();
|
||||
let prevEdits: prevEdit[] = getPrevEditsDescending(); // edits from most to least recent
|
||||
if (prevEdits.length > 0) {
|
||||
// if last edit was 10+ minutes ago or the workspace changed, forget previous edits
|
||||
if (
|
||||
timestamp - prevEdits[0].timestamp >= 1000 * 60 * 10 ||
|
||||
workspaceDir !== prevEdits[0].workspaceUri
|
||||
) {
|
||||
prevEditLruCache.clear();
|
||||
prevEdits = [];
|
||||
}
|
||||
|
||||
// extract filenames and diffs for logging
|
||||
filenamesAndDiffs = prevEdits.map(
|
||||
(edit) =>
|
||||
({
|
||||
// filename relative to workspace dir
|
||||
filename: edit.fileUri
|
||||
.replace(edit.workspaceUri, "")
|
||||
.replace(/^[/\\]/, ""),
|
||||
|
||||
// diff without the first 4 lines (the file header)
|
||||
diff: edit.unidiff.split("\n").slice(4).join("\n"),
|
||||
}) as filenameAndDiff,
|
||||
);
|
||||
}
|
||||
|
||||
if (filenamesAndDiffs.length > 0) {
|
||||
// if there are previous edits, log
|
||||
void DataLogger.getInstance().logDevData({
|
||||
name: "nextEditWithHistory",
|
||||
data: {
|
||||
previousEdits: filenamesAndDiffs,
|
||||
fileURI: filePath,
|
||||
workspaceDirURI: workspaceDir,
|
||||
beforeContent,
|
||||
afterContent,
|
||||
beforeCursorPos: cursorPosBeforeEdit,
|
||||
afterCursorPos: cursorPosAfterPrevEdit,
|
||||
context: autocompleteContext,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// add current edit to history
|
||||
const thisEdit: prevEdit = {
|
||||
unidiff: createDiff(
|
||||
beforeContent,
|
||||
afterContent,
|
||||
filePath,
|
||||
DiffFormatType.Unified,
|
||||
),
|
||||
fileUri: filePath,
|
||||
workspaceUri: workspaceDir,
|
||||
timestamp: timestamp,
|
||||
};
|
||||
|
||||
setPrevEdit(thisEdit);
|
||||
};
|
||||
48
core/nextEdit/context/processSmallEdit.ts
Normal file
48
core/nextEdit/context/processSmallEdit.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { IDE, Position } from "../..";
|
||||
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { NextEditProvider } from "../NextEditProvider";
|
||||
import { EditAggregator } from "./aggregateEdits";
|
||||
import { BeforeAfterDiff, createDiff, DiffFormatType } from "./diffFormatting";
|
||||
import { processNextEditData } from "./processNextEditData";
|
||||
|
||||
export const processSmallEdit = async (
|
||||
beforeAfterdiff: BeforeAfterDiff,
|
||||
cursorPosBeforeEdit: Position,
|
||||
cursorPosAfterPrevEdit: Position,
|
||||
configHandler: ConfigHandler,
|
||||
getDefsFromLspFunction: GetLspDefinitionsFunction,
|
||||
ide: IDE,
|
||||
) => {
|
||||
NextEditProvider.getInstance().addDiffToContext(
|
||||
createDiff(
|
||||
beforeAfterdiff.beforeContent,
|
||||
beforeAfterdiff.afterContent,
|
||||
beforeAfterdiff.filePath,
|
||||
DiffFormatType.Unified,
|
||||
),
|
||||
);
|
||||
|
||||
// Get the current context data from the most recent message
|
||||
const currentData = (EditAggregator.getInstance() as any)
|
||||
.latestContextData || {
|
||||
configHandler: configHandler,
|
||||
getDefsFromLspFunction: getDefsFromLspFunction,
|
||||
recentlyEditedRanges: [],
|
||||
recentlyVisitedRanges: [],
|
||||
};
|
||||
|
||||
void processNextEditData({
|
||||
filePath: beforeAfterdiff.filePath,
|
||||
beforeContent: beforeAfterdiff.beforeContent,
|
||||
afterContent: beforeAfterdiff.afterContent,
|
||||
cursorPosBeforeEdit: cursorPosBeforeEdit,
|
||||
cursorPosAfterPrevEdit: cursorPosAfterPrevEdit,
|
||||
ide: ide,
|
||||
configHandler: currentData.configHandler,
|
||||
getDefinitionsFromLsp: currentData.getDefsFromLspFunction,
|
||||
recentlyEditedRanges: currentData.recentlyEditedRanges,
|
||||
recentlyVisitedRanges: currentData.recentlyVisitedRanges,
|
||||
workspaceDir: currentData.workspaceDir,
|
||||
});
|
||||
};
|
||||
194
core/nextEdit/diff/diff.ts
Normal file
194
core/nextEdit/diff/diff.ts
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
import { DiffLine } from "../..";
|
||||
|
||||
/**
|
||||
* Given a diff of two editable regions, get the offset position at the last new line inside the editable region.
|
||||
* @param diffLines Result of myersDiff.
|
||||
* @param lineContentAtCursorPos Content of the line at cursor position.
|
||||
* @param lineOffsetAtCursorPos Offset of the line at cursor position compared to the start of the editable region.
|
||||
* @returns Offset position at last new line inside the editable region.
|
||||
*/
|
||||
export function getOffsetPositionAtLastNewLine(
|
||||
diffLines: DiffLine[],
|
||||
lineContentAtCursorPos: string,
|
||||
lineOffsetAtCursorPos: number,
|
||||
): {
|
||||
line: number;
|
||||
character: number;
|
||||
} {
|
||||
let lastNewLineContent = "";
|
||||
let lineOffset = -1;
|
||||
let currentResultLine = 0;
|
||||
let hasChanges = false;
|
||||
|
||||
// Build the string while tracking line numbers in the result
|
||||
diffLines.reduce((acc, curr, i) => {
|
||||
// Add the current line to our result
|
||||
acc += curr.line;
|
||||
|
||||
// Add newline if not the last line
|
||||
if (i < diffLines.length - 1) {
|
||||
acc += "\n";
|
||||
}
|
||||
|
||||
// If this is a "new" or "same" line, it will be part of the result
|
||||
if (curr.type === "new" || curr.type === "same") {
|
||||
if (curr.type === "new") {
|
||||
// If it's a new line, update our tracking
|
||||
lastNewLineContent = curr.line;
|
||||
lineOffset = currentResultLine;
|
||||
hasChanges = true;
|
||||
}
|
||||
// Increment our position in the result
|
||||
currentResultLine++;
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, "");
|
||||
|
||||
// If nothing has changed, return the original position
|
||||
if (!hasChanges) {
|
||||
lineOffset = lineOffsetAtCursorPos;
|
||||
lastNewLineContent = lineContentAtCursorPos;
|
||||
}
|
||||
// Calculate the character position for the end of the last relevant line
|
||||
const endOfCharPos = lastNewLineContent.length;
|
||||
return {
|
||||
line: lineOffset,
|
||||
character: endOfCharPos,
|
||||
};
|
||||
}
|
||||
|
||||
export function getRenderableDiffWithGutterAnnotations(
|
||||
diffLines: DiffLine[],
|
||||
lineContentAtCursorPos: string,
|
||||
lineOffsetAtCursorPos: number,
|
||||
): {
|
||||
offset: {
|
||||
line: number;
|
||||
character: number;
|
||||
};
|
||||
} {
|
||||
let lastNewLineContent = "";
|
||||
let lineOffset = -1;
|
||||
let currentResultLine = 0;
|
||||
let hasChanges = false;
|
||||
|
||||
// Build the string while tracking line numbers in the result
|
||||
diffLines.reduce((acc, curr, i) => {
|
||||
// Add the current line to our result
|
||||
acc += curr.line;
|
||||
|
||||
// Add newline if not the last line
|
||||
if (i < diffLines.length - 1) {
|
||||
acc += "\n";
|
||||
}
|
||||
|
||||
// If this is a "new" or "same" line, it will be part of the result
|
||||
if (curr.type === "new" || curr.type === "same") {
|
||||
if (curr.type === "new") {
|
||||
// If it's a new line, update our tracking
|
||||
lastNewLineContent = curr.line;
|
||||
lineOffset = currentResultLine;
|
||||
hasChanges = true;
|
||||
}
|
||||
// Increment our position in the result
|
||||
currentResultLine++;
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, "");
|
||||
|
||||
// If nothing has changed, return the original position
|
||||
if (!hasChanges) {
|
||||
lineOffset = lineOffsetAtCursorPos;
|
||||
lastNewLineContent = lineContentAtCursorPos;
|
||||
}
|
||||
// Calculate the character position for the end of the last relevant line
|
||||
const endOfCharPos = lastNewLineContent.length;
|
||||
return {
|
||||
offset: {
|
||||
line: lineOffset,
|
||||
character: endOfCharPos,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the diff is indeed a FIM.
|
||||
* @param oldEditRange Original string content.
|
||||
* @param newEditRange New string content.
|
||||
* @param cursorPosition The position of the cursor in the old string.
|
||||
* @returns boolean indicating if the change is purely additive (FIM)
|
||||
* @returns string of FIM text content.
|
||||
*/
|
||||
export function checkFim(
|
||||
oldEditRange: string,
|
||||
newEditRange: string,
|
||||
cursorPosition: { line: number; character: number },
|
||||
):
|
||||
| {
|
||||
isFim: true;
|
||||
fimText: string;
|
||||
}
|
||||
| {
|
||||
isFim: false;
|
||||
fimText: null;
|
||||
} {
|
||||
// Find the common prefix.
|
||||
let prefixLength = 0;
|
||||
while (
|
||||
prefixLength < oldEditRange.length &&
|
||||
prefixLength < newEditRange.length &&
|
||||
oldEditRange[prefixLength] === newEditRange[prefixLength]
|
||||
) {
|
||||
prefixLength++;
|
||||
}
|
||||
|
||||
// Find the common suffix
|
||||
let oldSuffixPos = oldEditRange.length - 1;
|
||||
let newSuffixPos = newEditRange.length - 1;
|
||||
|
||||
while (
|
||||
oldSuffixPos >= prefixLength &&
|
||||
newSuffixPos >= prefixLength &&
|
||||
oldEditRange[oldSuffixPos] === newEditRange[newSuffixPos]
|
||||
) {
|
||||
oldSuffixPos--;
|
||||
newSuffixPos--;
|
||||
}
|
||||
|
||||
// The old text is purely preserved if:
|
||||
// 1. The prefix ends before or at the cursor.
|
||||
// 2. The suffix starts after or at the cursor.
|
||||
// 3. There's no gap between prefix and suffix in the old text.
|
||||
|
||||
const suffixStartInOld = oldSuffixPos + 1;
|
||||
const suffixStartInNew = newSuffixPos + 1;
|
||||
|
||||
// Convert cursor position to an offset in the string.
|
||||
// For simplicity, we need to calculate the cursor's position in the string.
|
||||
// This requires knowledge of line endings in the oldEditRange.
|
||||
const lines = oldEditRange.substring(0, prefixLength).split("\n");
|
||||
const cursorOffset =
|
||||
lines.length > 1
|
||||
? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) +
|
||||
cursorPosition.character
|
||||
: cursorPosition.character;
|
||||
|
||||
// Check if the cursor is positioned between the prefix and suffix.
|
||||
const cursorBetweenPrefixAndSuffix =
|
||||
prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld;
|
||||
|
||||
// Check if the old text is completely preserved (no deletion).
|
||||
const noTextDeleted = suffixStartInOld - prefixLength <= 0;
|
||||
|
||||
const isFim = cursorBetweenPrefixAndSuffix && noTextDeleted;
|
||||
|
||||
if (isFim) {
|
||||
// Extract the content between prefix and suffix in the new string.
|
||||
const fimText = newEditRange.substring(prefixLength, suffixStartInNew);
|
||||
return { isFim, fimText };
|
||||
} else {
|
||||
return { isFim, fimText: null };
|
||||
}
|
||||
}
|
||||
92
core/nextEdit/diff/diff.vitest.ts
Normal file
92
core/nextEdit/diff/diff.vitest.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { checkFim } from "./diff";
|
||||
|
||||
describe("checkFim", () => {
|
||||
const testCases = [
|
||||
{
|
||||
name: "simple insertion at cursor",
|
||||
oldEditRange: ["function test() {", " ", "}"].join("\n"),
|
||||
newEditRange: ["function test() {", " console.log('hello');", "}"].join(
|
||||
"\n",
|
||||
),
|
||||
cursorPosition: { line: 1, character: 2 },
|
||||
expected: {
|
||||
isFim: true,
|
||||
fimText: "console.log('hello');",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "not a FIM because insertion starts before { and new suffix is different from {}",
|
||||
oldEditRange: ["function test() {}"].join("\n"),
|
||||
newEditRange: ["function test() {console.log('test');}"].join("\n"),
|
||||
cursorPosition: { line: 0, character: 16 },
|
||||
expected: {
|
||||
isFim: false,
|
||||
fimText: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "insertion with cursor at beginning",
|
||||
oldEditRange: ["function test() {}"].join("\n"),
|
||||
newEditRange: ["function test() {console.log('test');}"].join("\n"),
|
||||
cursorPosition: { line: 0, character: 17 },
|
||||
expected: {
|
||||
isFim: true,
|
||||
fimText: "console.log('test');",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "not a FIM because text was deleted",
|
||||
oldEditRange: ["function test() {", " return 42;", "}"].join("\n"),
|
||||
newEditRange: ["function test() {", " console.log('hello');", "}"].join(
|
||||
"\n",
|
||||
),
|
||||
cursorPosition: { line: 1, character: 2 },
|
||||
expected: {
|
||||
isFim: false,
|
||||
fimText: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "not a FIM because text was changed before cursor",
|
||||
oldEditRange: ["let x = 1;"].join("\n"),
|
||||
newEditRange: ["const x = 1; // initialized x"].join("\n"),
|
||||
cursorPosition: { line: 0, character: 8 },
|
||||
expected: {
|
||||
isFim: false,
|
||||
fimText: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "multi-line insertion at cursor",
|
||||
oldEditRange: [
|
||||
"function process() {",
|
||||
" ",
|
||||
" return result;",
|
||||
"}",
|
||||
].join("\n"),
|
||||
newEditRange: [
|
||||
"function process() {",
|
||||
" const data = fetchData();",
|
||||
" const result = processData(data);",
|
||||
" return result;",
|
||||
"}",
|
||||
].join("\n"),
|
||||
cursorPosition: { line: 1, character: 2 },
|
||||
expected: {
|
||||
isFim: true,
|
||||
fimText:
|
||||
"const data = fetchData();\n const result = processData(data);",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(
|
||||
({ name, oldEditRange, newEditRange, cursorPosition, expected }) => {
|
||||
it(name, () => {
|
||||
const result = checkFim(oldEditRange, newEditRange, cursorPosition);
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
343
core/nextEdit/templating/NextEditPromptEngine.ts
Normal file
343
core/nextEdit/templating/NextEditPromptEngine.ts
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { Position } from "../..";
|
||||
import { SnippetPayload } from "../../autocomplete/snippets";
|
||||
import { HelperVars } from "../../autocomplete/util/HelperVars";
|
||||
import {
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
USER_CURSOR_IS_HERE_TOKEN,
|
||||
} from "../constants";
|
||||
|
||||
export type Prompt = SystemPrompt | UserPrompt;
|
||||
|
||||
interface SystemPrompt {
|
||||
role: "system";
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface UserPrompt {
|
||||
role: "user";
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface NextEditTemplate {
|
||||
template: string;
|
||||
}
|
||||
|
||||
export interface TemplateVars {
|
||||
userEdits: string;
|
||||
languageShorthand: string;
|
||||
userExcerpts: string;
|
||||
}
|
||||
|
||||
type TemplateRenderer = (vars: TemplateVars) => string;
|
||||
|
||||
type NextEditModelName = "mercury-coder-nextedit" | "this field is not used";
|
||||
|
||||
const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
|
||||
"mercury-coder-nextedit": {
|
||||
template:
|
||||
"### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
|
||||
},
|
||||
"this field is not used": {
|
||||
template: "NEXT_EDIT",
|
||||
},
|
||||
};
|
||||
|
||||
function templateRendererOfModel(
|
||||
modelName: NextEditModelName,
|
||||
): TemplateRenderer {
|
||||
let 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 function renderPrompt(
|
||||
helper: HelperVars,
|
||||
userEdits: string,
|
||||
): UserPrompt {
|
||||
let modelName = helper.modelName as NextEditModelName;
|
||||
|
||||
if (modelName === "this field is not used") {
|
||||
return {
|
||||
role: "user",
|
||||
content: "NEXT_EDIT",
|
||||
};
|
||||
}
|
||||
|
||||
// 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 NextEditModelName;
|
||||
} else {
|
||||
throw new Error(
|
||||
`${helper.modelName} is not yet supported for next edit.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const renderer = templateRendererOfModel(modelName);
|
||||
const editedCodeWithTokens = insertTokens(
|
||||
helper.fileContents.split("\n"),
|
||||
helper.pos,
|
||||
);
|
||||
|
||||
const tv: TemplateVars = {
|
||||
userEdits,
|
||||
languageShorthand: helper.lang.name,
|
||||
userExcerpts: editedCodeWithTokens,
|
||||
};
|
||||
|
||||
return {
|
||||
role: "user",
|
||||
content: renderer(tv),
|
||||
};
|
||||
}
|
||||
|
||||
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?`,
|
||||
};
|
||||
}
|
||||
|
||||
// export async function renderFineTunedUserPrompt(
|
||||
// snippets: SnippetPayload,
|
||||
// ide: IDE,
|
||||
// helper: HelperVars,
|
||||
// ): Promise<UserPrompt> {
|
||||
// const ideInfo = await ide.getIdeInfo();
|
||||
// switch (ideInfo.ideType) {
|
||||
// case "vscode":
|
||||
// const editedCodeWithPins = insertTokens(
|
||||
// helper.fileContents.split("\n"),
|
||||
// helper.pos,
|
||||
// );
|
||||
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: renderStringTemplate(
|
||||
// mercuryCoderTemplate,
|
||||
// snippets.diffSnippets.join("\n"),
|
||||
// helper.lang.name,
|
||||
// editedCodeWithPins,
|
||||
// ),
|
||||
// };
|
||||
|
||||
// case "jetbrains":
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: "",
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
// export async function renderDefaultBasicUserPrompt(
|
||||
// snippets: SnippetPayload,
|
||||
// ide: IDE,
|
||||
// helper: HelperVars,
|
||||
// ): Promise<UserPrompt> {
|
||||
// const ideInfo = await ide.getIdeInfo();
|
||||
// switch (ideInfo.ideType) {
|
||||
// case "vscode":
|
||||
// const editedCodeWithPins = insertTokens(
|
||||
// helper.fileContents.split("\n"),
|
||||
// helper.pos,
|
||||
// );
|
||||
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: renderStringTemplate(
|
||||
// mercuryCoderTemplate,
|
||||
// JSON.stringify(snippets),
|
||||
// helper.lang.name,
|
||||
// editedCodeWithPins,
|
||||
// ),
|
||||
// };
|
||||
|
||||
// case "jetbrains":
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: "",
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
// export async function renderFineTunedBasicUserPrompt(
|
||||
// snippets: SnippetPayload,
|
||||
// ide: IDE,
|
||||
// helper: HelperVars,
|
||||
// diffContext: string,
|
||||
// ): Promise<UserPrompt> {
|
||||
// const ideInfo = await ide.getIdeInfo();
|
||||
// switch (ideInfo.ideType) {
|
||||
// case "vscode":
|
||||
// const lines = helper.fileContents.split("\n");
|
||||
// const editedCodeWithPins = insertTokens(lines, helper.pos);
|
||||
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: renderStringTemplate(
|
||||
// mercuryCoderTemplate,
|
||||
// diffContext,
|
||||
// helper.lang.name,
|
||||
// editedCodeWithPins,
|
||||
// ),
|
||||
// };
|
||||
|
||||
// case "jetbrains":
|
||||
// return {
|
||||
// role: "user",
|
||||
// content: "",
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
function insertTokens(lines: string[], cursorPos: Position) {
|
||||
const a = insertCursorToken(lines, cursorPos);
|
||||
const b = insertEditableRegionTokensWithStaticRange(a, cursorPos);
|
||||
return b.join("\n");
|
||||
}
|
||||
|
||||
function insertCursorToken(lines: string[], cursorPos: Position) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure character position is within bounds or at the end of the line.
|
||||
const lineLength = lines[cursorPos.line].length;
|
||||
const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
|
||||
|
||||
lines[cursorPos.line] =
|
||||
lines[cursorPos.line].slice(0, charPos) +
|
||||
USER_CURSOR_IS_HERE_TOKEN +
|
||||
lines[cursorPos.line].slice(charPos);
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
function insertEditableRegionTokensWithStaticRange(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure editable regions are within bounds.
|
||||
const editableRegionStart = Math.max(
|
||||
cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
0,
|
||||
);
|
||||
const editableRegionEnd = Math.min(
|
||||
cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
lines.length - 1, // Line numbers should be zero-indexed.
|
||||
);
|
||||
|
||||
const instrumentedLines = [
|
||||
...lines.slice(0, editableRegionStart),
|
||||
EDITABLE_REGION_START_TOKEN,
|
||||
...lines.slice(editableRegionStart, editableRegionEnd + 1),
|
||||
EDITABLE_REGION_END_TOKEN,
|
||||
...lines.slice(editableRegionEnd + 1),
|
||||
];
|
||||
|
||||
return instrumentedLines;
|
||||
}
|
||||
|
||||
function insertEditableRegionTokensWithAst(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure character position is within bounds or at the end of the line.
|
||||
const lineLength = lines[cursorPos.line].length;
|
||||
const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
|
||||
|
||||
(lines[cursorPos.line] =
|
||||
lines[cursorPos.line].slice(0, charPos) + USER_CURSOR_IS_HERE_TOKEN),
|
||||
lines[cursorPos.line].slice(charPos);
|
||||
|
||||
return lines;
|
||||
}
|
||||
45
core/nextEdit/types.ts
Normal file
45
core/nextEdit/types.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../";
|
||||
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFile & {
|
||||
timestamp: number;
|
||||
lines: string[];
|
||||
symbols: Set<string>;
|
||||
};
|
||||
|
||||
export interface AutocompleteInput {
|
||||
isUntitledFile: boolean;
|
||||
completionId: string;
|
||||
filepath: string;
|
||||
pos: Position;
|
||||
recentlyVisitedRanges: AutocompleteCodeSnippet[];
|
||||
recentlyEditedRanges: RecentlyEditedRange[];
|
||||
// Used for notebook files
|
||||
manuallyPassFileContents?: string;
|
||||
// Used for VS Code git commit input box
|
||||
manuallyPassPrefix?: string;
|
||||
selectedCompletionInfo?: {
|
||||
text: string;
|
||||
range: Range;
|
||||
};
|
||||
injectDetails?: string;
|
||||
}
|
||||
|
||||
export interface NextEditOutcome extends TabAutocompleteOptions {
|
||||
accepted?: boolean;
|
||||
time: number;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
modelProvider: string;
|
||||
modelName: string;
|
||||
completionOptions: any;
|
||||
cacheHit: boolean;
|
||||
numLines: number;
|
||||
filepath: string;
|
||||
gitRepo?: string;
|
||||
completionId: string;
|
||||
uniqueId: string;
|
||||
timestamp: number;
|
||||
}
|
||||
564
core/package-lock.json
generated
564
core/package-lock.json
generated
|
|
@ -105,6 +105,7 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"shiki": "^3.6.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
|
|
@ -166,12 +167,12 @@
|
|||
},
|
||||
"../packages/openai-adapters": {
|
||||
"name": "@continuedev/openai-adapters",
|
||||
"version": "1.0.42",
|
||||
"version": "1.0.44",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.5",
|
||||
"@continuedev/config-yaml": "^1.0.51",
|
||||
"@continuedev/fetch": "^1.0.11",
|
||||
"@continuedev/fetch": "^1.0.15",
|
||||
"dotenv": "^16.5.0",
|
||||
"json-schema": "^0.4.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
|
|
@ -4751,6 +4752,80 @@
|
|||
"integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@shikijs/core": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.6.0.tgz",
|
||||
"integrity": "sha512-9By7Xb3olEX0o6UeJyPLI1PE1scC4d3wcVepvtv2xbuN9/IThYN4Wcwh24rcFeASzPam11MCq8yQpwwzCgSBRw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@shikijs/types": "3.6.0",
|
||||
"@shikijs/vscode-textmate": "^10.0.2",
|
||||
"@types/hast": "^3.0.4",
|
||||
"hast-util-to-html": "^9.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@shikijs/engine-javascript": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.6.0.tgz",
|
||||
"integrity": "sha512-7YnLhZG/TU05IHMG14QaLvTW/9WiK8SEYafceccHUSXs2Qr5vJibUwsDfXDLmRi0zHdzsxrGKpSX6hnqe0k8nA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@shikijs/types": "3.6.0",
|
||||
"@shikijs/vscode-textmate": "^10.0.2",
|
||||
"oniguruma-to-es": "^4.3.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@shikijs/engine-oniguruma": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.6.0.tgz",
|
||||
"integrity": "sha512-nmOhIZ9yT3Grd+2plmW/d8+vZ2pcQmo/UnVwXMUXAKTXdi+LK0S08Ancrz5tQQPkxvjBalpMW2aKvwXfelauvA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@shikijs/types": "3.6.0",
|
||||
"@shikijs/vscode-textmate": "^10.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@shikijs/langs": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.6.0.tgz",
|
||||
"integrity": "sha512-IdZkQJaLBu1LCYCwkr30hNuSDfllOT8RWYVZK1tD2J03DkiagYKRxj/pDSl8Didml3xxuyzUjgtioInwEQM/TA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@shikijs/types": "3.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@shikijs/themes": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.6.0.tgz",
|
||||
"integrity": "sha512-Fq2j4nWr1DF4drvmhqKq8x5vVQ27VncF8XZMBuHuQMZvUSS3NBgpqfwz/FoGe36+W6PvniZ1yDlg2d4kmYDU6w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@shikijs/types": "3.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@shikijs/types": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.6.0.tgz",
|
||||
"integrity": "sha512-cLWFiToxYu0aAzJqhXTQsFiJRTFDAGl93IrMSBNaGSzs7ixkLfdG6pH11HipuWFGW5vyx4X47W8HDQ7eSrmBUg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@shikijs/vscode-textmate": "^10.0.2",
|
||||
"@types/hast": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@shikijs/vscode-textmate": {
|
||||
"version": "10.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz",
|
||||
"integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@sinclair/typebox": {
|
||||
"version": "0.27.8",
|
||||
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz",
|
||||
|
|
@ -5481,6 +5556,16 @@
|
|||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/hast": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",
|
||||
"integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/istanbul-lib-coverage": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
|
||||
|
|
@ -5552,6 +5637,16 @@
|
|||
"resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz",
|
||||
"integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA=="
|
||||
},
|
||||
"node_modules/@types/mdast": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",
|
||||
"integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/mozilla-readability": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/mozilla-readability/-/mozilla-readability-0.2.1.tgz",
|
||||
|
|
@ -5688,6 +5783,13 @@
|
|||
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
|
||||
"integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw=="
|
||||
},
|
||||
"node_modules/@types/unist": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
|
||||
"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/uuid": {
|
||||
"version": "9.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz",
|
||||
|
|
@ -7205,6 +7307,17 @@
|
|||
"resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
|
||||
"integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw=="
|
||||
},
|
||||
"node_modules/ccount": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
|
||||
"integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/chai": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-5.2.0.tgz",
|
||||
|
|
@ -7261,6 +7374,28 @@
|
|||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/character-entities-html4": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
|
||||
"integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/character-entities-legacy": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
|
||||
"integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/check-error": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz",
|
||||
|
|
@ -7486,6 +7621,17 @@
|
|||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/comma-separated-tokens": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
|
||||
"integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/command-line-args": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz",
|
||||
|
|
@ -8025,6 +8171,16 @@
|
|||
"resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz",
|
||||
"integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ=="
|
||||
},
|
||||
"node_modules/dequal": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
|
||||
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz",
|
||||
|
|
@ -8042,6 +8198,20 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/devlop": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",
|
||||
"integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dequal": "^2.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/devtools-protocol": {
|
||||
"version": "0.0.1312386",
|
||||
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1312386.tgz",
|
||||
|
|
@ -10588,6 +10758,44 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/hast-util-to-html": {
|
||||
"version": "9.0.5",
|
||||
"resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",
|
||||
"integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0",
|
||||
"@types/unist": "^3.0.0",
|
||||
"ccount": "^2.0.0",
|
||||
"comma-separated-tokens": "^2.0.0",
|
||||
"hast-util-whitespace": "^3.0.0",
|
||||
"html-void-elements": "^3.0.0",
|
||||
"mdast-util-to-hast": "^13.0.0",
|
||||
"property-information": "^7.0.0",
|
||||
"space-separated-tokens": "^2.0.0",
|
||||
"stringify-entities": "^4.0.0",
|
||||
"zwitch": "^2.0.4"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/hast-util-whitespace": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
|
||||
"integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/he": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
|
||||
|
|
@ -10613,6 +10821,17 @@
|
|||
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/html-void-elements": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",
|
||||
"integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2": {
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz",
|
||||
|
|
@ -13009,6 +13228,28 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/mdast-util-to-hast": {
|
||||
"version": "13.2.0",
|
||||
"resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.0.tgz",
|
||||
"integrity": "sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0",
|
||||
"@types/mdast": "^4.0.0",
|
||||
"@ungap/structured-clone": "^1.0.0",
|
||||
"devlop": "^1.0.0",
|
||||
"micromark-util-sanitize-uri": "^2.0.0",
|
||||
"trim-lines": "^3.0.0",
|
||||
"unist-util-position": "^5.0.0",
|
||||
"unist-util-visit": "^5.0.0",
|
||||
"vfile": "^6.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/media-typer": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
|
||||
|
|
@ -13042,6 +13283,100 @@
|
|||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-util-character": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
|
||||
"integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "GitHub Sponsors",
|
||||
"url": "https://github.com/sponsors/unifiedjs"
|
||||
},
|
||||
{
|
||||
"type": "OpenCollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"micromark-util-symbol": "^2.0.0",
|
||||
"micromark-util-types": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-util-encode": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
|
||||
"integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "GitHub Sponsors",
|
||||
"url": "https://github.com/sponsors/unifiedjs"
|
||||
},
|
||||
{
|
||||
"type": "OpenCollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/micromark-util-sanitize-uri": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
|
||||
"integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "GitHub Sponsors",
|
||||
"url": "https://github.com/sponsors/unifiedjs"
|
||||
},
|
||||
{
|
||||
"type": "OpenCollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"micromark-util-character": "^2.0.0",
|
||||
"micromark-util-encode": "^2.0.0",
|
||||
"micromark-util-symbol": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/micromark-util-symbol": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
|
||||
"integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "GitHub Sponsors",
|
||||
"url": "https://github.com/sponsors/unifiedjs"
|
||||
},
|
||||
{
|
||||
"type": "OpenCollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/micromark-util-types": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",
|
||||
"integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "GitHub Sponsors",
|
||||
"url": "https://github.com/sponsors/unifiedjs"
|
||||
},
|
||||
{
|
||||
"type": "OpenCollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/micromatch": {
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
|
||||
|
|
@ -13884,6 +14219,25 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/oniguruma-parser": {
|
||||
"version": "0.12.1",
|
||||
"resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.1.tgz",
|
||||
"integrity": "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/oniguruma-to-es": {
|
||||
"version": "4.3.3",
|
||||
"resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.3.tgz",
|
||||
"integrity": "sha512-rPiZhzC3wXwE59YQMRDodUwwT9FZ9nNBwQQfsd1wfdtlKEyCdRV0avrTcSZ5xlIvGRVPd/cx6ZN45ECmS39xvg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"oniguruma-parser": "^0.12.1",
|
||||
"regex": "^6.0.1",
|
||||
"regex-recursion": "^6.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/onnx-proto": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/onnx-proto/-/onnx-proto-4.0.4.tgz",
|
||||
|
|
@ -14881,6 +15235,17 @@
|
|||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/property-information": {
|
||||
"version": "7.1.0",
|
||||
"resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
|
||||
"integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/protobufjs": {
|
||||
"version": "6.11.4",
|
||||
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.4.tgz",
|
||||
|
|
@ -15285,6 +15650,33 @@
|
|||
"@babel/runtime": "^7.8.4"
|
||||
}
|
||||
},
|
||||
"node_modules/regex": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/regex/-/regex-6.0.1.tgz",
|
||||
"integrity": "sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"regex-utilities": "^2.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/regex-recursion": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz",
|
||||
"integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"regex-utilities": "^2.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/regex-utilities": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",
|
||||
"integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/regexp.prototype.flags": {
|
||||
"version": "1.5.3",
|
||||
"resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.3.tgz",
|
||||
|
|
@ -15856,6 +16248,23 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shiki": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/shiki/-/shiki-3.6.0.tgz",
|
||||
"integrity": "sha512-tKn/Y0MGBTffQoklaATXmTqDU02zx8NYBGQ+F6gy87/YjKbizcLd+Cybh/0ZtOBX9r1NEnAy/GTRDKtOsc1L9w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@shikijs/core": "3.6.0",
|
||||
"@shikijs/engine-javascript": "3.6.0",
|
||||
"@shikijs/engine-oniguruma": "3.6.0",
|
||||
"@shikijs/langs": "3.6.0",
|
||||
"@shikijs/themes": "3.6.0",
|
||||
"@shikijs/types": "3.6.0",
|
||||
"@shikijs/vscode-textmate": "^10.0.2",
|
||||
"@types/hast": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
|
||||
|
|
@ -16136,6 +16545,17 @@
|
|||
"source-map": "^0.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/space-separated-tokens": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
|
||||
"integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/split": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz",
|
||||
|
|
@ -16457,6 +16877,21 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/stringify-entities": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
|
||||
"integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"character-entities-html4": "^2.0.0",
|
||||
"character-entities-legacy": "^3.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
|
|
@ -16947,6 +17382,17 @@
|
|||
"tree-sitter-wasms": "^0.1.11"
|
||||
}
|
||||
},
|
||||
"node_modules/trim-lines": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
|
||||
"integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/triple-beam": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
|
||||
|
|
@ -17375,6 +17821,79 @@
|
|||
"imurmurhash": "^0.1.4"
|
||||
}
|
||||
},
|
||||
"node_modules/unist-util-is": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.0.tgz",
|
||||
"integrity": "sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "^3.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/unist-util-position": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",
|
||||
"integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "^3.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/unist-util-stringify-position": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
|
||||
"integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "^3.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/unist-util-visit": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz",
|
||||
"integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "^3.0.0",
|
||||
"unist-util-is": "^6.0.0",
|
||||
"unist-util-visit-parents": "^6.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/unist-util-visit-parents": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.1.tgz",
|
||||
"integrity": "sha512-L/PqWzfTP9lzzEa6CKs0k2nARxTdZduw3zyh8d2NVBnsyvHjSX4TWse388YrrQKbvI8w20fGjGlhgT96WwKykw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "^3.0.0",
|
||||
"unist-util-is": "^6.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/universal-user-agent": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz",
|
||||
|
|
@ -17534,6 +18053,36 @@
|
|||
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
|
||||
"integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ=="
|
||||
},
|
||||
"node_modules/vfile": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
|
||||
"integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "^3.0.0",
|
||||
"vfile-message": "^4.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/vfile-message": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.2.tgz",
|
||||
"integrity": "sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/unist": "^3.0.0",
|
||||
"unist-util-stringify-position": "^4.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/unified"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.3.5",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
|
||||
|
|
@ -18345,6 +18894,17 @@
|
|||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
},
|
||||
"node_modules/zwitch": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
|
||||
"integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"shiki": "^3.6.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { IDE } from "../..";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { IDE } from "..";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
152
core/promptFiles/getPromptFiles.ts
Normal file
152
core/promptFiles/getPromptFiles.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
import { DEFAULT_PROMPTS_FOLDER_V1 } from ".";
|
||||
import { IDE } from "..";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { readAllGlobalPromptFiles } from "../util/paths";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
// The hardcoded init prompt content
|
||||
const INIT_PROMPT_CONTENT = `name: Init
|
||||
description: Initialize Codebase
|
||||
---
|
||||
You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project.
|
||||
|
||||
## Step 1: Check Required Tools
|
||||
First, verify that you have access to the necessary tools:
|
||||
- builtin_file_glob_search: To discover project files
|
||||
- builtin_read_file: To analyze file contents
|
||||
- builtin_ls: To explore directory structure
|
||||
- builtin_create_new_file: To generate the CONTINUE.md file
|
||||
|
||||
If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
|
||||
|
||||
## Step 2: Project Analysis
|
||||
Analyze the project structure and key files to understand:
|
||||
- The programming languages and frameworks used
|
||||
- The overall architecture and organization
|
||||
- Key components and their responsibilities
|
||||
- Important configuration files
|
||||
- Build/deployment system
|
||||
|
||||
## Step 3: Generate CONTINUE.md
|
||||
Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections:
|
||||
|
||||
1. **Project Overview**
|
||||
- Brief description of the project's purpose
|
||||
- Key technologies used
|
||||
- High-level architecture
|
||||
|
||||
2. **Getting Started**
|
||||
- Prerequisites (required software, dependencies)
|
||||
- Installation instructions
|
||||
- Basic usage examples
|
||||
- Running tests
|
||||
|
||||
3. **Project Structure**
|
||||
- Overview of main directories and their purpose
|
||||
- Key files and their roles
|
||||
- Important configuration files
|
||||
|
||||
4. **Development Workflow**
|
||||
- Coding standards or conventions
|
||||
- Testing approach
|
||||
- Build and deployment process
|
||||
- Contribution guidelines
|
||||
|
||||
5. **Key Concepts**
|
||||
- Domain-specific terminology
|
||||
- Core abstractions
|
||||
- Design patterns used
|
||||
|
||||
6. **Common Tasks**
|
||||
- Step-by-step guides for frequent development tasks
|
||||
- Examples of common operations
|
||||
|
||||
7. **Troubleshooting**
|
||||
- Common issues and their solutions
|
||||
- Debugging tips
|
||||
|
||||
8. **References**
|
||||
- Links to relevant documentation
|
||||
- Important resources
|
||||
|
||||
Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
|
||||
|
||||
## Step 4: Finalize
|
||||
After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to:
|
||||
1. Review and edit the file as needed
|
||||
2. Commit it to their repository to share with their team
|
||||
3. Explain that Continue will automatically load this file into context when working with the project
|
||||
|
||||
Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`;
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
|
||||
|
||||
export async function getPromptFilesFromDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
try {
|
||||
const exists = await ide.fileExists(dir);
|
||||
|
||||
if (!exists) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const uris = await walkDir(dir, ide, {
|
||||
source: "get dir prompt files",
|
||||
});
|
||||
const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
|
||||
const results = promptFilePaths.map(async (uri) => {
|
||||
const content = await ide.readFile(uri); // make a try catch
|
||||
return { path: uri, content };
|
||||
});
|
||||
return Promise.all(results);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAllPromptFiles(
|
||||
ide: IDE,
|
||||
overridePromptFolder?: string,
|
||||
checkV1DefaultFolder: boolean = false,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let promptFiles: { path: string; content: string }[] = [];
|
||||
|
||||
let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2];
|
||||
if (checkV1DefaultFolder) {
|
||||
dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1);
|
||||
}
|
||||
if (overridePromptFolder) {
|
||||
dirsToCheck = [overridePromptFolder];
|
||||
}
|
||||
|
||||
const fullDirs = workspaceDirs
|
||||
.map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
|
||||
.flat();
|
||||
|
||||
promptFiles = (
|
||||
await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
|
||||
).flat();
|
||||
|
||||
// Also read from ~/.continue/.prompts
|
||||
promptFiles.push(...readAllGlobalPromptFiles());
|
||||
|
||||
// Add hardcoded init prompt
|
||||
promptFiles.push({
|
||||
path: "builtin:/init.prompt",
|
||||
content: INIT_PROMPT_CONTENT,
|
||||
});
|
||||
|
||||
return await Promise.all(
|
||||
promptFiles.map(async (file) => {
|
||||
if (file.path.startsWith("builtin:")) {
|
||||
return file;
|
||||
}
|
||||
const content = await ide.readFile(file.path);
|
||||
return { path: file.path, content };
|
||||
}),
|
||||
);
|
||||
}
|
||||
19
core/promptFiles/index.ts
Normal file
19
core/promptFiles/index.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { ContextProviderName } from "..";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
|
||||
|
||||
export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [
|
||||
"file",
|
||||
"clipboard",
|
||||
"repo-map",
|
||||
"currentFile",
|
||||
"os",
|
||||
"problems",
|
||||
"codebase",
|
||||
"tree",
|
||||
"open",
|
||||
"debugger",
|
||||
"terminal",
|
||||
"diff",
|
||||
];
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
import { getLastNPathParts } from "../util/uri";
|
||||
|
||||
export function parsePromptFileV1V2(path: string, content: string) {
|
||||
export function parsePromptFile(path: string, content: string) {
|
||||
let [preambleRaw, prompt] = content.split("\n---\n");
|
||||
if (prompt === undefined) {
|
||||
prompt = preambleRaw;
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { ContextItem, ContinueSDK, IContextProvider } from "../..";
|
||||
|
||||
function createContextItem(item: ContextItem, provider: IContextProvider) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function getContextProviderHelpers(
|
||||
context: ContinueSDK,
|
||||
): Array<[string, Handlebars.HelperDelegate]> | undefined {
|
||||
return context.config.contextProviders?.map((provider: IContextProvider) => [
|
||||
provider.description.title,
|
||||
async (helperContext: any) => {
|
||||
const items = await provider.getContextItems(helperContext, {
|
||||
config: context.config,
|
||||
embeddingsProvider: context.config.selectedModelByRole.embed,
|
||||
fetch: context.fetch,
|
||||
fullInput: context.input,
|
||||
ide: context.ide,
|
||||
llm: context.llm,
|
||||
reranker: context.config.selectedModelByRole.rerank,
|
||||
selectedCode: context.selectedCode,
|
||||
});
|
||||
|
||||
items.forEach((item) =>
|
||||
context.addContextItem(createContextItem(item, provider)),
|
||||
);
|
||||
|
||||
return items.map((item) => item.content).join("\n\n");
|
||||
},
|
||||
]);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue