Merge pull request #1987 from continuedev/nate/merge-main

v0.9.196-vscode
This commit is contained in:
Nate Sesti 2024-08-11 01:04:54 -07:00 • committed by GitHub
commit 59f88af73c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
140 changed files with 3628 additions and 1648 deletions

View file

@ -0,0 +1,6 @@
## 0.8.46 - 2024-08-11
### Added
* new /onboard slash command
### Fixed
* Fixed problem loading config.ts
* Fixed bug causing duplicate indexing work

View file

@ -1,13 +1,11 @@
name: Publish Extension
on:
push:
create:
tags:
- "v0.8.*-vscode"
branches:
- main
# pull_request:
# types: [closed]
# branches:
# - main
jobs:
build:
@ -49,8 +47,13 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
# 1. Check-out repository
- name: Check-out repository
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # This ensures all tags are fetched
- name: Checkout tag
run: git checkout ${GITHUB_REF#refs/tags/}
- name: Make sure version isn't odd
run: |
@ -99,14 +102,6 @@ jobs:
cd core
npm ci
# 2.25 Run core tests
- name: Run core tests
run: |
cd core
npm run test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
# 2.5. Pre package
- name: Set var for environment info
shell: pwsh
@ -117,6 +112,14 @@ jobs:
cd extensions/vscode
npm run prepackage -- --target ${{ env.target }}
# 2.75 Run core tests
- name: Run core tests
run: |
cd core
npm run test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
# 3. Re-install esbuild (for cases that we force installed for another arch in prepackage.js)
- name: Re-install esbuild
run: |
@ -167,20 +170,10 @@ jobs:
# Download the .vsix artifacts
- uses: actions/download-artifact@v3
- name: Tag the repository
id: tag
run: |
# See https://docs.github.com/en/get-started/using-git/dealing-with-special-characters-in-branch-and-tag-names
TAG=v$(grep -o '"version": "[^"]*' extensions/vscode/package.json | cut -d'"' -f4)-vscode
echo "$TAG"
echo "tag=$TAG" >> $GITHUB_OUTPUT
git tag -a $TAG -m "Published version $TAG" ${GITHUB_SHA}
git push origin $TAG
- name: Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.tag.outputs.tag }}
tag_name: ${{ github.ref_name }}
files: |
alpine-x64/*.vsix
darwin-arm64/*.vsix

View file

@ -1,9 +1,11 @@
name: Publish Preview Extension
on:
push:
create:
tags:
- "v0.9.*-vscode"
branches:
- preview
- dev
jobs:
build:
@ -45,8 +47,13 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
# 1. Check-out repository
- name: Check-out repository
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # This ensures all tags are fetched
- name: Checkout tag
run: git checkout ${GITHUB_REF#refs/tags/}
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
@ -90,14 +97,6 @@ jobs:
cd core
npm ci
# 2.25 Run core tests
- name: Run core tests
run: |
cd core
npm run test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
# 2.5. Pre package
- name: Set var for environment info
shell: pwsh
@ -108,6 +107,14 @@ jobs:
cd extensions/vscode
npm run prepackage -- --target ${{ env.target }}
# 2.75 Run core tests
- name: Run core tests
run: |
cd core
npm run test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
# 3. Re-install esbuild (for cases that we force installed for another arch in prepackage.js)
- name: Re-install esbuild
run: |
@ -158,20 +165,10 @@ jobs:
# Download the .vsix artifacts
- uses: actions/download-artifact@v3
- name: Tag the repository
id: tag
run: |
# See https://docs.github.com/en/get-started/using-git/dealing-with-special-characters-in-branch-and-tag-names
TAG=v$(grep -o '"version": "[^"]*' extensions/vscode/package.json | cut -d'"' -f4)-vscode
echo "$TAG"
echo "tag=$TAG" >> $GITHUB_OUTPUT
git tag -a $TAG -m "Published version $TAG" ${GITHUB_SHA}
git push origin $TAG
- name: Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.tag.outputs.tag }}
tag_name: ${{ github.ref_name }}
files: |
alpine-x64/*.vsix
darwin-arm64/*.vsix
@ -202,7 +199,7 @@ jobs:
git config --local user.name "GitHub Action"
- name: Pull latest changes
run: git pull origin preview
run: git pull origin dev
# 1. Download the artifacts
- uses: actions/download-artifact@v3

44
.vscode/launch.json vendored
View file

@ -5,6 +5,27 @@
"version": "0.2.0",
"compounds": [],
"configurations": [
{
"name": "Launch extension",
"type": "extensionHost",
"request": "launch",
"cwd": "${workspaceFolder}/extensions/vscode",
"args": [
// Pass a directory to manually test in
"${workspaceFolder}/manual-testing-sandbox",
"${workspaceFolder}/manual-testing-sandbox/test.js",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],
"pauseForSourceMap": false,
"outFiles": [
"${workspaceFolder}/extensions/vscode/out/extension.js",
"/Users/natesesti/.continue/config.ts"
],
"preLaunchTask": "vscode-extension:build",
"env": {
// "CONTROL_PLANE_ENV": "local"
}
},
{
"type": "node",
"request": "launch",
@ -52,30 +73,9 @@
"sourceMaps": true
// "preLaunchTask": "gui:dev"
},
{
"name": "Extension (VSCode)",
"type": "extensionHost",
"request": "launch",
"cwd": "${workspaceFolder}/extensions/vscode",
"args": [
// Pass a directory to manually test in
"${workspaceFolder}/extensions/vscode",
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox/test.js",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],
"pauseForSourceMap": false,
"outFiles": [
"${workspaceFolder}/extensions/vscode/out/extension.js",
"/Users/natesesti/.continue/config.ts"
],
"preLaunchTask": "vscode-extension:build",
"env": {
// "CONTROL_PLANE_ENV": "local"
}
},
// Has to be run after starting the server (separately or using the compound configuration)
{
"name": "Tests (VSCode)",
"name": "Run tests",
"type": "extensionHost",
"request": "launch",
"cwd": "${workspaceFolder}/extensions/vscode",

View file

@ -71,6 +71,7 @@ You can run the documentation server locally using either of the following metho
1. Open your terminal and navigate to the root directory of the project.
2. Run the following command to start the documentation server:
```bash
npm run start --prefix docs
```
@ -116,7 +117,7 @@ nvm use
2. Start debugging:
1. Switch to Run and Debug view
2. Select `Extension (VS Code)` from drop down
2. Select `Launch extension` from drop down
3. Hit play button
4. This will start the extension in debug mode and open a new VS Code window with it installed
1. The new VS Code window with the extension is referred to as the _Host VS Code_
@ -162,6 +163,10 @@ For the sake of rapid development, it is also possible to configure this communi
If you make changes to Kotlin code, they can often be hot-reloaded with "Run -> Debugging Actions -> Reload Changed Classes".
### Our Git Workflow
We keep two permanent branches: `main` and `dev`. All contributions should be made as pull requests to the `dev` branch. When we are ready to create a "pre-release" version, we create a tag on the `dev` branch, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will merge its tag into the `main` branch. Creating a tag on the `main` branch will then trigger a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question.
### Formatting
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.

View file

@ -184,7 +184,14 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
entryPoints: ["src/index.ts"],
bundle: true,
outfile: esbuildOutputFile,
external: ["esbuild", "./xhr-sync-worker.js", "vscode", "./index.node"],
external: [
"esbuild",
"./xhr-sync-worker.js",
"llamaTokenizerWorkerPool.mjs",
"tiktokenWorkerPool.mjs",
"vscode",
"./index.node",
],
format: "cjs",
platform: "node",
sourcemap: true,
@ -204,6 +211,11 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
"../core/node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js",
"out/xhr-sync-worker.js",
);
fs.cpSync("../core/llm/tiktokenWorkerPool.mjs", "out/tiktokenWorkerPool.mjs");
fs.cpSync(
"../core/llm/llamaTokenizerWorkerPool.mjs",
"out/llamaTokenizerWorkerPool.mjs",
);
if (esbuildOnly) {
return;

View file

@ -45,14 +45,12 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",
"@types/mozilla-readability": "^0.2.1",
"@types/node-fetch": "^2.6.11",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@xenova/transformers": "2.14.0",
@ -70,6 +68,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
@ -105,13 +104,20 @@
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
"@types/jsdom": "^21.1.6",
"@types/mozilla-readability": "^0.2.1",
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",
"@types/pg": "^8.11.6",
"@types/request": "^2.48.12",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",

View file

@ -1,9 +1,9 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2020",
"target": "ES2022",
"outDir": "out",
"lib": ["ES2021", "dom", "es6", "es5", "dom.iterable", "scripthost"],
"lib": ["ES2022", "dom", "es6", "es5", "dom.iterable", "scripthost"],
"sourceMap": true,
"rootDirs": ["src", "../core"],
"allowJs": true,

3
core/.gitignore vendored
View file

@ -3,4 +3,5 @@ target
**/.DS_Store
npm-debug.log*
.env
.continue-test
.continue-test
testDir

View file

@ -458,8 +458,8 @@ export class CompletionProvider {
if (
!shownGptClaudeWarning &&
nonAutocompleteModels.some((model) => llm.model.includes(model)) &&
!llm.model.includes("deepseek") &&
!llm.model.includes("codestral")
!llm.model.toLowerCase().includes("deepseek") &&
!llm.model.toLowerCase().includes("codestral")
) {
shownGptClaudeWarning = true;
throw new Error(

View file

@ -1,11 +1,7 @@
import {
CustomCommand,
SlashCommand,
SlashCommandDescription,
} from "../index.js";
import { stripImages } from "../llm/images.js";
import { renderTemplatedString } from "../llm/llms/index.js";
import SlashCommands from "./slash/index.js";
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
import SlashCommands from "./slash";
export function slashFromCustomCommand(
customCommand: CustomCommand,

View file

@ -1,12 +1,13 @@
import GenerateTerminalCommand from "./cmd.js";
import CommentSlashCommand from "./comment.js";
import CommitMessageCommand from "./commit.js";
import DraftIssueCommand from "./draftIssue.js";
import EditSlashCommand from "./edit.js";
import HttpSlashCommand from "./http.js";
import ReviewMessageCommand from "./review.js";
import ShareSlashCommand from "./share.js";
import StackOverflowSlashCommand from "./stackOverflow.js";
import GenerateTerminalCommand from "./cmd";
import CommentSlashCommand from "./comment";
import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import EditSlashCommand from "./edit";
import HttpSlashCommand from "./http";
import ReviewMessageCommand from "./review";
import ShareSlashCommand from "./share";
import StackOverflowSlashCommand from "./stackOverflow";
import OnboardSlashCommand from "./onboard";
export default [
DraftIssueCommand,
@ -18,4 +19,5 @@ export default [
HttpSlashCommand,
CommitMessageCommand,
ReviewMessageCommand,
OnboardSlashCommand,
];

View file

@ -0,0 +1,156 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { IDE, SlashCommand } from "../..";
import * as fs from "fs/promises";
import * as path from "path";
import { stripImages } from "../../llm/images";
import ignore from "ignore";
import {
defaultIgnoreDir,
defaultIgnoreFile,
gitIgArrayFromFile,
} from "../../indexing/ignore";
const LANGUAGE_DEP_MGMT_FILENAMES = [
"package.json", // JavaScript (Node.js)
"requirements.txt", // Python
"Gemfile", // Ruby
"pom.xml", // Java (Maven)
"build.gradle", // Java (Gradle)
"composer.json", // PHP
"Cargo.toml", // Rust
"go.mod", // Go
"packages.config", // C# (.NET)
"*.csproj", // C# (.NET Core)
"pubspec.yaml", // Dart
"Project.toml", // Julia
"mix.exs", // Elixir
"rebar.config", // Erlang
"shard.yml", // Crystal
"Package.swift", // Swift
"dependencies.gradle", // Kotlin (when using Gradle)
"Podfile", // Objective-C/Swift (CocoaPods)
"*.cabal", // Haskell
"dub.json", // D
];
const MAX_EXPLORE_DEPTH = 2;
const OnboardSlashCommand: SlashCommand = {
name: "onboard",
description: "Familiarize yourself with the codebase",
run: async function* ({ llm, ide }) {
const [workspaceDir] = await ide.getWorkspaceDirs();
const context = await gatherProjectContext(workspaceDir, ide);
const prompt = createOnboardingPrompt(context);
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
])) {
yield stripImages(chunk.content);
}
},
};
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
const entries = await fs.readdir(dir, { withFileTypes: true });
let ig = ignore().add(defaultIgnoreDir).add(defaultIgnoreFile);
const gitIgnorePath = path.join(dir, ".gitignore");
const hasIgnoreFile = await fs
.access(gitIgnorePath)
.then(() => true)
.catch(() => false);
if (hasIgnoreFile) {
const gitIgnore = await ide.readFile(gitIgnorePath);
const igPatterns = gitIgArrayFromFile(gitIgnore);
ig = ig.add(igPatterns);
}
const filteredEntries = entries.filter((entry) => !ig.ignores(entry.name));
return filteredEntries;
}
async function gatherProjectContext(
workspaceDir: string,
ide: IDE,
): Promise<string> {
let context = "";
async function exploreDirectory(dir: string, currentDepth: number = 0) {
if (currentDepth > MAX_EXPLORE_DEPTH) {
return;
}
const entries = await getEntriesFilteredByIgnore(dir, ide);
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relativePath = path.relative(workspaceDir, fullPath);
if (entry.isDirectory()) {
context += `\nFolder: ${relativePath}\n`;
await exploreDirectory(fullPath, currentDepth + 1);
} else {
if (entry.name.toLowerCase() === "readme.md") {
const content = await fs.readFile(fullPath, "utf-8");
context += `README for ${relativePath}:\n${content}\n\n`;
} else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.name)) {
const content = await fs.readFile(fullPath, "utf-8");
context += `${entry.name} for ${relativePath}:\n${content}\n\n`;
}
}
}
}
await exploreDirectory(workspaceDir);
return context;
}
function createOnboardingPrompt(context: string): string {
return `
As a helpful AI assistant, your task is to onboard a new developer to this project.
Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview:
${context}
Please provide an overview of the project with the following guidelines:
- Determine the most important folders in the project, at most 10
- Go through each important folder step-by-step:
- Explain what each folder does in isolation by summarzing the README or package.json file, if available
- Mention the most popular or common packages used in that folder and their roles.
- After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture:
- How different parts of the codebase fit together.
- The overall project architecture or design patterns evident from the folder structure and dependencies.
- Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown.
Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole.
Here is an example of a valid response:
## Important folders
### /folder1
- Description: Contains the main application logic.
- Key packages: Express.js for routing, Mongoose for database operations.
#### /folder1/folder2
## Project Architecture
- The frontend is built using React and Redux for state management.
- The backend is a Node.js application using Express.js for routing and Mongoose for database operations.
- The application follows a Model-View-Controller (MVC) architecture.
## Additional Insights
- The project is using a monorepo structure.
- The project uses TypeScript for type checking.
`;
}
export default OnboardSlashCommand;

View file

@ -258,6 +258,7 @@ export class ConfigHandler {
const newConfig = await this.currentProfile.reloadConfig();
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
this.notifyConfigListeners(newConfig);
return newConfig;
}
getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {

View file

@ -587,7 +587,9 @@ async function loadFullConfigNode(
// Try config.ts first
const configJsPath = getConfigJsPath();
const module = await import(configJsPath);
delete require.cache[require.resolve(configJsPath)];
if (typeof require !== "undefined") {
delete require.cache[require.resolve(configJsPath)];
}
if (!module.modifyConfig) {
throw new Error("config.ts does not export a modifyConfig function.");
}
@ -604,7 +606,9 @@ async function loadFullConfigNode(
ideSettings.remoteConfigServerUrl,
);
const module = await import(configJsPathForRemote);
delete require.cache[require.resolve(configJsPathForRemote)];
if (typeof require !== "undefined") {
delete require.cache[require.resolve(configJsPathForRemote)];
}
if (!module.modifyConfig) {
throw new Error("config.ts does not export a modifyConfig function.");
}

View file

@ -4,8 +4,8 @@ import * as YAML from "yaml";
import type { IDE, SlashCommand } from "..";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../llm/llms/index";
import { getBasename } from "../util/index";
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
@ -15,6 +15,7 @@ export async function getPromptFiles(
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
@ -89,6 +90,32 @@ export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommand {
const { name, description, systemMessage, prompt } = parsePromptFile(
path,
content,
);
return {
name,
description,
run: async function* (context) {
const userInput = extractUserInput(context.input, name);
const renderedPrompt = await renderPrompt(prompt, context, userInput);
const messages = updateChatHistory(
context.history,
name,
renderedPrompt,
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
},
};
}
function parsePromptFile(path: string, content: string) {
let [preambleRaw, prompt] = content.split("\n---\n");
if (prompt === undefined) {
prompt = preambleRaw;
@ -105,115 +132,122 @@ export function slashCommandFromPromptFile(
prompt = prompt.split("</system>")[1].trim();
}
return {
name,
description,
run: async function* ({
input,
llm,
history,
ide,
config,
fetch,
selectedCode,
addContextItem,
}) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${name}`)) {
userInput = userInput
.slice(name.length + 1, userInput.length)
.trimStart();
}
return { name, description, systemMessage, prompt };
}
// Render prompt template
const helpers: [string, Handlebars.HelperDelegate][] | undefined =
config.contextProviders?.map((provider) => {
return [
provider.description.title,
async (context: any) => {
const items = await provider.getContextItems(context, {
config,
embeddingsProvider: config.embeddingsProvider,
fetch,
fullInput: userInput,
ide,
llm,
reranker: config.reranker,
selectedCode,
});
items.forEach((item) =>
addContextItem({
...item,
id: {
itemId: item.description,
providerTitle: provider.description.title,
},
}),
);
return items.map((item) => item.content).join("\n\n");
},
];
});
function extractUserInput(input: string, commandName: string): string {
if (input.startsWith(`/${commandName}`)) {
return input.slice(commandName.length + 1).trimStart();
}
return input;
}
// A few context providers that don't need to be in config.json to work in .prompt files
const diff = await ide.getDiff();
const currentFilePath = await ide.getCurrentFile();
const promptUserInput = await renderTemplatedString(
prompt,
ide.readFile.bind(ide),
{
input: userInput,
diff,
currentFile: currentFilePath
? await ide.readFile(currentFilePath)
: undefined,
},
helpers,
async function renderPrompt(prompt: string, context: any, userInput: string) {
const helpers = getContextProviderHelpers(context);
// A few context providers that don't need to be in config.json to work in .prompt files
const diff = await context.ide.getDiff();
const currentFilePath = await context.ide.getCurrentFile();
const currentFile = currentFilePath
? await context.ide.readFile(currentFilePath)
: undefined;
return renderTemplatedString(
prompt,
context.ide.readFile.bind(context.ide),
{ diff, currentFile, input: userInput },
helpers,
);
}
function getContextProviderHelpers(
context: any,
): Array<[string, Handlebars.HelperDelegate]> | undefined {
return context.config.contextProviders?.map((provider: any) => [
provider.description.title,
async (helperContext: any) => {
const items = await provider.getContextItems(helperContext, {
config: context.config,
embeddingsProvider: context.config.embeddingsProvider,
fetch: context.fetch,
fullInput: context.input,
ide: context.ide,
llm: context.llm,
reranker: context.config.reranker,
selectedCode: context.selectedCode,
});
items.forEach((item: any) =>
context.addContextItem(createContextItem(item, provider)),
);
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
return items.map((item: any) => item.content).join("\n\n");
},
]);
}
if (
Array.isArray(content) &&
content.some((part) => part.text?.startsWith(`/${name}`))
) {
messages[i] = {
...messages[i],
content: content.map((part) => {
return part.text?.startsWith(`/${name}`)
? { ...part, text: promptUserInput }
: part;
}),
};
break;
} else if (
typeof content === "string" &&
content.startsWith(`/${name}`)
) {
messages[i] = { ...messages[i], content: promptUserInput };
break;
}
}
// System message
if (systemMessage) {
if (messages[0]?.role === "system") {
messages[0].content = systemMessage;
} else {
messages.unshift({ role: "system", content: systemMessage });
}
}
for await (const chunk of llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
function createContextItem(item: any, provider: any) {
return {
...item,
id: {
itemId: item.description,
providerTitle: provider.description.title,
},
};
}
function updateChatHistory(
history: any[],
commandName: string,
renderedPrompt: string,
systemMessage?: string,
) {
const messages = [...history];
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
if (Array.isArray(content)) {
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
messages[i] = updateArrayContent(
messages[i],
commandName,
renderedPrompt,
);
break;
}
} else if (
typeof content === "string" &&
content.startsWith(`/${commandName}`)
) {
messages[i] = { ...messages[i], content: renderedPrompt };
break;
}
}
if (systemMessage) {
messages[0]?.role === "system"
? (messages[0].content = systemMessage)
: messages.unshift({ role: "system", content: systemMessage });
}
return messages;
}
function updateArrayContent(
message: any,
commandName: string,
renderedPrompt: string,
) {
return {
...message,
content: message.content.map((part: any) =>
part.text?.startsWith(`/${commandName}`)
? { ...part, text: renderedPrompt }
: part,
),
};
}

View file

@ -1,28 +1,5 @@
const Types = `
declare global {
declare global {
interface Window {
ide?: "vscode";
windowId: string;
serverUrl: string;
vscMachineId: string;
vscMediaUrl: string;
fullColorTheme?: {
rules?: {
token?: string;
foreground?: string;
}[];
};
colorThemeName?: string;
workspacePaths?: string[];
postIntellijMessage?: (
messageType: string,
data: any,
messageIde: string,
) => void;
}
}
export interface ChunkWithoutID {
content: string;
startLine: number;
@ -507,6 +484,7 @@ declare global {
| "gemini"
| "mistral"
| "bedrock"
| "sagemaker"
| "deepinfra"
| "flowise"
| "groq"

View file

@ -6,6 +6,7 @@ import {
LoadSubmenuItemsArgs,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import getDatabaseAdapter from "dbinfoz";
class DatabaseContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -30,10 +31,9 @@ class DatabaseContextProvider extends BaseContextProvider {
const [connectionName, table] = query.split(".");
const { getDatabaseAdapter } = await import("dbinfoz");
for (const connection of connections) {
if (connection.name === connectionName) {
// @ts-ignore (incorrect typings on module's declaration file)
const adapter = getDatabaseAdapter(
connection.connection_type,
connection.connection,
@ -87,9 +87,8 @@ class DatabaseContextProvider extends BaseContextProvider {
return contextItems;
}
const { getDatabaseAdapter } = await import("dbinfoz");
for (const connection of connections) {
// @ts-ignore (incorrect typings on module's declaration file)
const adapter = getDatabaseAdapter(
connection.connection_type,
connection.connection,

View file

@ -1,7 +1,6 @@
import { ContextProviderName } from "../../index.js";
import { BaseContextProvider } from "../index.js";
import CodeContextProvider from "./CodeContextProvider.js";
import CodebaseContextProvider from "./CodebaseContextProvider.js";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider.js";
import CurrentFileContextProvider from "./CurrentFileContextProvider.js";
import DatabaseContextProvider from "./DatabaseContextProvider.js";

View file

@ -7,7 +7,6 @@ import {
} from "../../../index.js";
import { chunkDocument } from "../../../indexing/chunk/chunk.js";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js";
import { MAX_CHUNK_SIZE } from "../../../llm/constants.js";
import { retrieveFts } from "../fullTextSearch.js";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js";
@ -20,6 +19,7 @@ export interface RetrievalPipelineOptions {
nRetrieve: number;
nFinal: number;
tags: BranchAndDir[];
pathSep: string;
filterDirectory?: string;
}
@ -30,8 +30,10 @@ export interface IRetrievalPipeline {
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private lanceDbIndex: LanceDbIndex;
constructor(protected readonly options: RetrievalPipelineOptions) {
this.lanceDbIndex = new LanceDbIndex(options.embeddingsProvider, (path) =>
options.ide.readFile(path),
this.lanceDbIndex = new LanceDbIndex(
options.embeddingsProvider,
(path) => options.ide.readFile(path),
options.pathSep,
);
}
@ -60,7 +62,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
const fileChunks = chunkDocument({
filepath,
contents,
maxChunkSize: MAX_CHUNK_SIZE,
maxChunkSize: this.options.embeddingsProvider.maxChunkSize,
digest: filepath,
});

View file

@ -70,6 +70,7 @@ export async function retrieveContextItemsFromEmbeddings(
nFinal,
nRetrieve,
tags,
pathSep: await extras.ide.pathSep(),
embeddingsProvider: extras.embeddingsProvider,
reranker: extras.reranker,
filterDirectory,

View file

@ -13,6 +13,7 @@ const modelDescriptionSchema = z.object({
"gemini",
"mistral",
"bedrock",
"sagemaker",
"cloudflare",
"azure",
]),

View file

@ -171,6 +171,9 @@ export class Core {
this.messenger.onError((err) => {
console.error(err);
Telemetry.capture("core_messenger_error", {
message: err.message,
});
this.messenger.request("errorPopup", { message: err.message });
});
@ -366,6 +369,7 @@ export class Core {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return({
modelTitle: model.title ?? model.model,
completion: "",
prompt: "",
completionOptions: {
@ -402,6 +406,7 @@ export class Core {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return({
modelTitle: model.title ?? model.model,
completion: "",
prompt: "",
completionOptions: {
@ -679,6 +684,16 @@ export class Core {
)) {
this.messenger.request("indexProgress", update);
this.indexingState = update;
if (update.status === "failed") {
Telemetry.capture(
"indexing_error",
{
error: update.desc,
},
false,
);
}
}
this.messenger.send("refreshSubmenuItems", undefined);

3
core/index.d.ts vendored
View file

@ -289,6 +289,7 @@ export interface InputModifiers {
}
export interface PromptLog {
modelTitle: string;
completionOptions: CompletionOptions;
prompt: string;
completion: string;
@ -351,6 +352,7 @@ export interface LLMOptions {
watsonxUsername?: string;
watsonxPassword?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -592,6 +594,7 @@ type ModelProvider =
| "gemini"
| "mistral"
| "bedrock"
| "sagemaker"
| "deepinfra"
| "flowise"
| "groq"

View file

@ -7,6 +7,7 @@ import type {
IndexingProgressUpdate,
} from "../index.js";
import { getBasename, getLastNPathParts } from "../util/index.js";
import { migrate } from "../util/paths.js";
import {
TSQueryType,
getParserForFile,
@ -43,6 +44,55 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
snippetId INTEGER NOT NULL,
FOREIGN KEY (snippetId) REFERENCES code_snippets (id)
)`);
migrate("delete_duplicate_code_snippets", async () => {
// Delete duplicate entries in code_snippets
await db.exec(`
DELETE FROM code_snippets
WHERE id NOT IN (
SELECT MIN(id)
FROM code_snippets
GROUP BY path, cacheKey, content, title, startLine, endLine
)
`);
// Add unique constraint if it doesn't exist
await db.exec(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_code_snippets_unique
ON code_snippets (path, cacheKey, content, title, startLine, endLine)
`);
// Delete code_snippets associated with duplicate code_snippets_tags entries
await db.exec(`
DELETE FROM code_snippets
WHERE id IN (
SELECT snippetId
FROM code_snippets_tags
WHERE (snippetId, tag) IN (
SELECT snippetId, tag
FROM code_snippets_tags
GROUP BY snippetId, tag
HAVING COUNT(*) > 1
)
)
`);
// Delete duplicate entries
await db.exec(`
DELETE FROM code_snippets_tags
WHERE id NOT IN (
SELECT MIN(id)
FROM code_snippets_tags
GROUP BY snippetId, tag
)
`);
// Add unique constraint if it doesn't exist
await db.exec(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_snippetId_tag
ON code_snippets_tags (snippetId, tag)
`);
});
}
async getSnippetsInFile(
@ -93,12 +143,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
);
} catch (e) {
// If can't parse, assume malformatted code
console.error(`Error parsing ${compute.path}:`, e);
}
// Add snippets to sqlite
for (const snippet of snippets) {
const { lastID } = await db.run(
"INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
"REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
[
compute.path,
compute.cacheKey,
@ -110,7 +161,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
);
await db.run(
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
"REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
[lastID, tagString],
);
}
@ -136,15 +187,33 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
}
for (let i = 0; i < results.addTag.length; i++) {
const snippetsWithPath = await db.all(
"SELECT * FROM code_snippets WHERE cacheKey = ?",
[results.addTag[i].cacheKey],
);
const addTag = results.addTag[i];
let snippets: (ChunkWithoutID & { title: string })[] = [];
try {
snippets = await this.getSnippetsInFile(
addTag.path,
await this.ide.readFile(addTag.path),
);
} catch (e) {
// If can't parse, assume malformatted code
console.error(`Error parsing ${addTag.path}:`, e);
}
for (const snippet of snippetsWithPath) {
for (const snippet of snippets) {
const { lastID } = await db.run(
"INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
[
addTag.path,
addTag.cacheKey,
snippet.content,
snippet.title,
snippet.startLine,
snippet.endLine,
],
);
await db.run(
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
[snippet.id, tagString],
[lastID, tagString],
);
}

View file

@ -1,13 +1,17 @@
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { CodebaseIndex, IndexResultType } from "./types.js";
import { walkDir } from "./walkDir.js";
import {
CodebaseIndex,
IndexResultType,
RefreshIndexResults,
} from "./types.js";
import { walkDirAsync } from "./walkDir.js";
export class PauseToken {
constructor(private _paused: boolean) {}
@ -24,23 +28,26 @@ export class PauseToken {
export class CodebaseIndexer {
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
protected readonly ide: IDE,
private readonly pauseToken: PauseToken,
private readonly continueServerClient: IContinueServerClient,
) {}
private async getIndexesToBuild(): Promise<CodebaseIndex[]> {
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
const config = await this.configHandler.loadConfig();
const pathSep = await this.ide.pathSep();
const indexes = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
pathSep,
this.continueServerClient,
config.embeddingsProvider.maxChunkSize,
), // Chunking must come first
new LanceDbIndex(
config.embeddingsProvider,
this.ide.readFile.bind(this.ide),
pathSep,
this.continueServerClient,
),
new FullTextSearchCodebaseIndex(),
@ -62,24 +69,31 @@ export class CodebaseIndexer {
}
const branch = await this.ide.getBranch(workspaceDir);
const repoName = await this.ide.getRepoName(workspaceDir);
const stats = await this.ide.getLastModified([file]);
const indexesToBuild = await this.getIndexesToBuild();
for (const codebaseIndex of indexesToBuild) {
const tag: IndexTag = {
const stats = await this.ide.getLastModified([file]);
for (const index of indexesToBuild) {
const tag = {
directory: workspaceDir,
branch,
artifactId: codebaseIndex.artifactId,
artifactId: index.artifactId,
};
const [results, lastUpdated, markComplete] = await getComputeDeleteAddRemove(
const [results, lastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
// since this is only a single file update / save we do not want to actualy remove anything, we just want to recompute for our single file
results.removeTag = [];
results.addTag = [];
results.del = [];
for await (const _ of index.update(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
results,
markComplete,
repoName,
);
for await (const _ of codebaseIndex.update(tag, results, markComplete, repoName)) {
lastUpdated.forEach((lastUpdated, path) => {
markComplete([lastUpdated], IndexResultType.UpdateLastUpdated);
});
)) {
}
}
}
@ -115,12 +129,7 @@ export class CodebaseIndexer {
};
}
const indexesToBuild = await this.getIndexesToBuild();
let completedDirs = 0;
const totalRelativeExpectedTime = indexesToBuild.reduce(
(sum, index) => sum + index.relativeExpectedTime,
0,
);
// Wait until Git Extension has loaded to report progress
// so we don't appear stuck at 0% while waiting
@ -131,113 +140,226 @@ export class CodebaseIndexer {
desc: "Starting indexing...",
status: "loading",
};
const beginTime = Date.now();
for (const directory of workspaceDirs) {
const files = await walkDir(directory, this.ide);
const stats = await this.ide.getLastModified(files);
const dirBasename = await this.basename(directory);
yield {
progress,
desc: `Discovering files in ${dirBasename}...`,
status: "indexing",
};
const workspaceFiles = [];
for await (const p of walkDirAsync(directory, this.ide)) {
workspaceFiles.push(p);
if (abortSignal.aborted) {
yield {
progress: 1,
desc: "Indexing cancelled",
status: "disabled",
};
return;
}
if (this.pauseToken.paused) {
yield* this.yieldUpdateAndPause();
}
}
const branch = await this.ide.getBranch(directory);
const repoName = await this.ide.getRepoName(directory);
let completedRelativeExpectedTime = 0;
let nextLogThreshold = 0;
for (const codebaseIndex of indexesToBuild) {
// TODO: IndexTag type should use repoName rather than directory
const tag: IndexTag = {
try {
for await (const updateDesc of this.indexFiles(
directory,
workspaceFiles,
branch,
artifactId: codebaseIndex.artifactId,
};
const [results, lastUpdated, markComplete] = await getComputeDeleteAddRemove(
repoName,
)) {
// Handle pausing in this loop because it's the only one really taking time
if (abortSignal.aborted) {
yield {
progress: 1,
desc: "Indexing cancelled",
status: "disabled",
};
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(workspaceFiles.length * updateDesc.progress),
updateDesc.progress,
);
}
}
} catch (err) {
yield this.handleErrorAndGetProgressUpdate(err);
return;
}
completedDirs += 1;
}
yield {
progress: 100,
desc: "Indexing Complete",
status: "done",
};
}
private handleErrorAndGetProgressUpdate(
err: unknown,
): IndexingProgressUpdate {
console.log("error when indexing: ", err);
if (err instanceof Error) {
return this.errorToProgressUpdate(err);
}
return {
progress: 0,
desc: `Indexing failed: ${err}`,
status: "failed",
};
}
private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
const errorRegex =
/Invalid argument error: Values length (\d+) is less than the length \((\d+)\) multiplied by the value size \(\d+\)/;
const match = err.message.match(errorRegex);
let errMsg: string;
if (match) {
const [_, valuesLength, expectedLength] = match;
errMsg = `Generated embedding had length ${valuesLength} but was expected to be ${expectedLength}. This may be solved by deleting ~/.continue/index and refreshing the window to re-index.`;
} else {
errMsg = `${err}`;
}
return {
progress: 0,
desc: errMsg,
status: "failed",
};
}
private logProgress(
beginTime: number,
completedFileCount: number,
progress: number,
) {
const timeTaken = Date.now() - beginTime;
const seconds = Math.round(timeTaken / 1000);
const progressPercentage = (progress * 100).toFixed(1);
const filesPerSec = (completedFileCount / seconds).toFixed(2);
console.debug(
`Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
);
}
private async *yieldUpdateAndPause(): AsyncGenerator<IndexingProgressUpdate> {
yield {
progress: 0,
desc: "Indexing Paused",
status: "paused",
};
while (this.pauseToken.paused) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
private getBatchSize(workspaceSize: number): number {
return 100;
}
/*
* enables the indexing operation to be completed in small batches, this is important in large
* repositories where indexing can quickly use up all the memory available
*/
private *batchRefreshIndexResults(
results: RefreshIndexResults,
workspaceSize: number,
): Generator<RefreshIndexResults> {
let curPos = 0;
const batchSize = this.getBatchSize(workspaceSize);
while (
curPos < results.compute.length ||
curPos < results.del.length ||
curPos < results.addTag.length ||
curPos < results.removeTag.length
) {
yield {
compute: results.compute.slice(curPos, curPos + batchSize),
del: results.del.slice(curPos, curPos + batchSize),
addTag: results.addTag.slice(curPos, curPos + batchSize),
removeTag: results.removeTag.slice(curPos, curPos + batchSize),
};
curPos += batchSize;
}
}
private async *indexFiles(
workspaceDir: string,
workspaceFiles: string[],
branch: string,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const stats = await this.ide.getLastModified(workspaceFiles);
const indexesToBuild = await this.getIndexesToBuild();
let completedIndexCount = 0;
let progress = 0;
for (const codebaseIndex of indexesToBuild) {
const tag: IndexTag = {
directory: workspaceDir,
branch,
artifactId: codebaseIndex.artifactId,
};
yield {
progress: progress,
desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
status: "indexing",
};
const [results, lastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
try {
for await (let {
progress: indexProgress,
desc,
} of codebaseIndex.update(tag, results, markComplete, repoName)) {
// Handle pausing in this loop because it's the only one really taking time
if (abortSignal.aborted) {
yield {
progress: 1,
desc: "Indexing cancelled",
status: "disabled",
};
return;
}
if (this.pauseToken.paused) {
yield {
progress,
desc: "Paused",
status: "paused",
};
while (this.pauseToken.paused) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
progress =
(completedDirs +
(completedRelativeExpectedTime +
Math.min(1.0, indexProgress) *
codebaseIndex.relativeExpectedTime) /
totalRelativeExpectedTime) /
workspaceDirs.length;
yield {
progress,
desc,
status: "indexing",
};
}
lastUpdated.forEach((lastUpdated, path) => {
markComplete([lastUpdated], IndexResultType.UpdateLastUpdated);
});
completedRelativeExpectedTime += codebaseIndex.relativeExpectedTime;
const totalOps =
results.compute.length +
results.del.length +
results.addTag.length +
results.removeTag.length;
let completedOps = 0;
for (const subResult of this.batchRefreshIndexResults(
results,
workspaceFiles.length,
)) {
for await (const { desc } of codebaseIndex.update(
tag,
subResult,
markComplete,
repoName,
)) {
yield {
progress:
(completedDirs +
completedRelativeExpectedTime / totalRelativeExpectedTime) /
workspaceDirs.length,
desc: "Completed indexing " + codebaseIndex.artifactId,
progress: progress,
desc,
status: "indexing",
};
} catch (e: any) {
let errMsg = `${e}`;
const errorRegex =
/Invalid argument error: Values length (\d+) is less than the length \((\d+)\) multiplied by the value size \(\d+\)/;
const match = e.message.match(errorRegex);
if (match) {
const [_, valuesLength, expectedLength] = match;
errMsg = `Generated embedding had length ${valuesLength} but was expected to be ${expectedLength}. This may be solved by deleting ~/.continue/index and refreshing the window to re-index.`;
}
yield {
progress: 0,
desc: errMsg,
status: "failed",
};
console.warn(
`Error updating the ${codebaseIndex.artifactId} index: ${e}`,
);
return;
}
completedOps +=
subResult.compute.length +
subResult.del.length +
subResult.addTag.length +
subResult.removeTag.length;
progress =
(completedIndexCount + completedOps / totalOps) *
(1 / indexesToBuild.length);
}
completedDirs++;
progress = completedDirs / workspaceDirs.length;
yield {
progress,
desc: "Indexing Complete",
status: "done",
};
await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
completedIndexCount += 1;
}
}
@ -250,4 +372,10 @@ export class CodebaseIndexer {
}
return undefined;
}
private async basename(filepath: string): Promise<string> {
const pathSep = await this.ide.pathSep();
const path = filepath.split(pathSep);
return path[path.length - 1];
}
}

View file

@ -1,4 +1,5 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { RunResult } from "sqlite3";
import { v4 as uuidv4 } from "uuid";
import { Table } from "vectordb";
import { IContinueServerClient } from "../continueServer/interface.js";
@ -11,11 +12,12 @@ import {
} from "../index.js";
import { getBasename } from "../util/index.js";
import { getLanceDbPath, migrate } from "../util/paths.js";
import { chunkDocument } from "./chunk/chunk.js";
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import {
CodebaseIndex,
IndexResultType,
MarkCompleteCallback,
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
@ -38,6 +40,7 @@ export class LanceDbIndex implements CodebaseIndex {
constructor(
private readonly embeddingsProvider: EmbeddingsProvider,
private readonly readFile: (filepath: string) => Promise<string>,
private readonly pathSep: string,
private readonly continueServerClient?: IContinueServerClient,
) {}
@ -82,105 +85,83 @@ export class LanceDbIndex implements CodebaseIndex {
);
}
private async *computeChunks(
items: PathAndCacheKey[],
): AsyncGenerator<
| [
number,
LanceDbRow,
{ startLine: number; endLine: number; contents: string },
string,
]
| PathAndCacheKey
> {
const contents = await Promise.all(
items.map(({ path }) => this.readFile(path)),
);
for (let i = 0; i < items.length; i++) {
// Break into chunks
const content = contents[i];
const chunks: Chunk[] = [];
let hasEmptyChunks = false;
for await (const chunk of chunkDocument({
filepath: items[i].path,
contents: content,
maxChunkSize: this.embeddingsProvider.maxChunkSize,
digest: items[i].cacheKey,
})) {
if (chunk.content.length == 0) {
hasEmptyChunks = true;
break;
}
chunks.push(chunk);
}
if (hasEmptyChunks) {
// File did not chunk properly, let's skip it.
continue;
}
if (chunks.length > 20) {
// Too many chunks to index, probably a larger file than we want to include
continue;
}
let embeddings: number[][];
try {
// Calculate embeddings
embeddings = await this.embeddingsProvider.embed(
chunks.map((c) => c.content),
);
} catch (e) {
// Rather than fail the entire indexing process, we'll just skip this file
// so that it may be picked up on the next indexing attempt
console.warn(
`Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}: ${e}`,
);
continue;
}
if (embeddings.some((emb) => emb === undefined)) {
throw new Error(
`Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}`,
);
}
// Create row format
for (let j = 0; j < chunks.length; j++) {
const progress = (i + j / chunks.length) / items.length;
const row = {
vector: embeddings[j],
path: items[i].path,
cachekey: items[i].cacheKey,
uuid: uuidv4(),
};
const chunk = chunks[j];
yield [
progress,
row,
{
contents: chunk.content,
startLine: chunk.startLine,
endLine: chunk.endLine,
},
`Indexing ${getBasename(chunks[j].filepath)}`,
];
}
yield items[i];
private async packToRows(item: PathAndCacheKey): Promise<LanceDbRow[]> {
const content = await this.readFile(item.path);
if (!shouldChunk(this.pathSep, item.path, content)) {
return [];
}
const chunks: Chunk[] = [];
const chunkParams = {
filepath: item.path,
contents: content,
maxChunkSize: this.embeddingsProvider.maxChunkSize,
digest: item.cacheKey,
};
for await (const chunk of chunkDocument(chunkParams)) {
if (chunk.content.length === 0) {
// File did not chunk properly, let's skip it.
throw new Error("did not chunk properly");
}
chunks.push(chunk);
}
const embeddings = await this.chunkListToEmbedding(chunks);
if (chunks.length !== embeddings.length) {
throw new Error(
`Unexpected lengths: chunks and embeddings do not match for ${item.path}`,
);
}
const results = [];
for (let i = 0; i < chunks.length; i++) {
results.push({
path: item.path,
cachekey: item.cacheKey,
uuid: uuidv4(),
vector: embeddings[i],
startLine: chunks[i].startLine,
endLine: chunks[i].endLine,
contents: chunks[i].content,
});
}
return results;
}
private async chunkListToEmbedding(chunks: Chunk[]): Promise<number[][]> {
let embeddings: number[][];
try {
embeddings = await this.embeddingsProvider.embed(
chunks.map((c) => c.content),
);
} catch (err) {
throw new Error(
`Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}: ${err}`,
{ cause: err },
);
}
if (embeddings.some((emb) => emb === undefined)) {
throw new Error(
`Empty embedding returned for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}`,
);
}
return embeddings;
}
private async computeRows(items: PathAndCacheKey[]): Promise<LanceDbRow[]> {
const rowChunkPromises = items.map(this.packToRows.bind(this));
const rowChunkLists = [];
for (let i = 0; i < items.length; i++) {
try {
rowChunkLists.push(await rowChunkPromises[i]);
} catch (err) {
console.log(`LanceDBIndex, skipping ${items[i].path}: ${err}`);
}
}
return rowChunkLists.flat();
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
markComplete: (
items: PathAndCacheKey[],
resultType: IndexResultType,
) => void,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const lancedb = await import("vectordb");
@ -216,7 +197,7 @@ export class LanceDbIndex implements CodebaseIndex {
}
// Mark item complete
markComplete([pathAndCacheKey], IndexResultType.Compute);
await markComplete([pathAndCacheKey], IndexResultType.Compute);
};
// Check remote cache
@ -277,39 +258,26 @@ export class LanceDbIndex implements CodebaseIndex {
}
}
const progressReservedForTagging = 0.1;
let accumulatedProgress = 0;
yield {
progress: 0,
desc: `Computing embeddings for ${
results.compute.length
} ${this.formatListPlurality("file", results.compute.length)}`,
status: "indexing",
};
let computedRows: LanceDbRow[] = [];
for await (const update of this.computeChunks(results.compute)) {
if (Array.isArray(update)) {
const [progress, row, data, desc] = update;
computedRows.push(row);
// Add the computed row to the cache
await sqlite.run(
"INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
row.uuid,
row.cachekey,
row.path,
this.artifactId,
JSON.stringify(row.vector),
data.startLine,
data.endLine,
data.contents,
const dbRows = await this.computeRows(results.compute);
await this.insertRows(sqlite, dbRows);
await Promise.all(
results.compute.map((item) => {
addComputedLanceDbRows(
item,
dbRows.filter((row) => row.path === item.path),
);
accumulatedProgress = progress * (1 - progressReservedForTagging);
yield {
progress: accumulatedProgress,
desc,
status: "indexing",
};
} else {
await addComputedLanceDbRows(update, computedRows);
computedRows = [];
}
}
}),
);
await markComplete(results.compute, IndexResultType.Compute);
let accumulatedProgress = 0;
// Add tag - retrieve the computed info from lance sqlite cache
for (const { path, cacheKey } of results.addTag) {
@ -343,7 +311,7 @@ export class LanceDbIndex implements CodebaseIndex {
}
}
markComplete([{ path, cacheKey }], IndexResultType.AddTag);
await markComplete([{ path, cacheKey }], IndexResultType.AddTag);
accumulatedProgress += 1 / results.addTag.length / 3;
yield {
progress: accumulatedProgress,
@ -367,7 +335,7 @@ export class LanceDbIndex implements CodebaseIndex {
};
}
}
markComplete(results.removeTag, IndexResultType.RemoveTag);
await markComplete(results.removeTag, IndexResultType.RemoveTag);
// Delete - also remove from sqlite cache
for (const { path, cacheKey } of results.del) {
@ -385,7 +353,7 @@ export class LanceDbIndex implements CodebaseIndex {
};
}
markComplete(results.del, IndexResultType.Delete);
await markComplete(results.del, IndexResultType.Delete);
yield {
progress: 1,
desc: "Completed Calculating Embeddings",
@ -466,4 +434,61 @@ export class LanceDbIndex implements CodebaseIndex {
};
});
}
private async insertRows(
db: DatabaseConnection,
rows: LanceDbRow[],
): Promise<void> {
return new Promise<void>((resolve, reject) => {
db.db.serialize(() => {
db.db.exec("BEGIN", (err: Error | null) => {
if (err) {
reject(new Error("error creating transaction", { cause: err }));
}
});
const sql =
"INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
rows.map((r) => {
db.db.run(
sql,
[
r.uuid,
r.cachekey,
r.path,
this.artifactId,
JSON.stringify(r.vector),
r.startLine,
r.endLine,
r.contents,
],
(result: RunResult, err: Error) => {
if (err) {
reject(
new Error("error inserting into lance_db_cache table", {
cause: err,
}),
);
}
},
);
});
db.db.exec("COMMIT", (err: Error | null) => {
if (err) {
reject(
new Error(
"error while committing insert into lance_db_rows transaction",
{ cause: err },
),
);
}
});
resolve();
});
});
}
private formatListPlurality(word: string, length: number): string {
return length <= 1 ? word : `${word}s`;
}
}

View file

@ -0,0 +1,69 @@
import type { IndexTag, IndexingProgressUpdate } from "../index.js";
import { DatabaseConnection, SqliteDb } from "./refreshIndex.js";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types.js";
/**
* This is a CodebaseIndex used for testing which files get indexed.
* It maintains a SQLite database of all file/tag pairs
*/
export class TestCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 0.1;
artifactId = "__test__";
private static async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS test_index (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
branch TEXT NOT NULL,
directory TEXT NOT NULL
)`);
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await TestCodebaseIndex._createTables(db);
for (const item of [...results.compute, ...results.addTag]) {
await db.run(
`INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)`,
[item.path, tag.branch, tag.directory],
);
}
for (const item of [...results.del, ...results.removeTag]) {
await db.run(
`DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?`,
[item.path, tag.branch, tag.directory],
);
}
markComplete(results.compute, IndexResultType.Compute);
markComplete(results.addTag, IndexResultType.AddTag);
markComplete(results.del, IndexResultType.Delete);
markComplete(results.removeTag, IndexResultType.RemoveTag);
}
async getIndexedFilesForTags(tags: IndexTag[]): Promise<string[]> {
const db = await SqliteDb.get();
await TestCodebaseIndex._createTables(db);
const rows = await db.all(
`SELECT path FROM test_index WHERE (branch, directory) IN (VALUES ${tags
.map(() => "(?, ?)")
.join(", ")})`,
tags.flatMap((tag) => [tag.branch, tag.directory]),
);
return rows.map((row: any) => row.path);
}
}

View file

@ -1,14 +1,17 @@
import { RunResult } from "sqlite3";
import { IContinueServerClient } from "../../continueServer/interface.js";
import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
import { getBasename } from "../../util/index.js";
import { getLanguageForFile } from "../../util/treeSitter.js";
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js";
import {
IndexResultType,
MarkCompleteCallback,
PathAndCacheKey,
RefreshIndexResults,
type CodebaseIndex,
} from "../types.js";
import { chunkDocument } from "./chunk.js";
import { chunkDocument, shouldChunk } from "./chunk.js";
export class ChunkCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 1;
@ -17,31 +20,13 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
constructor(
private readonly readFile: (filepath: string) => Promise<string>,
private readonly pathSep: string,
private readonly continueServerClient: IContinueServerClient,
private readonly maxChunkSize: number,
) {
this.readFile = readFile;
}
private async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cacheKey TEXT NOT NULL,
path TEXT NOT NULL,
idx INTEGER NOT NULL,
startLine INTEGER NOT NULL,
endLine INTEGER NOT NULL,
content TEXT NOT NULL
)`);
await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
chunkId INTEGER NOT NULL,
FOREIGN KEY (chunkId) REFERENCES chunks (id)
)`);
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
@ -49,28 +34,9 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await this._createTables(db);
await this.createTables(db);
const tagString = tagToString(tag);
async function handleChunk(chunk: Chunk) {
const { lastID } = await db.run(
"INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)",
[
chunk.digest,
chunk.filepath,
chunk.index,
chunk.startLine,
chunk.endLine,
chunk.content,
],
);
await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [
lastID,
tagString,
]);
}
// Check the remote cache
if (this.continueServerClient.connected) {
try {
@ -82,9 +48,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
);
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
for (const chunk of chunks) {
await handleChunk(chunk);
}
await this.insertChunks(db, tagString, chunks);
}
results.compute = results.compute.filter(
(item) => !resp.files[item.cacheKey],
@ -94,62 +58,34 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
}
}
const progressReservedForTagging = 0.3;
let accumulatedProgress = 0;
// Compute chunks for new files
const contents = await Promise.all(
results.compute.map(({ path }) => this.readFile(path)),
);
for (let i = 0; i < results.compute.length; i++) {
const item = results.compute[i];
// Insert chunks
if (contents.length) {
for await (const chunk of chunkDocument({
filepath: item.path,
contents: contents[i],
maxChunkSize: this.maxChunkSize,
digest: item.cacheKey,
})) {
await handleChunk(chunk);
}
}
accumulatedProgress =
(i / results.compute.length) * (1 - progressReservedForTagging);
if (results.compute.length > 0) {
yield {
progress: accumulatedProgress,
desc: `Chunking ${getBasename(item.path)}`,
desc: `Chunking ${results.compute.length} ${this.formatListPlurality("file", results.compute.length)}`,
status: "indexing",
progress: accumulatedProgress,
};
markComplete([item], IndexResultType.Compute);
const chunks = await this.computeChunks(results.compute);
await this.insertChunks(db, tagString, chunks);
await markComplete(results.compute, IndexResultType.Compute);
}
// Add tag
const addContents = await Promise.all(
results.addTag.map(({ path }) => this.readFile(path)),
);
for (let i = 0; i < results.addTag.length; i++) {
const item = results.addTag[i];
// Insert chunks
if (contents.length) {
for await (const chunk of chunkDocument({
filepath: item.path,
contents: contents[i],
maxChunkSize: this.maxChunkSize,
digest: item.cacheKey,
})) {
handleChunk(chunk);
}
}
markComplete([item], IndexResultType.AddTag);
for (const item of results.addTag) {
await db.run(
`
INSERT INTO chunk_tags (chunkId, tag)
SELECT id, ? FROM chunks
WHERE cacheKey = ? AND path = ?
`,
[tagString, item.cacheKey, item.path],
);
await markComplete([item], IndexResultType.AddTag);
accumulatedProgress += 1 / results.addTag.length / 4;
yield {
progress: accumulatedProgress,
desc: `Chunking ${getBasename(item.path)}`,
desc: `Adding ${getBasename(item.path)}`,
status: "indexing",
};
}
@ -167,7 +103,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
`,
[tagString, item.cacheKey, item.path],
);
markComplete([item], IndexResultType.RemoveTag);
await markComplete([item], IndexResultType.RemoveTag);
accumulatedProgress += 1 / results.removeTag.length / 4;
yield {
progress: accumulatedProgress,
@ -187,7 +123,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
deleted.lastID,
]);
markComplete([item], IndexResultType.Delete);
await markComplete([item], IndexResultType.Delete);
accumulatedProgress += 1 / results.del.length / 4;
yield {
progress: accumulatedProgress,
@ -196,4 +132,83 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
};
}
}
private async createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cacheKey TEXT NOT NULL,
path TEXT NOT NULL,
idx INTEGER NOT NULL,
startLine INTEGER NOT NULL,
endLine INTEGER NOT NULL,
content TEXT NOT NULL
)`);
await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
chunkId INTEGER NOT NULL,
FOREIGN KEY (chunkId) REFERENCES chunks (id)
)`);
}
private async packToChunks(pack: PathAndCacheKey): Promise<Chunk[]> {
const contents = await this.readFile(pack.path);
if (!shouldChunk(this.pathSep, pack.path, contents)) {
return [];
}
const chunks: Chunk[] = [];
const chunkParams = {
filepath: pack.path,
contents,
maxChunkSize: this.maxChunkSize,
digest: pack.cacheKey,
};
for await (const c of chunkDocument(chunkParams)) {
chunks.push(c);
}
return chunks;
}
private async computeChunks(paths: PathAndCacheKey[]): Promise<Chunk[]> {
const chunkLists = await Promise.all(paths.map(p => this.packToChunks(p)));
return chunkLists.flat();
}
private async insertChunks(db: DatabaseConnection, tagString: string, chunks: Chunk[]) {
await new Promise<void>((resolve, reject) => {
db.db.serialize(() => {
db.db.exec("BEGIN", (err: Error | null) => {
if (err) {
reject(new Error("error creating transaction", { cause: err }));
}
});
const chunksSQL = "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)";
chunks.map(c => {
db.db.run(chunksSQL, [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content], (result: RunResult, err: Error) => {
if (err) {
reject(new Error("error inserting into chunks table", { cause: err }));
}
});
const chunkTagsSQL = "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)";
db.db.run(chunkTagsSQL, [ tagString ], (result: RunResult, err: Error) => {
if (err) {
reject(new Error("error inserting into chunk_tags table", { cause: err }));
}
});
});
db.db.exec("COMMIT", (err: Error | null) => {
if (err) {
reject(new Error("error while committing insert chunks transaction", { cause: err }));
}
});
resolve();
});
});
}
private formatListPlurality(word: string, length: number): string {
return length <= 1 ? word : `${word}s`;
}
}

View file

@ -1,4 +1,4 @@
import { Chunk, ChunkWithoutID } from "../../index.js";
import { Chunk, ChunkWithoutID, IDE } from "../../index.js";
import { countTokens, countTokensAsync } from "../../llm/countTokens.js";
import { supportedLanguages } from "../../util/treeSitter.js";
import { basicChunker } from "./basic.js";
@ -50,22 +50,24 @@ export async function* chunkDocument({
contents,
maxChunkSize,
)) {
chunkPromises.push(new Promise(async (resolve) => {
if (await countTokensAsync(chunkWithoutId.content) > maxChunkSize) {
console.warn(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
chunkPromises.push(
new Promise(async (resolve) => {
if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) {
console.debug(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
filepath,
countTokens(chunkWithoutId.content),
);
return resolve(undefined);
}
resolve({
...chunkWithoutId,
digest,
index,
filepath,
countTokens(chunkWithoutId.content),
);
return resolve(undefined);
}
resolve({
...chunkWithoutId,
digest,
index,
filepath,
});
}));
});
}),
);
index++;
}
for await (const chunk of chunkPromises) {
@ -75,3 +77,16 @@ export async function* chunkDocument({
yield chunk;
}
}
export function shouldChunk(pathSep: string, filepath: string, contents: string): boolean {
if (contents.length > 1000000) {
// if a file has more than 1m characters then skip it
return false;
}
if (contents.length === 0) {
return false;
}
const basename = filepath.split(pathSep).pop();
// files without extensions are often binary files, skip it if so
return basename?.includes(".") ?? false;
}

View file

@ -232,7 +232,7 @@ export async function* codeChunker(
const parser = await getParserForFile(filepath);
if (parser === undefined) {
console.warn(`Failed to load parser for file ${filepath}: `);
console.debug(`Failed to load parser for file ${filepath}: `);
return;
}

View file

@ -476,7 +476,7 @@ export default class DocsService {
await runSqliteMigrations(db);
db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title STRING NOT NULL,
startUrl STRING NOT NULL UNIQUE,

View file

@ -5,7 +5,7 @@ import {
FetchFunction,
} from "../../index.js";
import { MAX_CHUNK_SIZE } from "../../llm/constants.js";
import { DEFAULT_MAX_CHUNK_SIZE } from "../../llm/constants.js";
export interface IBaseEmbeddingsProvider extends EmbeddingsProvider {
options: EmbedOptions;
@ -38,7 +38,7 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
};
this.fetch = fetch;
// Include the `max_chunk_size` if it is not the default, since we need to create other indices for different chunk_sizes
if (this.maxChunkSize !== MAX_CHUNK_SIZE) {
if (this.maxChunkSize !== DEFAULT_MAX_CHUNK_SIZE) {
this.id = `${this.constructor.name}::${this.options.model}::${this.maxChunkSize}`;
} else {
this.id = `${this.constructor.name}::${this.options.model}`;
@ -50,7 +50,7 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
abstract embed(chunks: string[]): Promise<number[][]>;
get maxChunkSize(): number {
return this.options.maxChunkSize ?? MAX_CHUNK_SIZE;
return this.options.maxChunkSize ?? DEFAULT_MAX_CHUNK_SIZE;
}
static getBatchedChunks(chunks: string[]): string[][] {

View file

@ -59,12 +59,12 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.gcda",
"*.gcno",
"go.sum",
".env",
".gitignore",
".gitkeep",
".continueignore",
"*.env",
"*.gitignore",
"*.gitkeep",
"*.continueignore",
"config.json",
".csv",
"*.csv",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];
@ -100,3 +100,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
export const DEFAULT_IGNORE =
DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
export function gitIgArrayFromFile(file: string) {
return file
.split(/\r?\n/) // Split on new line
.map((l) => l.trim()) // Remove whitespace
.filter((l) => !/^#|^$/.test(l)); // Remove empty lines
}

View file

@ -23,6 +23,8 @@ export class SqliteDb {
static db: DatabaseConnection | null = null;
private static async createTables(db: DatabaseConnection) {
await db.exec("PRAGMA journal_mode=WAL;");
await db.exec(
`CREATE TABLE IF NOT EXISTS tag_catalog (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@ -406,7 +408,7 @@ export async function getComputeDeleteAddRemove(
for await (const _ of globalCacheIndex.update(
tag,
results,
() => {},
async () => {},
repoName,
)) {
}
@ -433,7 +435,7 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
_: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const add = results.addTag;
const add = [...results.compute, ...results.addTag];
const remove = [...results.del, ...results.removeTag];
await Promise.all([
...remove.map(({ cacheKey }) => {

View file

@ -11,7 +11,7 @@ export enum IndexResultType {
export type MarkCompleteCallback = (
items: PathAndCacheKey[],
resultType: IndexResultType,
) => void;
) => Promise<void>;
export interface CodebaseIndex {
artifactId: string;

View file

@ -6,6 +6,7 @@ import {
DEFAULT_IGNORE_FILETYPES,
defaultIgnoreDir,
defaultIgnoreFile,
gitIgArrayFromFile,
} from "./ignore.js";
export interface WalkerOptions {
@ -46,6 +47,10 @@ class DFSWalker {
// walk is a depth-first search implementation
public async *walk(): AsyncGenerator<string> {
const fixupFunc = await this.newPathFixupFunc(
this.options.returnRelativePaths ? "" : this.path,
this.ide,
);
const root: WalkContext = {
walkableEntry: {
relPath: "",
@ -73,10 +78,10 @@ class DFSWalker {
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
yield w.relPath;
yield fixupFunc(w.relPath);
}
} else {
yield w.relPath;
yield fixupFunc(w.relPath);
}
}
}
@ -104,14 +109,7 @@ class DFSWalker {
if (ignoreFilesInDir.length === 0) {
return parentIgnore;
}
const patterns = ignoreFilesInDir
.map((c) => {
return c
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => !/^#|^$/.test(l));
})
.flat();
const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat();
return ignore().add(parentIgnore).add(patterns);
}
@ -153,6 +151,27 @@ class DFSWalker {
private entryIsSymlink(entry: Entry) {
return entry[1] === (64 as FileType.SymbolicLink);
}
// returns a function which will optionally prefix a root path and fixup the paths for the appropriate OS filesystem (i.e. windows)
// the reason to construct this function once is to avoid the need to call ide.pathSep() multiple times
private async newPathFixupFunc(
rootPath: string,
ide: IDE,
): Promise<(relPath: string) => string> {
const pathSep = await ide.pathSep();
const prefix = rootPath === "" ? "" : rootPath + pathSep;
if (pathSep === "/") {
if (rootPath === "") {
// return a no-op function in this case to avoid unnecessary string concatentation
return (relPath: string) => relPath;
}
return (relPath: string) => prefix + relPath;
}
// this serves to 'fix-up' the path on Windows
return (relPath: string) => {
return prefix + relPath.split("/").join(pathSep);
};
}
}
const defaultOptions: WalkerOptions = {
@ -165,18 +184,18 @@ export async function walkDir(
ide: IDE,
_options?: WalkerOptions,
): Promise<string[]> {
let entries: string[] = [];
const options = { ...defaultOptions, ..._options };
const dfsWalker = new DFSWalker(path, ide, options);
let relativePaths: string[] = [];
for await (const e of dfsWalker.walk()) {
relativePaths.push(e);
let paths: string[] = [];
for await (const p of walkDirAsync(path, ide, _options)) {
paths.push(p);
}
const pathSep = await ide.pathSep();
const prefix = options.returnRelativePaths ? "" : path + pathSep;
if (pathSep === "/") {
return relativePaths.map((p) => prefix + p);
}
return relativePaths.map((p) => prefix + p.split("/").join(pathSep));
return paths;
}
export async function* walkDirAsync(
path: string,
ide: IDE,
_options?: WalkerOptions,
): AsyncGenerator<string> {
const options = { ...defaultOptions, ..._options };
yield* new DFSWalker(path, ide, options).walk();
}

View file

@ -1,5 +1,9 @@
import fs from "fs";
import path from "path";
export default async function () {
process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true });
}
}

View file

@ -5,22 +5,23 @@ import * as path from "path";
export interface AsyncEncoder {
encode(text: string): Promise<number[]>;
decode(tokens: number[]): string;
decode(tokens: number[]): Promise<string>;
close(): Promise<void>;
}
export class LlamaAsyncEncoder implements AsyncEncoder {
private workerPool: workerpool.Pool;
constructor() {
this.workerPool = workerpool.pool(path.join(__dirname, "/llamaTokenizerWorkerPool.mjs"));
this.workerPool = workerpool.pool(workerCodeFilePath("llamaTokenizerWorkerPool.mjs"));
}
async encode(text: string): Promise<number[]> {
return this.workerPool.exec("encode", [text]);
}
decode(tokens: number[]): string {
return llamaTokenizer.decode(tokens);
async decode(tokens: number[]): Promise<string> {
return this.workerPool.exec("decode", [tokens]);
}
// TODO: this should be called somewhere before exit or potentially with a shutdown hook
@ -31,17 +32,30 @@ export class LlamaAsyncEncoder implements AsyncEncoder {
// this class does not yet do anything asynchronous
export class GPTAsyncEncoder implements AsyncEncoder {
private tiktokenEncoding: Tiktoken;
private workerPool: workerpool.Pool;
constructor() {
this.tiktokenEncoding = _encodingForModel("gpt-4");
this.workerPool = workerpool.pool(workerCodeFilePath("tiktokenWorkerPool.mjs"));
}
async encode(text: string): Promise<number[]> {
return this.tiktokenEncoding.encode(text, "all", []);
return this.workerPool.exec("encode", [text]);
}
decode(tokens: number[]): string {
return this.tiktokenEncoding.decode(tokens);
async decode(tokens: number[]): Promise<string> {
return this.workerPool.exec("decode", [tokens]);
}
// TODO: this should be called somewhere before exit or potentially with a shutdown hook
public async close(): Promise<void> {
await this.workerPool.terminate();
}
}
function workerCodeFilePath(workerFileName: string): string {
if (process.env.NODE_ENV === "test") {
// `cross-env` seems to make it so __dirname is the root of the project and not the directory containing this file
return path.join(__dirname, "llm", workerFileName);
}
return path.join(__dirname, workerFileName);
}

View file

@ -42,6 +42,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"msty",
"anthropic",
"bedrock",
"sagemaker",
"continue-proxy",
"mistral",
];
@ -54,6 +55,7 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
"msty",
"anthropic",
"bedrock",
"sagemaker",
"continue-proxy",
];
@ -97,6 +99,7 @@ function modelSupportsImages(
const PARALLEL_PROVIDERS: ModelProvider[] = [
"anthropic",
"bedrock",
"sagemaker",
"deepinfra",
"gemini",
"huggingface-inference-api",

View file

@ -29,14 +29,14 @@ const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
const TOKEN_BUFFER_FOR_SAFETY = 350;
const PROXY_URL = "http://localhost:65433";
const MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
export {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_CHUNK_SIZE,
DEFAULT_MAX_TOKENS,
MAX_CHUNK_SIZE,
PROXY_URL,
TOKEN_BUFFER_FOR_SAFETY,
};

View file

@ -38,8 +38,8 @@ import {
countTokens,
pruneRawPromptFromTop,
} from "./countTokens.js";
import CompletionOptionsForModels from "./templates/options.js";
import { stripImages } from "./images.js";
import CompletionOptionsForModels from "./templates/options.js";
export abstract class BaseLLM implements ILLM {
static providerName: ModelProvider;
@ -54,7 +54,12 @@ export abstract class BaseLLM implements ILLM {
}
supportsImages(): boolean {
return modelSupportsImages(this.providerName, this.model, this.title, this.capabilities);
return modelSupportsImages(
this.providerName,
this.model,
this.title,
this.capabilities,
);
}
supportsCompletions(): boolean {
@ -95,7 +100,7 @@ export abstract class BaseLLM implements ILLM {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
capabilities?: ModelCapability
capabilities?: ModelCapability;
engine?: string;
apiVersion?: string;
@ -109,11 +114,11 @@ export abstract class BaseLLM implements ILLM {
watsonxUrl?: string;
watsonxApiKey?: string;
watsonxZenApiKeyBase64?:string = "YOUR_WATSONX_ZENAPIKEY" // Required if using watsonx software with ZenApiKey auth
watsonxUsername?:string;
watsonxPassword?:string;
watsonxZenApiKeyBase64?: string = "YOUR_WATSONX_ZENAPIKEY"; // Required if using watsonx software with ZenApiKey auth
watsonxUsername?: string;
watsonxPassword?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
private _llmOptions: LLMOptions;
@ -172,6 +177,7 @@ export abstract class BaseLLM implements ILLM {
this.watsonxProjectId = options.watsonxProjectId;
this.watsonxUsername = options.watsonxUsername;
this.watsonxPassword = options.watsonxPassword;
this.watsonxStopToken = options.watsonxStopToken;
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;
@ -465,7 +471,12 @@ ${prompt}`;
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
return { prompt, completion, completionOptions };
return {
modelTitle: this.title ?? completionOptions.model,
prompt,
completion,
completionOptions,
};
}
async complete(_prompt: string, options: LLMFullCompletionOptions = {}) {
@ -562,6 +573,7 @@ ${prompt}`;
}
return {
modelTitle: this.title ?? completionOptions.model,
prompt,
completion,
completionOptions,

View file

@ -5,6 +5,11 @@ function encode(segment) {
return llamaTokenizer.encode(segment);
}
function decode(tokens) {
return llamaTokenizer.decode(tokens);
}
workerpool.worker({
decode,
encode,
});

View file

@ -89,10 +89,12 @@ class Bedrock extends BaseLLM {
}
private _convertMessages(messages: ChatMessage[]): any[] {
return messages.map((message) => ({
role: message.role,
content: this._convertMessageContent(message.content),
}));
return messages
.filter((message) => message.role !== "system")
.map((message) => ({
role: message.role,
content: this._convertMessageContent(message.content),
}));
}
private _convertMessageContent(messageContent: MessageContent): any[] {

View file

@ -104,13 +104,13 @@ class OpenAI extends BaseLLM {
this.maxStopWords !== undefined
? options.stop?.slice(0, this.maxStopWords)
: url.host === "api.deepseek.com"
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
};
return finalOptions;
@ -139,7 +139,7 @@ class OpenAI extends BaseLLM {
return completion;
}
private _getEndpoint(
protected _getEndpoint(
endpoint: "chat/completions" | "completions" | "models",
) {
if (this.apiType === "azure") {

205
core/llm/llms/SageMaker.ts Normal file
View file

@ -0,0 +1,205 @@
import {
InvokeEndpointWithResponseStreamCommand,
SageMakerRuntimeClient
} from "@aws-sdk/client-sagemaker-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
// @ts-ignore
import jinja from "jinja-js";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider
} from "../../index.js";
import { BaseLLM } from "../index.js";
class SageMaker extends BaseLLM {
private static PROFILE_NAME: string = "sagemaker";
static providerName: ModelProvider = "sagemaker";
static defaultOptions: Partial<LLMOptions> = {
region: "us-west-2",
contextLength: 200_000,
};
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`;
}
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const credentials = await this._getCredentials();
const client = new SageMakerRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const toolkit = new CompletionAPIToolkit(this);
const command = toolkit.generateCommand([], prompt, options);
const response = await client.send(command);
if (response.Body) {
let buffer = "";
for await (const rawValue of response.Body) {
const binaryChunk = rawValue.PayloadPart?.Bytes;
let value = new TextDecoder().decode(binaryChunk);
buffer += value;
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
const data = JSON.parse(line.replace(/^data:/, ''));
if ("choices" in data) {
yield data.choices[0].delta.content;
}
else if ("token" in data) {
yield data.token.text;
}
buffer = buffer.slice(position + 1);
}
}
}
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const client = new SageMakerRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const toolkit = new MessageAPIToolkit(this);
const command = toolkit.generateCommand(messages, "", options);
const response = await client.send(command);
if (response.Body) {
let buffer = "";
for await (const rawValue of response.Body) {
const binaryChunk = rawValue.PayloadPart?.Bytes;
let value = new TextDecoder().decode(binaryChunk);
buffer += value;
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
const data = JSON.parse(line.replace(/^data:/, ''));
if ("choices" in data) {
yield { role: "assistant", content: data.choices[0].delta.content };
}
else if ("token" in data) {
yield { role: "assistant", content: data.token.text };
}
buffer = buffer.slice(position + 1);
}
}
}
}
private async _getCredentials() {
try {
return await fromIni({
profile: SageMaker.PROFILE_NAME,
})();
} catch (e) {
console.warn(
`AWS profile with name ${SageMaker.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
}
interface SageMakerModelToolkit {
generateCommand(
messages: ChatMessage[],
prompt: string,
options: CompletionOptions,
): InvokeEndpointWithResponseStreamCommand;
}
class MessageAPIToolkit implements SageMakerModelToolkit {
constructor(private sagemaker: SageMaker) { }
generateCommand(
messages: ChatMessage[],
prompt: string,
options: CompletionOptions,
): InvokeEndpointWithResponseStreamCommand {
if ("chat_template" in this.sagemaker.completionOptions) {
// for some model you can apply chat_template to the model
let prompt = jinja.compile(this.sagemaker.completionOptions.chat_template).render(
{ messages: messages, add_generation_prompt: true },
{ autoEscape: false }
)
const payload = {
inputs: prompt,
parameters: this.sagemaker.completionOptions,
stream: true,
};
return new InvokeEndpointWithResponseStreamCommand({
EndpointName: options.model,
Body: new TextEncoder().encode(JSON.stringify(payload)),
ContentType: "application/json",
CustomAttributes: "accept_eula=false",
});
}
else {
const payload = {
messages: messages,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
stop: options.stop,
frequencyPenalty: options.frequencyPenalty,
presencePenalty: options.presencePenalty,
stream: true,
};
return new InvokeEndpointWithResponseStreamCommand({
EndpointName: options.model,
Body: new TextEncoder().encode(JSON.stringify(payload)),
ContentType: "application/json",
CustomAttributes: "accept_eula=false",
});
}
}
}
class CompletionAPIToolkit implements SageMakerModelToolkit {
constructor(private sagemaker: SageMaker) { }
generateCommand(
messages: ChatMessage[],
prompt: string,
options: CompletionOptions,
): InvokeEndpointWithResponseStreamCommand {
const payload = {
inputs: prompt,
parameters: this.sagemaker.completionOptions,
stream: true,
};
return new InvokeEndpointWithResponseStreamCommand({
EndpointName: options.model,
Body: new TextEncoder().encode(JSON.stringify(payload)),
ContentType: "application/json",
CustomAttributes: "accept_eula=false",
});
}
}
export default SageMaker;

30
core/llm/llms/Vllm.ts Normal file
View file

@ -0,0 +1,30 @@
import { LLMOptions, ModelProvider } from "../../index.js";
import OpenAI from "./OpenAI.js";
class Vllm extends OpenAI {
constructor(options: LLMOptions) {
super(options);
this._setupCompletionOptions();
}
private _setupCompletionOptions() {
this.fetch(this._getEndpoint("models"), {
method: "GET",
headers: this._getHeaders(),
}).then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling vLLM /models endpoint: ",
await response.text(),
);
return;
}
const json = await response.json();
const data = json.data;
this.model = data.id;
this.contextLength = Number.parseInt(data.max_model_len);
});
}
}
export default Vllm;

View file

@ -175,6 +175,8 @@ class WatsonX extends BaseLLM {
if (watsonxConfig.accessToken.token === undefined) {
throw new Error(`Something went wrong. Check your credentials, please.`);
}
const stopToken = this.watsonxStopToken ?? (options.model.includes("granite") ? "<|im_end|>" : undefined);
var streamResponse = await fetch(
`${this.watsonxUrl}/ml/v1/text/generation_stream?version=2023-05-29`,
{
@ -189,7 +191,8 @@ class WatsonX extends BaseLLM {
decoding_method: "greedy",
max_new_tokens: options.maxTokens ?? 1024,
min_new_tokens: 1,
stop_sequences: [],
stop_sequences: stopToken ? [stopToken] : [],
include_stop_sequence: false,
repetition_penalty: 1,
},
model_id: options.model,
@ -231,12 +234,10 @@ class WatsonX extends BaseLLM {
generatedChunk += result.generated_text || "";
});
} catch (e) {
throw e;
console.error(`Error parsing JSON string: ${dataStr}`, e);
}
}
});
generatedChunk = generatedChunk.replaceAll("<|im_end|>", " ");
generatedChunk = generatedChunk.replaceAll("<|im_start|> ", "\n");
yield {
role: "assistant",
content: generatedChunk,

View file

@ -1,105 +1,40 @@
import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
import {
BaseCompletionOptions,
IdeSettings,
ILLM,
LLMOptions,
ModelDescription,
} from "../../index.js";
import { DEFAULT_MAX_TOKENS } from "../constants.js";
import { BaseLLM } from "../index.js";
import Anthropic from "./Anthropic.js";
import Azure from "./Azure.js";
import Bedrock from "./Bedrock.js";
import Cloudflare from "./Cloudflare.js";
import Cohere from "./Cohere.js";
import DeepInfra from "./DeepInfra.js";
import Deepseek from "./Deepseek.js";
import Fireworks from "./Fireworks.js";
import Flowise from "./Flowise.js";
import FreeTrial from "./FreeTrial.js";
import Gemini from "./Gemini.js";
import Groq from "./Groq.js";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI.js";
import HuggingFaceTGI from "./HuggingFaceTGI.js";
import LMStudio from "./LMStudio.js";
import LlamaCpp from "./LlamaCpp.js";
import Llamafile from "./Llamafile.js";
import Mistral from "./Mistral.js";
import Msty from "./Msty.js";
import Ollama from "./Ollama.js";
import OpenAI from "./OpenAI.js";
import Replicate from "./Replicate.js";
import TextGenWebUI from "./TextGenWebUI.js";
import Together from "./Together.js";
import WatsonX from "./WatsonX.js";
import ContinueProxy from "./stubs/ContinueProxy.js";
function convertToLetter(num: number): string {
let result = "";
while (num > 0) {
const remainder = (num - 1) % 26;
result = String.fromCharCode(97 + remainder) + result;
num = Math.floor((num - 1) / 26);
}
return result;
}
const getHandlebarsVars = (
value: string,
): [string, { [key: string]: string }] => {
const ast = Handlebars.parse(value);
const keysToFilepath: { [key: string]: string } = {};
let keyIndex = 1;
for (const i in ast.body) {
if (ast.body[i].type === "MustacheStatement") {
const letter = convertToLetter(keyIndex);
keysToFilepath[letter] = (ast.body[i] as any).path.original;
value = value.replace(
new RegExp(`{{\\s*${(ast.body[i] as any).path.original}\\s*}}`),
`{{${letter}}}`,
);
keyIndex++;
}
}
return [value, keysToFilepath];
};
export async function renderTemplatedString(
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: any,
helpers?: [string, Handlebars.HelperDelegate][],
): Promise<string> {
const promises: { [key: string]: Promise<string> } = {};
if (helpers) {
for (const [name, helper] of helpers) {
Handlebars.registerHelper(name, (...args) => {
const id = uuidv4();
promises[id] = helper(...args);
return `__${id}__`;
});
}
}
const [newTemplate, vars] = getHandlebarsVars(template);
const data: any = { ...inputData };
for (const key in vars) {
const fileContents = await readFile(vars[key]);
data[key] = fileContents || (inputData[vars[key]] ?? vars[key]);
}
const templateFn = Handlebars.compile(newTemplate);
let final = templateFn(data);
await Promise.all(Object.values(promises));
for (const id in promises) {
final = final.replace(`__${id}__`, await promises[id]);
}
return final;
}
} from "../..";
import { renderTemplatedString } from "../../promptFiles/renderTemplatedString";
import { DEFAULT_MAX_TOKENS } from "../constants";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Azure from "./Azure";
import Bedrock from "./Bedrock";
import Cloudflare from "./Cloudflare";
import Cohere from "./Cohere";
import DeepInfra from "./DeepInfra";
import Deepseek from "./Deepseek";
import Fireworks from "./Fireworks";
import Flowise from "./Flowise";
import FreeTrial from "./FreeTrial";
import Gemini from "./Gemini";
import Groq from "./Groq";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
import HuggingFaceTGI from "./HuggingFaceTGI";
import LMStudio from "./LMStudio";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import Mistral from "./Mistral";
import Msty from "./Msty";
import Ollama from "./Ollama";
import OpenAI from "./OpenAI";
import Replicate from "./Replicate";
import SageMaker from "./SageMaker";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import WatsonX from "./WatsonX";
import ContinueProxy from "./stubs/ContinueProxy";
const LLMs = [
Anthropic,
@ -118,6 +53,7 @@ const LLMs = [
LMStudio,
Mistral,
Bedrock,
SageMaker,
DeepInfra,
Flowise,
Groq,

View file

@ -0,0 +1,17 @@
import workerpool from "workerpool";
import { encodingForModel as _encodingForModel } from "js-tiktoken";
const tiktokenEncoding = _encodingForModel("gpt-4");
function encode(text) {
return tiktokenEncoding.encode(text, "all", []);
}
function decode(tokens) {
return tiktokenEncoding.decode(tokens);
}
workerpool.worker({
decode,
encode,
});

394
core/package-lock.json generated
View file

@ -10,6 +10,7 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
@ -32,6 +33,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
@ -377,6 +379,350 @@
"node": ">=16.0.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime": {
"version": "3.624.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/client-sagemaker-runtime/-/client-sagemaker-runtime-3.624.0.tgz",
"integrity": "sha512-Af97WcvcB4uDV9A+ADmIXd/UCJn3qQ1lKdaWEbYAHN3FeuvjAZwjqjCiQsXfM5Yq9vg9SRmURSY1gW+HPTgHYg==",
"dependencies": {
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
"@aws-sdk/client-sso-oidc": "3.624.0",
"@aws-sdk/client-sts": "3.624.0",
"@aws-sdk/core": "3.624.0",
"@aws-sdk/credential-provider-node": "3.624.0",
"@aws-sdk/middleware-host-header": "3.620.0",
"@aws-sdk/middleware-logger": "3.609.0",
"@aws-sdk/middleware-recursion-detection": "3.620.0",
"@aws-sdk/middleware-user-agent": "3.620.0",
"@aws-sdk/region-config-resolver": "3.614.0",
"@aws-sdk/types": "3.609.0",
"@aws-sdk/util-endpoints": "3.614.0",
"@aws-sdk/util-user-agent-browser": "3.609.0",
"@aws-sdk/util-user-agent-node": "3.614.0",
"@smithy/config-resolver": "^3.0.5",
"@smithy/core": "^2.3.2",
"@smithy/eventstream-serde-browser": "^3.0.5",
"@smithy/eventstream-serde-config-resolver": "^3.0.3",
"@smithy/eventstream-serde-node": "^3.0.4",
"@smithy/fetch-http-handler": "^3.2.4",
"@smithy/hash-node": "^3.0.3",
"@smithy/invalid-dependency": "^3.0.3",
"@smithy/middleware-content-length": "^3.0.5",
"@smithy/middleware-endpoint": "^3.1.0",
"@smithy/middleware-retry": "^3.0.14",
"@smithy/middleware-serde": "^3.0.3",
"@smithy/middleware-stack": "^3.0.3",
"@smithy/node-config-provider": "^3.1.4",
"@smithy/node-http-handler": "^3.1.4",
"@smithy/protocol-http": "^4.1.0",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"@smithy/url-parser": "^3.0.3",
"@smithy/util-base64": "^3.0.0",
"@smithy/util-body-length-browser": "^3.0.0",
"@smithy/util-body-length-node": "^3.0.0",
"@smithy/util-defaults-mode-browser": "^3.0.14",
"@smithy/util-defaults-mode-node": "^3.0.14",
"@smithy/util-endpoints": "^2.0.5",
"@smithy/util-middleware": "^3.0.3",
"@smithy/util-retry": "^3.0.3",
"@smithy/util-stream": "^3.1.3",
"@smithy/util-utf8": "^3.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/client-sso": {
"version": "3.624.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.624.0.tgz",
"integrity": "sha512-EX6EF+rJzMPC5dcdsu40xSi2To7GSvdGQNIpe97pD9WvZwM9tRNQnNM4T6HA4gjV1L6Jwk8rBlG/CnveXtLEMw==",
"dependencies": {
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
"@aws-sdk/core": "3.624.0",
"@aws-sdk/middleware-host-header": "3.620.0",
"@aws-sdk/middleware-logger": "3.609.0",
"@aws-sdk/middleware-recursion-detection": "3.620.0",
"@aws-sdk/middleware-user-agent": "3.620.0",
"@aws-sdk/region-config-resolver": "3.614.0",
"@aws-sdk/types": "3.609.0",
"@aws-sdk/util-endpoints": "3.614.0",
"@aws-sdk/util-user-agent-browser": "3.609.0",
"@aws-sdk/util-user-agent-node": "3.614.0",
"@smithy/config-resolver": "^3.0.5",
"@smithy/core": "^2.3.2",
"@smithy/fetch-http-handler": "^3.2.4",
"@smithy/hash-node": "^3.0.3",
"@smithy/invalid-dependency": "^3.0.3",
"@smithy/middleware-content-length": "^3.0.5",
"@smithy/middleware-endpoint": "^3.1.0",
"@smithy/middleware-retry": "^3.0.14",
"@smithy/middleware-serde": "^3.0.3",
"@smithy/middleware-stack": "^3.0.3",
"@smithy/node-config-provider": "^3.1.4",
"@smithy/node-http-handler": "^3.1.4",
"@smithy/protocol-http": "^4.1.0",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"@smithy/url-parser": "^3.0.3",
"@smithy/util-base64": "^3.0.0",
"@smithy/util-body-length-browser": "^3.0.0",
"@smithy/util-body-length-node": "^3.0.0",
"@smithy/util-defaults-mode-browser": "^3.0.14",
"@smithy/util-defaults-mode-node": "^3.0.14",
"@smithy/util-endpoints": "^2.0.5",
"@smithy/util-middleware": "^3.0.3",
"@smithy/util-retry": "^3.0.3",
"@smithy/util-utf8": "^3.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/client-sso-oidc": {
"version": "3.624.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.624.0.tgz",
"integrity": "sha512-Ki2uKYJKKtfHxxZsiMTOvJoVRP6b2pZ1u3rcUb2m/nVgBPUfLdl8ZkGpqE29I+t5/QaS/sEdbn6cgMUZwl+3Dg==",
"dependencies": {
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
"@aws-sdk/core": "3.624.0",
"@aws-sdk/credential-provider-node": "3.624.0",
"@aws-sdk/middleware-host-header": "3.620.0",
"@aws-sdk/middleware-logger": "3.609.0",
"@aws-sdk/middleware-recursion-detection": "3.620.0",
"@aws-sdk/middleware-user-agent": "3.620.0",
"@aws-sdk/region-config-resolver": "3.614.0",
"@aws-sdk/types": "3.609.0",
"@aws-sdk/util-endpoints": "3.614.0",
"@aws-sdk/util-user-agent-browser": "3.609.0",
"@aws-sdk/util-user-agent-node": "3.614.0",
"@smithy/config-resolver": "^3.0.5",
"@smithy/core": "^2.3.2",
"@smithy/fetch-http-handler": "^3.2.4",
"@smithy/hash-node": "^3.0.3",
"@smithy/invalid-dependency": "^3.0.3",
"@smithy/middleware-content-length": "^3.0.5",
"@smithy/middleware-endpoint": "^3.1.0",
"@smithy/middleware-retry": "^3.0.14",
"@smithy/middleware-serde": "^3.0.3",
"@smithy/middleware-stack": "^3.0.3",
"@smithy/node-config-provider": "^3.1.4",
"@smithy/node-http-handler": "^3.1.4",
"@smithy/protocol-http": "^4.1.0",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"@smithy/url-parser": "^3.0.3",
"@smithy/util-base64": "^3.0.0",
"@smithy/util-body-length-browser": "^3.0.0",
"@smithy/util-body-length-node": "^3.0.0",
"@smithy/util-defaults-mode-browser": "^3.0.14",
"@smithy/util-defaults-mode-node": "^3.0.14",
"@smithy/util-endpoints": "^2.0.5",
"@smithy/util-middleware": "^3.0.3",
"@smithy/util-retry": "^3.0.3",
"@smithy/util-utf8": "^3.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
},
"peerDependencies": {
"@aws-sdk/client-sts": "^3.624.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/client-sts": {
"version": "3.624.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.624.0.tgz",
"integrity": "sha512-k36fLZCb2nfoV/DKK3jbRgO/Yf7/R80pgYfMiotkGjnZwDmRvNN08z4l06L9C+CieazzkgRxNUzyppsYcYsQaw==",
"dependencies": {
"@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0",
"@aws-sdk/client-sso-oidc": "3.624.0",
"@aws-sdk/core": "3.624.0",
"@aws-sdk/credential-provider-node": "3.624.0",
"@aws-sdk/middleware-host-header": "3.620.0",
"@aws-sdk/middleware-logger": "3.609.0",
"@aws-sdk/middleware-recursion-detection": "3.620.0",
"@aws-sdk/middleware-user-agent": "3.620.0",
"@aws-sdk/region-config-resolver": "3.614.0",
"@aws-sdk/types": "3.609.0",
"@aws-sdk/util-endpoints": "3.614.0",
"@aws-sdk/util-user-agent-browser": "3.609.0",
"@aws-sdk/util-user-agent-node": "3.614.0",
"@smithy/config-resolver": "^3.0.5",
"@smithy/core": "^2.3.2",
"@smithy/fetch-http-handler": "^3.2.4",
"@smithy/hash-node": "^3.0.3",
"@smithy/invalid-dependency": "^3.0.3",
"@smithy/middleware-content-length": "^3.0.5",
"@smithy/middleware-endpoint": "^3.1.0",
"@smithy/middleware-retry": "^3.0.14",
"@smithy/middleware-serde": "^3.0.3",
"@smithy/middleware-stack": "^3.0.3",
"@smithy/node-config-provider": "^3.1.4",
"@smithy/node-http-handler": "^3.1.4",
"@smithy/protocol-http": "^4.1.0",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"@smithy/url-parser": "^3.0.3",
"@smithy/util-base64": "^3.0.0",
"@smithy/util-body-length-browser": "^3.0.0",
"@smithy/util-body-length-node": "^3.0.0",
"@smithy/util-defaults-mode-browser": "^3.0.14",
"@smithy/util-defaults-mode-node": "^3.0.14",
"@smithy/util-endpoints": "^2.0.5",
"@smithy/util-middleware": "^3.0.3",
"@smithy/util-retry": "^3.0.3",
"@smithy/util-utf8": "^3.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/core": {
"version": "3.624.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.624.0.tgz",
"integrity": "sha512-WyFmPbhRIvtWi7hBp8uSFy+iPpj8ccNV/eX86hwF4irMjfc/FtsGVIAeBXxXM/vGCjkdfEzOnl+tJ2XACD4OXg==",
"dependencies": {
"@smithy/core": "^2.3.2",
"@smithy/node-config-provider": "^3.1.4",
"@smithy/protocol-http": "^4.1.0",
"@smithy/signature-v4": "^4.1.0",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"@smithy/util-middleware": "^3.0.3",
"fast-xml-parser": "4.4.1",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/credential-provider-http": {
"version": "3.622.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.622.0.tgz",
"integrity": "sha512-VUHbr24Oll1RK3WR8XLUugLpgK9ZuxEm/NVeVqyFts1Ck9gsKpRg1x4eH7L7tW3SJ4TDEQNMbD7/7J+eoL2svg==",
"dependencies": {
"@aws-sdk/types": "3.609.0",
"@smithy/fetch-http-handler": "^3.2.4",
"@smithy/node-http-handler": "^3.1.4",
"@smithy/property-provider": "^3.1.3",
"@smithy/protocol-http": "^4.1.0",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"@smithy/util-stream": "^3.1.3",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/credential-provider-ini": {
"version": "3.624.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.624.0.tgz",
"integrity": "sha512-mMoNIy7MO2WTBbdqMyLpbt6SZpthE6e0GkRYpsd0yozPt0RZopcBhEh+HG1U9Y1PVODo+jcMk353vAi61CfnhQ==",
"dependencies": {
"@aws-sdk/credential-provider-env": "3.620.1",
"@aws-sdk/credential-provider-http": "3.622.0",
"@aws-sdk/credential-provider-process": "3.620.1",
"@aws-sdk/credential-provider-sso": "3.624.0",
"@aws-sdk/credential-provider-web-identity": "3.621.0",
"@aws-sdk/types": "3.609.0",
"@smithy/credential-provider-imds": "^3.2.0",
"@smithy/property-provider": "^3.1.3",
"@smithy/shared-ini-file-loader": "^3.1.4",
"@smithy/types": "^3.3.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
},
"peerDependencies": {
"@aws-sdk/client-sts": "^3.624.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/credential-provider-node": {
"version": "3.624.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.624.0.tgz",
"integrity": "sha512-vYyGK7oNpd81BdbH5IlmQ6zfaQqU+rPwsKTDDBeLRjshtrGXOEpfoahVpG9PX0ibu32IOWp4ZyXBNyVrnvcMOw==",
"dependencies": {
"@aws-sdk/credential-provider-env": "3.620.1",
"@aws-sdk/credential-provider-http": "3.622.0",
"@aws-sdk/credential-provider-ini": "3.624.0",
"@aws-sdk/credential-provider-process": "3.620.1",
"@aws-sdk/credential-provider-sso": "3.624.0",
"@aws-sdk/credential-provider-web-identity": "3.621.0",
"@aws-sdk/types": "3.609.0",
"@smithy/credential-provider-imds": "^3.2.0",
"@smithy/property-provider": "^3.1.3",
"@smithy/shared-ini-file-loader": "^3.1.4",
"@smithy/types": "^3.3.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/credential-provider-sso": {
"version": "3.624.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.624.0.tgz",
"integrity": "sha512-A02bayIjU9APEPKr3HudrFHEx0WfghoSPsPopckDkW7VBqO4wizzcxr75Q9A3vNX+cwg0wCN6UitTNe6pVlRaQ==",
"dependencies": {
"@aws-sdk/client-sso": "3.624.0",
"@aws-sdk/token-providers": "3.614.0",
"@aws-sdk/types": "3.609.0",
"@smithy/property-provider": "^3.1.3",
"@smithy/shared-ini-file-loader": "^3.1.4",
"@smithy/types": "^3.3.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/@aws-sdk/credential-provider-web-identity": {
"version": "3.621.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.621.0.tgz",
"integrity": "sha512-w7ASSyfNvcx7+bYGep3VBgC3K6vEdLmlpjT7nSIHxxQf+WSdvy+HynwJosrpZax0sK5q0D1Jpn/5q+r5lwwW6w==",
"dependencies": {
"@aws-sdk/types": "3.609.0",
"@smithy/property-provider": "^3.1.3",
"@smithy/types": "^3.3.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=16.0.0"
},
"peerDependencies": {
"@aws-sdk/client-sts": "^3.621.0"
}
},
"node_modules/@aws-sdk/client-sagemaker-runtime/node_modules/fast-xml-parser": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz",
"integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
},
{
"type": "paypal",
"url": "https://paypal.me/naturalintelligence"
}
],
"dependencies": {
"strnum": "^1.0.5"
},
"bin": {
"fxparser": "src/cli/cli.js"
}
},
"node_modules/@aws-sdk/client-sso": {
"version": "3.620.1",
"resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.620.1.tgz",
@ -3724,15 +4070,15 @@
}
},
"node_modules/@smithy/core": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@smithy/core/-/core-2.3.1.tgz",
"integrity": "sha512-BC7VMXx/1BCmRPCVzzn4HGWAtsrb7/0758EtwOGFJQrlSwJBEjCcDLNZLFoL/68JexYa2s+KmgL/UfmXdG6v1w==",
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/@smithy/core/-/core-2.3.2.tgz",
"integrity": "sha512-in5wwt6chDBcUv1Lw1+QzZxN9fBffi+qOixfb65yK4sDuKG7zAUO9HAFqmVzsZM3N+3tTyvZjtnDXePpvp007Q==",
"dependencies": {
"@smithy/middleware-endpoint": "^3.1.0",
"@smithy/middleware-retry": "^3.0.13",
"@smithy/middleware-retry": "^3.0.14",
"@smithy/middleware-serde": "^3.0.3",
"@smithy/protocol-http": "^4.1.0",
"@smithy/smithy-client": "^3.1.11",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"@smithy/util-middleware": "^3.0.3",
"tslib": "^2.6.2"
@ -3895,14 +4241,14 @@
}
},
"node_modules/@smithy/middleware-retry": {
"version": "3.0.13",
"resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-3.0.13.tgz",
"integrity": "sha512-zvCLfaRYCaUmjbF2yxShGZdolSHft7NNCTA28HVN9hKcEbOH+g5irr1X9s+in8EpambclGnevZY4A3lYpvDCFw==",
"version": "3.0.14",
"resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-3.0.14.tgz",
"integrity": "sha512-7ZaWZJOjUxa5hgmuMspyt8v/zVsh0GXYuF7OvCmdcbVa/xbnKQoYC+uYKunAqRGTkxjOyuOCw9rmFUFOqqC0eQ==",
"dependencies": {
"@smithy/node-config-provider": "^3.1.4",
"@smithy/protocol-http": "^4.1.0",
"@smithy/service-error-classification": "^3.0.3",
"@smithy/smithy-client": "^3.1.11",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"@smithy/util-middleware": "^3.0.3",
"@smithy/util-retry": "^3.0.3",
@ -4057,9 +4403,9 @@
}
},
"node_modules/@smithy/smithy-client": {
"version": "3.1.11",
"resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-3.1.11.tgz",
"integrity": "sha512-l0BpyYkciNyMaS+PnFFz4aO5sBcXvGLoJd7mX9xrMBIm2nIQBVvYgp2ZpPDMzwjKCavsXu06iuCm0F6ZJZc6yQ==",
"version": "3.1.12",
"resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-3.1.12.tgz",
"integrity": "sha512-wtm8JtsycthkHy1YA4zjIh2thJgIQ9vGkoR639DBx5lLlLNU0v4GARpQZkr2WjXue74nZ7MiTSWfVrLkyD8RkA==",
"dependencies": {
"@smithy/middleware-endpoint": "^3.1.0",
"@smithy/middleware-stack": "^3.0.3",
@ -4149,12 +4495,12 @@
}
},
"node_modules/@smithy/util-defaults-mode-browser": {
"version": "3.0.13",
"resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-3.0.13.tgz",
"integrity": "sha512-ZIRSUsnnMRStOP6OKtW+gCSiVFkwnfQF2xtf32QKAbHR6ACjhbAybDvry+3L5qQYdh3H6+7yD/AiUE45n8mTTw==",
"version": "3.0.14",
"resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-3.0.14.tgz",
"integrity": "sha512-0iwTgKKmAIf+vFLV8fji21Jb2px11ktKVxbX6LIDPAUJyWQqGqBVfwba7xwa1f2FZUoolYQgLvxQEpJycXuQ5w==",
"dependencies": {
"@smithy/property-provider": "^3.1.3",
"@smithy/smithy-client": "^3.1.11",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"bowser": "^2.11.0",
"tslib": "^2.6.2"
@ -4164,15 +4510,15 @@
}
},
"node_modules/@smithy/util-defaults-mode-node": {
"version": "3.0.13",
"resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-3.0.13.tgz",
"integrity": "sha512-voUa8TFJGfD+U12tlNNLCDlXibt9vRdNzRX45Onk/WxZe7TS+hTOZouEZRa7oARGicdgeXvt1A0W45qLGYdy+g==",
"version": "3.0.14",
"resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-3.0.14.tgz",
"integrity": "sha512-e9uQarJKfXApkTMMruIdxHprhcXivH1flYCe8JRDTzkkLx8dA3V5J8GZlST9yfDiRWkJpZJlUXGN9Rc9Ade3OQ==",
"dependencies": {
"@smithy/config-resolver": "^3.0.5",
"@smithy/credential-provider-imds": "^3.2.0",
"@smithy/node-config-provider": "^3.1.4",
"@smithy/property-provider": "^3.1.3",
"@smithy/smithy-client": "^3.1.11",
"@smithy/smithy-client": "^3.1.12",
"@smithy/types": "^3.3.0",
"tslib": "^2.6.2"
},
@ -9458,6 +9804,14 @@
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/jinja-js": {
"version": "0.1.8",
"resolved": "https://registry.npmjs.org/jinja-js/-/jinja-js-0.1.8.tgz",
"integrity": "sha512-1wJNbeZxknEckfqt5VU4oVvphC2qASn9yfAw5BNF0JhRZM5LNPcnQKC6nAiEx8nJh0NhxkjCWjQDOut/zQqUOw==",
"bin": {
"jinjajs": "cli.js"
}
},
"node_modules/js-tiktoken": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.12.tgz",

View file

@ -40,6 +40,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/credential-providers": "^3.620.1",
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",
@ -47,6 +48,7 @@
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@xenova/transformers": "2.14.0",
"jinja-js": "0.1.8",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",

View file

@ -0,0 +1,57 @@
import path from "path";
import { IDE } from "..";
import { DEFAULT_PROMPTS_FOLDER } from "./";
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
# It is used to define and reuse prompts within Continue
# Continue will automatically create a slash command for each prompt in the .prompts folder
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
temperature: 0.0
---
{{{ diff }}}
Give me feedback on the above changes. For each file, you should output a markdown section including the following:
- If you found any problems, an h3 like "❌ <filename>"
- If you didn't find any problems, an h3 like "✅ <filename>"
- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it
- If you didn't find any problems, you don't need to add anything else
Here is an example. The example is surrounded in backticks, but your response should not be:
\`\`\`
### ✅ <Filename1>
### ❌ <Filename2>
<Description>
\`\`\`
You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
- console.logs that have been left after debugging
- repeated code
- algorithmic errors that could fail under edge cases
- something that could be refactored
Make sure to review ALL files that were changed, do not skip any.
`;
export async function createNewPromptFile(
ide: IDE,
promptPath: string | undefined,
): Promise<void> {
const workspaceDirs = await ide.getWorkspaceDirs();
if (workspaceDirs.length === 0) {
throw new Error(
"No workspace directories found. Make sure you've opened a folder in your IDE.",
);
}
const promptFilePath = path.join(
workspaceDirs[0],
promptPath ?? DEFAULT_PROMPTS_FOLDER,
"new-prompt-file.prompt",
);
await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE);
await ide.openFile(promptFilePath);
}

View file

@ -0,0 +1,37 @@
import Handlebars from "handlebars";
export function getContextProviderHelpers(
context: any,
): Array<[string, Handlebars.HelperDelegate]> | undefined {
return context.config.contextProviders?.map((provider: any) => [
provider.description.title,
async (helperContext: any) => {
const items = await provider.getContextItems(helperContext, {
config: context.config,
embeddingsProvider: context.config.embeddingsProvider,
fetch: context.fetch,
fullInput: context.input,
ide: context.ide,
llm: context.llm,
reranker: context.config.reranker,
selectedCode: context.selectedCode,
});
items.forEach((item: any) =>
context.addContextItem(createContextItem(item, provider)),
);
return items.map((item: any) => item.content).join("\n\n");
},
]);
}
function createContextItem(item: any, provider: any) {
return {
...item,
id: {
itemId: item.description,
providerTitle: provider.description.title,
},
};
}

View file

@ -0,0 +1,25 @@
import { IDE } from "..";
import { walkDir } from "../indexing/walkDir";
export async function getPromptFiles(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
const results = paths.map(async (path) => {
const content = await ide.readFile(path); // make a try catch
return { path, content };
});
return Promise.all(results);
} catch (e) {
console.error(e);
return [];
}
}

View file

@ -0,0 +1,114 @@
import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
export function convertToLetter(num: number): string {
let result = "";
while (num > 0) {
const remainder = (num - 1) % 26;
result = String.fromCharCode(97 + remainder) + result;
num = Math.floor((num - 1) / 26);
}
return result;
}
/**
* We replace filepaths with alphabetic characters to handle
* escaping issues.
*/
export const replaceFilepaths = (
value: string,
ctxProviderNames: string[],
): [string, { [key: string]: string }] => {
const ast = Handlebars.parse(value);
const keysToFilepath: { [key: string]: string } = {};
let keyIndex = 1;
for (const i in ast.body) {
const node = ast.body[i] as any;
if (node.type === "MustacheStatement") {
const originalNodeVal = node.path.original;
const isFilepath = !ctxProviderNames.includes(originalNodeVal);
if (isFilepath) {
const letter = convertToLetter(keyIndex);
keysToFilepath[letter] = originalNodeVal;
value = value.replace(
new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
`{{${letter}}}`,
);
keyIndex++;
}
}
}
return [value, keysToFilepath];
};
export function registerHelpers(
helpers: Array<[string, Handlebars.HelperDelegate]>,
): {
[key: string]: Promise<string>;
} {
const promises: { [key: string]: Promise<string> } = {};
for (const [name, helper] of helpers) {
Handlebars.registerHelper(name, (...args) => {
const id = uuidv4();
promises[id] = helper(...args);
return `__${id}__`;
});
}
return promises;
}
export async function prepareTemplateAndData(
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: any,
ctxProviderNames: string[],
): Promise<[string, any]> {
const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames);
const data: any = { ...inputData };
for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) {
data[replacedName] =
inputData[originalCtxProviderName] ?? originalCtxProviderName;
// If it's not a context provider, assume it's a filepath.
if (!ctxProviderNames.includes(originalCtxProviderName)) {
const fileContents = await readFile(vars[replacedName]);
if (fileContents) {
data[replacedName] = fileContents;
}
}
}
return [newTemplate, data];
}
export function compileAndRenderTemplate(template: string, data: any): string {
const templateFn = Handlebars.compile(template);
return templateFn(data);
}
export async function resolveHelperPromises(
renderedString: string,
promises: { [key: string]: Promise<string> },
): Promise<string> {
await Promise.all(Object.values(promises));
for (const id in promises) {
renderedString = renderedString.replace(`__${id}__`, await promises[id]);
}
return renderedString;
}

View file

@ -0,0 +1,8 @@
import { IDE } from "..";
import { getPromptFiles } from "./getPromptFiles";
import { createNewPromptFile } from "./createNewPromptFile";
import { slashCommandFromPromptFile } from "./slashCommandFromPromptFile";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
export { getPromptFiles, createNewPromptFile, slashCommandFromPromptFile };

View file

@ -0,0 +1,30 @@
import {
compileAndRenderTemplate,
prepareTemplateAndData,
registerHelpers,
resolveHelperPromises,
} from "./handlebarUtils";
export async function renderTemplatedString(
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: any,
availableHelpers?: Array<[string, Handlebars.HelperDelegate]>,
): Promise<string> {
const helperPromises = availableHelpers
? registerHelpers(availableHelpers)
: {};
const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
const [newTemplate, data] = await prepareTemplateAndData(
template,
readFile,
inputData,
ctxProviderNames,
);
let renderedString = compileAndRenderTemplate(newTemplate, data);
return resolveHelperPromises(renderedString, helperPromises);
}

View file

@ -0,0 +1,93 @@
import { SlashCommand } from "..";
import { stripImages } from "../llm/images";
import { getContextProviderHelpers } from "./getContextProviderHelpers";
import { renderTemplatedString } from "./renderTemplatedString";
import { updateChatHistory } from "./updateChatHistory";
import * as YAML from "yaml";
import { getBasename } from "../util/index";
export function extractName(preamble: { name?: string }, path: string): string {
return preamble.name ?? getBasename(path).split(".prompt")[0];
}
export function parsePromptFile(path: string, content: string) {
let [preambleRaw, prompt] = content.split("\n---\n");
if (prompt === undefined) {
prompt = preambleRaw;
preambleRaw = "";
}
const preamble = YAML.parse(preambleRaw) ?? {};
const name = extractName(preamble, path);
const description = preamble.description ?? name;
let systemMessage: string | undefined = undefined;
if (prompt.includes("<system>")) {
systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
prompt = prompt.split("</system>")[1].trim();
}
return { name, description, systemMessage, prompt };
}
export function extractUserInput(input: string, commandName: string): string {
if (input.startsWith(`/${commandName}`)) {
return input.slice(commandName.length + 1).trimStart();
}
return input;
}
export async function getDefaultVariables(context: any, userInput: string) {
const currentFilePath = await context.ide.getCurrentFile();
const currentFile = currentFilePath
? await context.ide.readFile(currentFilePath)
: undefined;
return { currentFile, input: userInput };
}
export async function renderPrompt(
prompt: string,
context: any,
userInput: string,
) {
const helpers = getContextProviderHelpers(context);
const inputData = await getDefaultVariables(context, userInput);
return renderTemplatedString(
prompt,
context.ide.readFile.bind(context.ide),
inputData,
helpers,
);
}
export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommand {
const { name, description, systemMessage, prompt } = parsePromptFile(
path,
content,
);
return {
name,
description,
run: async function* (context) {
const userInput = extractUserInput(context.input, name);
const renderedPrompt = await renderPrompt(prompt, context, userInput);
const messages = updateChatHistory(
context.history,
name,
renderedPrompt,
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
},
};
}

View file

@ -0,0 +1,55 @@
export function updateChatHistory(
history: any[],
commandName: string,
renderedPrompt: string,
systemMessage?: string,
) {
const messages = [...history];
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
if (Array.isArray(content)) {
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
messages[i] = updateArrayContent(
messages[i],
commandName,
renderedPrompt,
);
break;
}
} else if (
typeof content === "string" &&
content.startsWith(`/${commandName}`)
) {
messages[i] = { ...messages[i], content: renderedPrompt };
break;
}
}
if (systemMessage) {
messages[0]?.role === "system"
? (messages[0].content = systemMessage)
: messages.unshift({ role: "system", content: systemMessage });
}
return messages;
}
function updateArrayContent(
message: any,
commandName: string,
renderedPrompt: string,
) {
return {
...message,
content: message.content.map((part: any) =>
part.text?.startsWith(`/${commandName}`)
? { ...part, text: renderedPrompt }
: part,
),
};
}

View file

@ -0,0 +1,42 @@
import fs from "node:fs";
import path from "node:path";
import { defaultConfig } from "../../config/default";
import { getConfigTsPath } from "../../util/paths";
import { testConfigHandler } from "../fixtures";
import { TEST_DIR } from "../testUtils/testDir";
describe("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.listProfiles();
expect(profiles.length).toBe(1);
expect(profiles[0].id).toBe("local");
const currentProfile = testConfigHandler.currentProfile;
expect(currentProfile.profileId).toBe("local");
});
test("should load the default config successfully", async () => {
const config = await testConfigHandler.loadConfig();
expect(config.models.length).toBe(defaultConfig.models.length);
});
test.skip("should add a system message from config.ts", async () => {
const configTs = `export function modifyConfig(config: Config): Config {
config.systemMessage = "SYSTEM";
return config;
}`;
fs.writeFileSync(getConfigTsPath(), configTs);
await new Promise((resolve) => setTimeout(resolve, 1000));
const config = await testConfigHandler.reloadConfig();
expect(config.systemMessage).toBe("SYSTEM");
});
test.skip("should acknowledge override from .continuerc.json", async () => {
fs.writeFileSync(
path.join(TEST_DIR, ".continuerc.json"),
JSON.stringify({ systemMessage: "SYSTEM2" }),
);
const config = await testConfigHandler.reloadConfig();
expect(config.systemMessage).toBe("SYSTEM2");
});
});

View file

@ -0,0 +1,64 @@
import fetch from "node-fetch";
import {
ContextProviderExtras,
ContextProviderWithParams,
IContextProvider,
} from "../../..";
import { ConfigHandler } from "../../../config/ConfigHandler";
import { contextProviderClassFromName } from "../../../context/providers";
import { ControlPlaneClient } from "../../../control-plane/client";
import FileSystemIde from "../../../util/filesystem";
import { TEST_DIR } from "../../testUtils/testDir";
const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
{ name: "diff", params: {} },
{ name: "currentFile", params: {} },
{ name: "locals", params: {} },
{ name: "open", params: {} },
{ name: "os", params: {} },
{ name: "problems", params: {} },
{ name: "terminal", params: {} },
{ name: "tree", params: {} },
];
async function getContextProviderExtras(
fullInput: string,
): Promise<ContextProviderExtras> {
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
async (text) => {},
new ControlPlaneClient(Promise.resolve(undefined)),
);
const config = await configHandler.loadConfig();
return {
fullInput,
ide,
config,
embeddingsProvider: config.embeddingsProvider,
fetch: fetch,
llm: config.models[0],
reranker: config.reranker,
selectedCode: [],
};
}
describe("Should successfully run all context providers", () => {
const extrasPromise = getContextProviderExtras("Test");
CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {
test(`should successfully run ${provider.name} context provider`, async () => {
const cls = contextProviderClassFromName(provider.name) as any;
const instance: IContextProvider = new cls(provider.params);
expect(instance.description.title).toBe(provider.name);
const items = await instance.getContextItems("test", await extrasPromise);
expect(Array.isArray(items)).toBe(true);
});
});
});

13
core/test/fixtures.ts Normal file
View file

@ -0,0 +1,13 @@
import { ConfigHandler } from "../config/ConfigHandler";
import { ControlPlaneClient } from "../control-plane/client";
import FileSystemIde from "../util/filesystem";
import { TEST_DIR } from "./testUtils/testDir";
export const testIde = new FileSystemIde(TEST_DIR);
export const ideSettingsPromise = testIde.getIdeSettings();
export const testConfigHandler = new ConfigHandler(
testIde,
ideSettingsPromise,
async (text) => {},
new ControlPlaneClient(Promise.resolve(undefined)),
);

View file

@ -1,178 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ContinueServerClient } from "../../continueServer/stubs/client.js";
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js";
import { LanceDbIndex } from "../../indexing/LanceDbIndex.js";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
import FileSystemIde from "../../util/filesystem.js";
import {
getIndexFolderPath,
getIndexSqlitePath,
getLanceDbPath,
} from "../../util/paths.js";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "../testUtils/testDir.js";
import { jest } from "@jest/globals";
jest.useFakeTimers();
const TEST_TS = `\
function main() {
console.log("Hello, world!");
}
class Foo {
constructor(public bar: string) {}
}
`;
const TEST_PY = `\
def main():
print("Hello, world!")
class Foo:
def __init__(self, bar: str):
self.bar = bar
`;
const TEST_RS = `\
fn main() {
println!("Hello, world!");
}
struct Foo {
bar: String,
}
`;
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe.skip("CodebaseIndexer", () => {
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
async (text) => {},
undefined as any, // TODO
);
const pauseToken = new PauseToken(false);
const continueServerClient = new ContinueServerClient(undefined, undefined);
const codebaseIndexer = new CodebaseIndexer(
configHandler,
ide,
pauseToken,
continueServerClient,
);
const lancedbIndex = new LanceDbIndex(
new TransformersJsEmbeddingsProvider(),
ide.readFile.bind(ide),
continueServerClient,
);
beforeAll(async () => {
setUpTestDir();
});
afterAll(async () => {
tearDownTestDir();
});
test("should index test folder without problem", async () => {
addToTestDir([
["test.ts", TEST_TS],
["py/main.py", TEST_PY],
]);
const abortController = new AbortController();
const abortSignal = abortController.signal;
const updates = [];
for await (const update of codebaseIndexer.refresh(
[TEST_DIR],
abortSignal,
)) {
updates.push(update);
}
expect(updates.length).toBeGreaterThan(0);
});
test("should have created index folder with all necessary files", async () => {
expect(fs.existsSync(getIndexFolderPath())).toBe(true);
expect(fs.existsSync(getIndexSqlitePath())).toBe(true);
expect(fs.existsSync(getLanceDbPath())).toBe(true);
});
test("should be able to query lancedb index", async () => {
const chunks = await lancedbIndex.retrieve(
"What is the main function doing?",
10,
await ide.getTags(lancedbIndex.artifactId),
undefined,
);
expect(chunks.length).toBe(2);
// Check that the main function from both files is returned
expect(chunks.some((chunk) => chunk.filepath.endsWith("test.ts"))).toBe(
true,
);
expect(chunks.some((chunk) => chunk.filepath.endsWith("main.py"))).toBe(
true,
);
});
test("should successfully re-index after adding a file", async () => {
addToTestDir([["main.rs", TEST_RS]]);
const abortController = new AbortController();
const abortSignal = abortController.signal;
const updates = [];
for await (const update of codebaseIndexer.refresh(
[TEST_DIR],
abortSignal,
)) {
updates.push(update);
}
expect(updates.length).toBeGreaterThan(0);
// Check that the new file was indexed
const chunks = await lancedbIndex.retrieve(
"What is the main function doing?",
3,
await ide.getTags(lancedbIndex.artifactId),
undefined,
);
expect(chunks.length).toBe(3);
expect(chunks.some((chunk) => chunk.filepath.endsWith("main.rs"))).toBe(
true,
);
});
test("should successfully re-index after deleting a file", async () => {
fs.rmSync(path.join(TEST_DIR, "main.rs"));
const abortController = new AbortController();
const abortSignal = abortController.signal;
const updates = [];
for await (const update of codebaseIndexer.refresh(
[TEST_DIR],
abortSignal,
)) {
updates.push(update);
}
expect(updates.length).toBeGreaterThan(0);
// Check that the deleted file was removed from the index
const chunks = await lancedbIndex.retrieve(
"What is the main function doing?",
10,
await ide.getTags(lancedbIndex.artifactId),
undefined,
);
expect(chunks.length).toBe(2);
expect(chunks.every((chunk) => !chunk.filepath.endsWith("main.rs"))).toBe(
true,
);
});
});

View file

@ -0,0 +1,209 @@
import { jest } from "@jest/globals";
import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { ContinueServerClient } from "../../continueServer/stubs/client.js";
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "../../indexing/refreshIndex.js";
import { TestCodebaseIndex } from "../../indexing/TestCodebaseIndex.js";
import { CodebaseIndex } from "../../indexing/types.js";
import { walkDir } from "../../indexing/walkDir.js";
import { getIndexSqlitePath } from "../../util/paths.js";
import { testConfigHandler, testIde } from "../fixtures.js";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "../testUtils/testDir.js";
jest.useFakeTimers();
const TEST_TS = `\
function main() {
console.log("Hello, world!");
}
class Foo {
constructor(public bar: string) {}
}
`;
const TEST_PY = `\
def main():
print("Hello, world!")
class Foo:
def __init__(self, bar: str):
self.bar = bar
`;
const TEST_RS = `\
fn main() {
println!("Hello, world!");
}
struct Foo {
bar: String,
}
`;
// A subclass of CodebaseIndexer that adds a new CodebaseIndex
class TestCodebaseIndexer extends CodebaseIndexer {
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
return [new TestCodebaseIndex()];
}
}
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe("CodebaseIndexer", () => {
const pauseToken = new PauseToken(false);
const continueServerClient = new ContinueServerClient(undefined, undefined);
const codebaseIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
pauseToken,
continueServerClient,
);
const testIndex = new TestCodebaseIndex();
beforeAll(async () => {
tearDownTestDir();
setUpTestDir();
});
afterAll(async () => {
tearDownTestDir();
});
async function refreshIndex() {
const abortController = new AbortController();
const abortSignal = abortController.signal;
const updates = [];
for await (const update of codebaseIndexer.refresh(
[TEST_DIR],
abortSignal,
)) {
updates.push(update);
}
return updates;
}
async function getAllIndexedFiles() {
const files = await testIndex.getIndexedFilesForTags(
await testIde.getTags(testIndex.artifactId),
);
return files;
}
async function getIndexPlan() {
const workspaceFiles = await walkDir(TEST_DIR, testIde);
const [tag] = await testIde.getTags(testIndex.artifactId);
const stats = await testIde.getLastModified(workspaceFiles);
const [results, lastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => testIde.readFile(filepath),
undefined,
);
return results;
}
async function expectPlan(
compute: number,
addTag: number,
removeTag: number,
del: number,
) {
const plan = await getIndexPlan();
console.log("PLAN: ", plan);
expect(plan.compute).toHaveLength(compute);
expect(plan.addTag).toHaveLength(addTag);
expect(plan.removeTag).toHaveLength(removeTag);
expect(plan.del).toHaveLength(del);
return plan;
}
test("should index test folder without problem", async () => {
addToTestDir([
["test.ts", TEST_TS],
["py/main.py", TEST_PY],
]);
await expectPlan(2, 0, 0, 0);
const updates = await refreshIndex();
expect(updates.length).toBeGreaterThan(0);
});
test("should have created index folder with all necessary files", async () => {
expect(fs.existsSync(getIndexSqlitePath())).toBe(true);
});
test("should have indexed all of the files", async () => {
const indexed = await getAllIndexedFiles();
expect(indexed.length).toBe(2);
expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
});
test("should successfully re-index after adding a file", async () => {
addToTestDir([["main.rs", TEST_RS]]);
await expectPlan(1, 0, 0, 0);
const updates = await refreshIndex();
expect(updates.length).toBeGreaterThan(0);
// Check that the new file was indexed
const files = await getAllIndexedFiles();
expect(files.length).toBe(3);
expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
});
test("should successfully re-index after deleting a file", async () => {
fs.rmSync(path.join(TEST_DIR, "main.rs"));
await expectPlan(0, 0, 0, 1);
const updates = await refreshIndex();
expect(updates.length).toBeGreaterThan(0);
// Check that the deleted file was removed from the index
const files = await getAllIndexedFiles();
expect(files.length).toBe(2);
expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
});
test("shouldn't index any files when nothing changed", async () => {
await expectPlan(0, 0, 0, 0);
const updates = await refreshIndex();
expect(updates.length).toBeGreaterThan(0);
});
test("should create git repo for testing", async () => {
execSync(
`cd ${TEST_DIR} && git init && git checkout -b main && git add -A && git commit -m "First commit"`,
);
});
test.skip("should only re-index the changed files when changing branches", async () => {
execSync(`cd ${TEST_DIR} && git checkout -b test2`);
// Rewriting the file
addToTestDir([["test.ts", "// This is different"]]);
// Should re-compute test.ts, but just re-tag the .py file
await expectPlan(1, 1, 0, 0);
execSync(`cd ${TEST_DIR} && git add -A && git commit -m "Change .ts file"`);
});
test.skip("shouldn't re-index anything when changing back to original branch", async () => {
execSync(`cd ${TEST_DIR} && git checkout main`);
await expectPlan(0, 0, 0, 0);
});
});

View file

@ -0,0 +1,32 @@
import path from "path";
import { shouldChunk } from "../../../indexing/chunk/chunk";
describe("shouldChunk", () => {
test("should chunk a typescript file", () => {
const filePath = path.join("directory", "file.ts");
const fileContent = generateString(10000);
expect(shouldChunk(path.sep, filePath, fileContent)).toBe(true);
});
test("should not chunk a large typescript file", () => {
const filePath = path.join("directory", "file.ts");
const fileContent = generateString(1500000);
expect(shouldChunk(path.sep, filePath, fileContent)).toBe(false);
});
test("should not chunk an empty file", () => {
const filePath = path.join("directory", "file.ts");
const fileContent = generateString(0);
expect(shouldChunk(path.sep, filePath, fileContent)).toBe(false);
});
test("should not chunk a file without extension", () => {
const filePath = path.join("directory", "with.dot", "filename");
const fileContent = generateString(10000);
expect(shouldChunk(path.sep, filePath, fileContent)).toBe(false);
});
});
function generateString(length: number) {
return "a".repeat(length);
}

View file

@ -0,0 +1,41 @@
import { GPTAsyncEncoder, LlamaAsyncEncoder } from "../../llm/asyncEncoder";
describe("llama encoder", () => {
var tokenizer: LlamaAsyncEncoder;
beforeAll(() => {
tokenizer = new LlamaAsyncEncoder();
});
afterAll(() => {
tokenizer.close();
});
test("hello world", async () => {
const input = "the quick brown fox jumped over the lazy dog";
const output = await tokenizer.encode(input);
expect(output).toEqual([1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203]);
const decoded = await tokenizer.decode(output);
expect(decoded).toBe(input);
});
});
describe("tiktoken encoder", () => {
var tokenizer: GPTAsyncEncoder;
beforeAll(() => {
tokenizer = new GPTAsyncEncoder();
});
afterAll(() => {
tokenizer.close();
});
test("hello world", async () => {
const input = "the quick brown fox jumped over the lazy dog";
const output = await tokenizer.encode(input);
expect(output).toEqual([1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679]);
const decoded = await tokenizer.decode(output);
expect(decoded).toBe(input);
});
});

View file

@ -1,7 +1,8 @@
import fs from "fs";
import path from "path";
export const TEST_DIR = path.join(__dirname, "testDir");
// Want this outside of the git repository so we can change branches in tests
export const TEST_DIR = path.join(__dirname, "..", "..", "testDir");
export function setUpTestDir() {
if (fs.existsSync(TEST_DIR)) {
@ -11,17 +12,22 @@ export function setUpTestDir() {
}
export function tearDownTestDir() {
fs.rmSync(TEST_DIR, { recursive: true });
if (fs.existsSync(TEST_DIR)) {
fs.rmSync(TEST_DIR, { recursive: true });
}
}
export function addToTestDir(paths: (string | string[])[]) {
for (const p of paths) {
const filepath = path.join(TEST_DIR, Array.isArray(p) ? p[0] : p);
fs.mkdirSync(path.dirname(filepath), { recursive: true });
if (Array.isArray(p)) {
fs.writeFileSync(path.join(TEST_DIR, p[0]), p[1]);
fs.writeFileSync(filepath, p[1]);
} else if (p.endsWith("/")) {
fs.mkdirSync(path.join(TEST_DIR, p), { recursive: true });
fs.mkdirSync(filepath, { recursive: true });
} else {
fs.writeFileSync(path.join(TEST_DIR, p), "");
fs.writeFileSync(filepath, "");
}
}
}

View file

@ -45,12 +45,17 @@ class FileSystemIde implements IDE {
async getGitHubAuthToken(): Promise<string | undefined> {
return undefined;
}
getLastModified(files: string[]): Promise<{ [path: string]: number }> {
return new Promise((resolve) => {
resolve({
[files[0]]: 1234567890,
});
});
async getLastModified(files: string[]): Promise<{ [path: string]: number }> {
const result: { [path: string]: number } = {};
for (const file of files) {
try {
const stats = fs.statSync(file);
result[file] = stats.mtimeMs;
} catch (error) {
console.error(`Error getting last modified time for ${file}:`, error);
}
}
return result;
}
getGitRootPath(dir: string): Promise<string | undefined> {
return Promise.resolve(dir);
@ -78,8 +83,13 @@ class FileSystemIde implements IDE {
return Promise.resolve(undefined);
}
getTags(artifactId: string): Promise<IndexTag[]> {
return Promise.resolve([]);
async getTags(artifactId: string): Promise<IndexTag[]> {
const directory =(await this.getWorkspaceDirs())[0]
return [{
artifactId,
branch: await this.getBranch(directory),
directory
}]
}
getIdeInfo(): Promise<IdeInfo> {

View file

@ -84,11 +84,15 @@ export async function getParserForFile(filepath: string) {
const parser = new Parser();
const language = await getLanguageForFile(filepath);
if (!language) {
return undefined;
}
parser.setLanguage(language);
return parser;
} catch (e) {
console.error("Unable to load language for file", filepath, e);
console.debug("Unable to load language for file", filepath, e);
return undefined;
}
}
@ -116,7 +120,7 @@ export async function getLanguageForFile(
}
return language;
} catch (e) {
console.error("Unable to load language for file", filepath, e);
console.debug("Unable to load language for file", filepath, e);
return undefined;
}
}

View file

@ -107,6 +107,17 @@ The StackOverflow slash command will automatically pull results from StackOverfl
}
```
### `/onboard`
The Onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture.
```json
{
"name": "onboard",
"description": "Familiarize yourself with the codebase"
}
```
## Custom Slash Commands
There are two ways to add custom slash commands:

View file

@ -1,11 +1,55 @@
---
title: 🧑‍💻 Development data
title: Development Data
description: Collecting data on how you build software
keywords: [development data, dev data, LLM-aided development]
keywords: [development data, dev data, LLM-aided development, software development, coding feedback]
---
# 🧑‍💻 Development Data
# Development Data
When you use Continue, you automatically collect data on how you build software. By default, this development data is saved to `.continue/dev_data` on your local machine. When combined with the code that you ultimately commit, it can be used to improve the LLM that you or your team use (if you allow).
## Why You Need Development Data
You can read more about how development data is generated as a byproduct of LLM-aided development and why we believe that you should start collecting it now: [It’s time to collect data on how you build software](https://blog.continue.dev/its-time-to-collect-data-on-how-you-build-software)
Development data is essential for any organization aiming to optimize its software development process. It provides crucial insights into how software is built by capturing the detailed workflow, context behind decisions, and natural language reasoning used during coding. Collecting and utilizing this data helps in:
- **Improving LLMs**: Enhancing the performance and relevance of Large Language Models (LLMs) that assist in coding, making them more accurate and helpful.
- **Understanding Developer Challenges**: Identifying what frustrates developers and how they overcome challenges.
- **Demonstrating ROI**: Calculating the return on investment (ROI) of using LLMs within your organization.
- **Continual Improvement**: Establishing a continuous feedback loop to keep LLMs updated with the latest information, code, and preferred styles.
## Understanding Development Data
### Data Components
- **Step-by-Step Process**: Detailed record of each step taken while completing a task.
- **Context Capture**: Information used to make decisions, such as code snippets, documentation, and logs.
- **Natural Language Reasoning**: Explanations and decisions made in natural language during coding.
### Data Storage
By default, the development data collected by Continue is stored locally on your machine in the directory `~/.continue/dev_data`.
The data remains within your control on your local machine. If you choose to share your data with Continue for improving LLMs or other services, you must give explicit consent. If you are interested in working with us, please email us at [data@continue.dev](mailto:data@continue.dev).
## Utilizing Development Data
When combined with the code you commit, the development data can significantly improve the performance and relevance of LLMs. This results in more accurate suggestions and assistance during coding. Continue helps establish a continuous feedback loop to ensure LLMs always have fresh information, code, and preferred styles.
Continue plays a critical role in leveraging development data for enhancing LLMs:
- **Automatic Data Collection**: Continue automatically collects development data, including the step-by-step process, context, and natural language reasoning.
- **Improvement of LLMs**: The collected data is used to create a continuous feedback loop, ensuring the LLMs are constantly updated with fresh and relevant information, thus improving their performance and accuracy.
- **Development Data Engine**: Continue aids organizations in setting up development data engines. These engines offer visibility into how developers interact with LLMs, help calculate the ROI, identify frustrations, and enhance the models to overcome challenges.
- **Open-Source Coding Autopilot**: Continue is building an open-source coding autopilot that enables the automatic collection and utilization of development data, providing flexibility, customization, and better privacy and security.
- **Customized Improvement**: Continue allows teams to track and improve the metrics that matter most to their specific definitions of "great" software.
- **Addressing Budget and Data Staleness**: Continue supports organizations in justifying their LLM budgets and managing data staleness by helping them extract, load, and transform their data effectively.
## Privacy, Security, and Additional Resources
Understanding the privacy and security implications of development data collection is crucial. Ensure that sensitive information is safeguarded and that data collection aligns with your organization's privacy policies. For more detailed insights and guidelines, refer to the following:
- [Privacy Policy](https://continue.dev/privacy)
- [It’s time to collect data on how you build software](https://blog.continue.dev/its-time-to-collect-data-on-how-you-build-software) (Article)

View file

@ -1,8 +1,12 @@
# Prompt files (experimental)
Prompt (`.prompt`) files are an easy way to build and share LLM prompts with others. The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), and adds templating so that you can easily refer to files, your current git diff, and eventually much more.
Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts.
## How to create a prompt file
## Quick start
:::tip[Prompt library]
To assist you in getting started, [we've curated a small library of `.prompt` files](https://github.com/continuedev/prompt-file-example). We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts!
:::
Below is a quick example of setting up a prompt file to write unit tests using Jest.
@ -29,22 +33,23 @@ Write unit tests for the above selected code, following each of these instructio
- Don't explain how to set up `jest`
```
Now to use this prompt, you can highlight code and use cmd/ctrl+L to select it in the Continue sidebar. Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file.
Now to use this prompt, you can highlight code and use `cmd/ctrl+L` to select it in the Continue sidebar.
## Examples library
Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file.
To assist you in getting started, we've curated a small library of `.prompt` files. You can access this collection here: <https://github.com/continuedev/prompt-file-examples>
## Format
We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts!
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to use context providers and built-in variables using [Handlebars syntax](https://handlebarsjs.com/guide/).
## Syntax
> The current state of this format is experimental and subject to change
:::info
The current state of this format is experimental and subject to change
:::
### Preamble
The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters:
- `name`
- `temperature`
- `topP`
- `topK`
@ -54,29 +59,28 @@ The "preamble" is everything above the `---` separator, and lets you specify mod
- `mirostat`
- `stop`
- `maxTokens`
- `name`
- `description`
If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator.
### Body
The "body" is everything below the `---` separator, and contains your prompt.
At its most basic, the body can be just text.
### System message
To add a system message, start the body with `<system></system>` tags like in the example above and place your system message inside.
The body also supports templating with [Handlebars syntax](https://handlebarsjs.com/guide/). The following variables are currently available:
### Built-in variables
- `input`: The full text from the input box in the sidebar that is sent along with the slash command
- `currentFile`: The currently open file in your IDE
The following built-in variables are currently available:
#### Context providers
- `{{{ input }}}` - The full text from the input box in the sidebar that is sent along with the slash command
- `{{{ currentFile }}}` - The currently open file in your IDE
- `{{{ ./path/to/file.js }}}` - Any file can be directly referenced
The body of a .prompt file also supports any [context provider](../customization/context-providers.md) that you have added to your config by referencing the name of the context provider.
### Context providers
For example, if you wanted to include the contents of the terminal in your prompt, then you would use `{{{terminal}}}` in your prompt file. If you wanted to use the "url" context provider to include the contents of <https://github.com/continuedev/continue>, you would use `{{{url "https://github.com/continuedev/continue"}}}`, where the second part is the argument to the context provider, separated by a space.
Any [context provider](../customization/context-providers.md) that you have added to your config can be referenced using the name of the context provider. Context providers that receive an input are also supported.
- `{{{ terminal }}}` - The contents of the terminal
- `{{{ url "https://github.com/continuedev/continue" }}}` - The contents of a URL
## Feedback

View file

@ -12,6 +12,7 @@ OpenAI compatible servers
- [LocalAI](https://localai.io/basics/getting_started/)
- [llama-cpp-python](https://github.com/abetlen/llama-cpp-python#web-server)
- [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples)
- [vLLM](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) [^1]
OpenAI compatible APIs
@ -40,4 +41,7 @@ To force usage of `chat/completions` instead of `completions` endpoint you can s
"useLegacyCompletionsEndpoint": false
```
[^1]: Use the [Vllm Model Provider](./vllm.md) instead.
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/OpenAI.ts)

View file

@ -0,0 +1,30 @@
# AWS SageMaker
SageMaker provider support SageMaker endpoint deployed with [LMI](https://docs.djl.ai/docs/serving/serving/docs/lmi/index.html)
To setup SageMaker, add the following to your `config.json` file:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "deepseek-6.7b-instruct",
"provider": "sagemaker",
"model": "lmi-model-deepseek-coder-xxxxxxx",
"region": "us-west-2"
},
]
}
```
The value in model should be the SageMaker endpoint name you deployed.
Authentication will be through temporary or long-term credentials in
~/.aws/credentials under a profile called "sagemaker".
```title="~/.aws/credentials
[sagemaker]
aws_access_key_id = abcdefg
aws_secret_access_key = hijklmno
aws_session_token = pqrstuvwxyz # Optional: means short term creds.
```

View file

@ -0,0 +1,22 @@
# vLLM
Run the OpenAI-compatible server by vLLM using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/models/engine_args.html).
```shell
vllm serve NousResearch/Meta-Llama-3-8B-Instruct --max-model-len 1024
```
The continue implementation uses [OpenAI](./openai.md) under the hood and automatically selects the available model. You only need to set the `apiBase` like this:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "My vLLM OpenAI-compatible server",
"apiBase": "http://localhost:8000/v1"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)

View file

@ -1,4 +1,4 @@
# WatsonX
# Watsonx
Watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.

View file

@ -18,6 +18,7 @@ keywords:
Ollama,
HuggingFace,
AWS Bedrock,
AWS SageMaker,
]
---
@ -45,7 +46,8 @@ You can run a model on your local computer using:
- [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) (OpenAI compatible server)
- [IPEX-LLM](../reference/Model%20Providers/ipex_llm.md) (Local LLM on Intel GPU)
- [Msty](../reference/Model%20Providers/msty.md)
- [WatsonX](../reference/Model%20Providers/watsonx.md)
- [Watsonx](../reference/Model%20Providers/watsonx.md)
- [Nvidia NIMS](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
### Remote
@ -74,6 +76,7 @@ You can run open-source LLMs with cloud services like:
- [Deepinfra](../reference/Model%20Providers/deepinfra.md)
- [Groq](../reference/Model%20Providers/openai.md) (OpenAI compatible API)
- [AWS Bedrock](../reference/Model%20Providers/bedrock.md)
- [Nvidia NIMS](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
### Commercial models

View file

@ -1,40 +1,53 @@
---
title: 🦔 Telemetry
description: Continue collects anonymous usage information
title: Telemetry
description: Learn how Continue collects anonymous usage information and how you can opt out.
keywords: [telemetry, anonymous, usage info, opt out]
---
# 🦔 Telemetry
# Telemetry
## Overview
Continue collects and reports **anonymous** usage information.
Continue collects and reports **anonymous** usage information to help us improve our product. This data enables us to understand user interactions and optimize the user experience effectively. You can opt out of telemetry collection at any time if you prefer not to share your usage information.
This data is essential to understanding how we should improve the product. You can opt out of it at any time.
We utilize [Posthog](https://posthog.com/), an open-source platform for product analytics, to gather and store this data. For transparency, you can review the implementation code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) or read our [official privacy policy](https://continue.dev/privacy).
We use [Posthog](https://posthog.com/), an open source platform for product analytics, to collect and store the data. You can review the code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx), or review our official policy [here](https://continue.dev/privacy).
## Tracking Policy
## Tracking policy
All data collected by Continue is anonymized and stripped of personally identifiable information (PII) before being sent to PostHog. We are committed to maintaining the privacy and security of your data.
All data is anonymous and cleaned of PII before being sent to PostHog.
## What We Track
## What we track
The following usage information is collected and reported:
- Whether you accept or reject suggestions (never including the code or the prompt)
- The name of the model and command used
- The number of tokens generated
- The name of your OS and IDE
- Pageviews
- **Suggestion Interactions:** Whether you accept or reject suggestions (excluding the actual code or prompts involved).
- **Model and Command Information:** The name of the model and command used.
- **Token Metrics:** The number of tokens generated.
- **System Information:** The name of your operating system (OS) and integrated development environment (IDE).
- **Pageviews:** General pageview statistics.
## How to opt out
## How to Opt Out
The `~/.continue` directory contains a `config.json` file that looks like this:
You can disable anonymous telemetry by modifying the `config.json` file located in the `~/.continue` directory. This file typically includes the following entry:
```json title="~/.continue/config.json"
{
"allowAnonymousTelemetry": true,
...
}
```
You can turn off anonymous telemetry by changing the value of `allowAnonymousTelemetry` to `false`. Alternatively, you can uncheck the "Continue: Telemetry Enabled" box in VS Code settings.
To opt out, change the value of `allowAnonymousTelemetry` to `false`. Alternatively, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box.
### Steps to Disable Telemetry via Configuration File
1. Open the `~/.continue/config.json` file in your text editor.
2. Locate the `"allowAnonymousTelemetry"` setting.
3. Change the value from `true` to `false`.
4. Save the file.
### Steps to Disable Telemetry via VS Code Settings
1. Open VS Code.
2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut `Ctrl+,` on Windows/Linux or `Cmd+,` on macOS).
3. In the search bar, type "Continue: Telemetry Enabled".
4. Uncheck the "Continue: Telemetry Enabled" checkbox.

View file

@ -59,8 +59,21 @@ const sidebars = {
collapsed: true,
items: ["walkthroughs/set-up-codestral", "walkthroughs/llama3.1"],
},
"development-data",
"telemetry",
{
type: "category",
label: "🧑‍💻 Privacy",
collapsible: true,
collapsed: true,
items: [
"development-data",
"telemetry",
{
type: 'link',
label: 'Privacy Policy',
href: 'https://www.continue.dev/privacy',
},
],
},
"troubleshooting",
{
type: "category",

View file

@ -171,6 +171,7 @@
"anthropic",
"cohere",
"bedrock",
"sagemaker",
"together",
"ollama",
"huggingface-tgi",
@ -213,7 +214,7 @@
"### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)",
"### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)",
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### WatsonX\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks."
"### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks."
],
"type": "string"
},
@ -722,6 +723,23 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["sagemaker"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"markdownDescription": "SageMaker endpoint name"
}
}
}
},
{
"if": {
"properties": {
@ -1217,10 +1235,13 @@
"watsonxProjectId": {
"type": "string"
},
"watsonxStopToken": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
"ibm/granite-13b-instruct-v2",
"ibm/granite-20b-code-instruct",
"mistralai/mistral-large",
"meta-llama/llama-3-8b-instruct",
"meta-llama/llama-3-70b-instruct"
@ -1471,46 +1492,6 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {

View file

@ -1,7 +1,5 @@
<!-- Plugin description -->
![readme](media/readme.png)
<h1 align="center">Continue</h1>
<div align="center">
@ -14,26 +12,18 @@
## Easily understand code sections
![understand](docs/static/img/understand.gif)
`cmd+J` (MacOS) / `ctrl+J` (Windows)
## Tab to autocomplete code suggestions
![autocomplete](docs/static/img/autocomplete.gif)
`tab` (MacOS) / `tab` (Windows)
## Refactor functions where you are coding
![inline](docs/static/img/inline.gif)
`cmd+I` (MacOS) / `ctrl+I` (Windows)
## Quickly use documentation as context
![docs](docs/static/img/docs.gif)
`@docs` (MacOS) / `@docs` (Windows)
</div>

View file

@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension
pluginName = continue-intellij-extension
pluginRepositoryUrl = https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion = 0.0.57
pluginVersion = 0.0.59
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild = 223

View file

@ -171,6 +171,7 @@
"anthropic",
"cohere",
"bedrock",
"sagemaker",
"together",
"ollama",
"huggingface-tgi",
@ -213,7 +214,7 @@
"### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)",
"### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)",
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### WatsonX\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks."
"### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks."
],
"type": "string"
},
@ -722,6 +723,23 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["sagemaker"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"markdownDescription": "SageMaker endpoint name"
}
}
}
},
{
"if": {
"properties": {
@ -1217,10 +1235,13 @@
"watsonxProjectId": {
"type": "string"
},
"watsonxStopToken": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
"ibm/granite-13b-instruct-v2",
"ibm/granite-20b-code-instruct",
"mistralai/mistral-large",
"meta-llama/llama-3-8b-instruct",
"meta-llama/llama-3-70b-instruct"
@ -1471,46 +1492,6 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {

View file

@ -5,6 +5,13 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
## 0.8.46 - 2024-08-11
### Added
* new /onboard slash command
### Fixed
* Fixed problem loading config.ts
* Fixed bug causing duplicate indexing work
## 0.8.45 - 2024-08-05
### Added
* Support for Llama 3.1 and gpt-4o-mini

View file

@ -171,6 +171,7 @@
"anthropic",
"cohere",
"bedrock",
"sagemaker",
"together",
"ollama",
"huggingface-tgi",
@ -213,7 +214,7 @@
"### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)",
"### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)",
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### WatsonX\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks."
"### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks."
],
"type": "string"
},
@ -722,6 +723,23 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["sagemaker"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"markdownDescription": "SageMaker endpoint name"
}
}
}
},
{
"if": {
"properties": {
@ -1217,10 +1235,13 @@
"watsonxProjectId": {
"type": "string"
},
"watsonxStopToken": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
"ibm/granite-13b-instruct-v2",
"ibm/granite-20b-code-instruct",
"mistralai/mistral-large",
"meta-llama/llama-3-8b-instruct",
"meta-llama/llama-3-70b-instruct"
@ -1471,46 +1492,6 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {

View file

@ -174,6 +174,7 @@
"anthropic",
"cohere",
"bedrock",
"sagemaker",
"together",
"ollama",
"huggingface-tgi",
@ -216,7 +217,7 @@
"### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)",
"### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)",
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### WatsonX\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks."
"### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks."
],
"type": "string"
},
@ -784,6 +785,27 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"sagemaker"
]
}
},
"required": [
"provider"
]
},
"then": {
"properties": {
"model": {
"markdownDescription": "SageMaker endpoint name"
}
}
}
},
{
"if": {
"properties": {
@ -1348,10 +1370,13 @@
"watsonxProjectId": {
"type": "string"
},
"watsonxStopToken": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
"ibm/granite-13b-instruct-v2",
"ibm/granite-20b-code-instruct",
"mistralai/mistral-large",
"meta-llama/llama-3-8b-instruct",
"meta-llama/llama-3-70b-instruct"
@ -1624,55 +1649,6 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": [
"docs"
]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": [
"title",
"startUrl"
]
}
}
},
"required": [
"sites"
]
}
},
"required": [
"params"
]
}
},
{
"if": {
"properties": {

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.194",
"version": "0.9.196",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.194",
"version": "0.9.196",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -18,7 +18,7 @@
"axios": "^1.2.5",
"core": "file:../../core",
"cors": "^2.8.5",
"dbinfoz": "^0.1.4",
"dbinfoz": "^0.11.0",
"downshift": "^7.6.0",
"esbuild": "^0.17.19",
"express": "^4.18.2",
@ -96,6 +96,7 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
@ -118,6 +119,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
@ -3918,9 +3920,9 @@
}
},
"node_modules/dbinfoz": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.1.4.tgz",
"integrity": "sha512-MB56+xS571ip7qoXqxdnOUtXebbWaqoZN+S++W51SQYJRSjQFGEIPucNmxgeQlBGJ1vM4mQNV47wzV6fcrezZg==",
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.11.0.tgz",
"integrity": "sha512-l7REBd9pwTBI6PWSk/dx+zCpSE2tiJdSKfApeoOajnSgyMJgkwGfhpPO2mV76MLQeKPaSm0mMKxmoqd38SaHmw==",
"dependencies": {
"mysql2": "^3.9.1",
"pg": "^8.11.3",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.8.45",
"version": "0.8.46",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -579,7 +579,7 @@
"axios": "^1.2.5",
"core": "file:../../core",
"cors": "^2.8.5",
"dbinfoz": "^0.1.4",
"dbinfoz": "^0.11.0",
"downshift": "^7.6.0",
"esbuild": "^0.17.19",
"express": "^4.18.2",

View file

@ -19,6 +19,7 @@ const esbuildConfig = {
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
inject: ["./scripts/importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
supported: { "dynamic-import": false },
};
(async () => {

View file

@ -15,14 +15,18 @@ if (!fs.existsSync("build")) {
const isPreRelease = args.includes("--pre-release");
let command = isPreRelease
? "npx vsce package --out ./build patch --pre-release --no-dependencies" // --yarn"
: "npx vsce package --out ./build patch --no-dependencies"; // --yarn";
? "npx vsce package --out ./build patch --pre-release --no-dependencies" // --yarn"
: "npx vsce package --out ./build patch --no-dependencies"; // --yarn";
if (target) command += ` --target ${target}`;
if (target) {
command += ` --target ${target}`;
}
exec(command, (error) => {
if (error) throw error;
if (error) {
throw error;
}
console.log(
"vsce package completed - extension created at extensions/vscode/build/continue-patch.vsix",
"vsce package completed - extension created at extensions/vscode/build/continue-{version}.vsix",
);
});

View file

@ -245,6 +245,7 @@ const exe = os === "win32" ? ".exe" : "";
"../../../core/vendor/tree-sitter.wasm",
"../../../core/llm/llamaTokenizerWorkerPool.mjs",
"../../../core/llm/llamaTokenizer.mjs",
"../../../core/llm/tiktokenWorkerPool.mjs",
];
for (const f of filesToCopy) {
fs.copyFileSync(path.join(__dirname, f), path.join(__dirname, "..", "out", path.basename(f)));

View file

@ -320,8 +320,6 @@ const commandsMap: (
// Handle closing the GUI only if we are focused on the input
if (fullScreenTab) {
fullScreenPanel?.dispose();
} else {
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
}
} else {
// Handle opening the GUI otherwise
@ -480,11 +478,6 @@ const commandsMap: (
//Full screen not open - open it
captureCommandTelemetry("openFullScreen");
// Close the sidebar.webviews
// vscode.commands.executeCommand("workbench.action.closeSidebar");
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
// vscode.commands.executeCommand("workbench.action.toggleZenMode");
//create the full screen panel
let panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
@ -601,8 +594,8 @@ const commandsMap: (
currentStatus === StatusBarStatus.Paused
? StatusBarStatus.Enabled
: currentStatus === StatusBarStatus.Disabled
? StatusBarStatus.Paused
: StatusBarStatus.Disabled;
? StatusBarStatus.Paused
: StatusBarStatus.Disabled;
} else {
// Toggle between Disabled and Enabled
targetStatus =

View file

@ -259,9 +259,6 @@ export class VsCodeExtension {
const indexer = await this.core.codebaseIndexerPromise;
indexer.refreshFile(filepath);
}
// Reindex the workspaces
this.core.invoke("index/forceReIndex", undefined);
});
// When GitHub sign-in status changes, reload config

View file

@ -95,38 +95,29 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider {
return [quickEdit];
}
getSymbolsFrom(symbol: vscode.DocumentSymbol): vscode.DocumentSymbol[] {
if (symbol.children.length === 0) {
return [symbol];
}
const symbols: vscode.DocumentSymbol[] = [];
symbols.push(symbol);
for (const children of symbol.children) {
if (children.children.length === 0) {
symbols.push(children);
} else {
symbols.push(...this.getSymbolsFrom(children));
}
}
return symbols;
}
async getAllSymbols(uri: vscode.Uri) {
const docSymbols = await vscode.commands.executeCommand<
/**
* Get all top-level symbols and their immediate children.
* We do not recurse through all children to avoid noise.
*/
async getTopLevelAndChildrenSymbols(uri: vscode.Uri) {
const topLevelSymbols = await vscode.commands.executeCommand<
Array<vscode.DocumentSymbol> | undefined
>("vscode.executeDocumentSymbolProvider", uri);
if (!docSymbols) {
if (!topLevelSymbols) {
return [];
}
const symbols = docSymbols.flatMap((symbol) => this.getSymbolsFrom(symbol));
const childrenSymbols = topLevelSymbols.flatMap(
(symbol) => symbol.children,
);
const filteredSmybols = symbols?.filter((def) =>
this.quickActionSymbolKinds.includes(def.kind),
const symbols = [...topLevelSymbols, ...childrenSymbols];
const filteredSmybols = symbols?.filter(
(symbol) =>
this.quickActionSymbolKinds.includes(symbol.kind) &&
!symbol.range.isSingleLine,
);
return filteredSmybols;
@ -147,7 +138,7 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider {
return [];
}
const symbols = await this.getAllSymbols(document.uri);
const symbols = await this.getTopLevelAndChildrenSymbols(document.uri);
return symbols.flatMap(({ range }) => {
const commands: vscode.Command[] = !!this.customQuickActionsConfig

View file

@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { IDE } from "core";
import { ContinueConfig, IDE } from "core";
import { walkDir } from "core/indexing/walkDir";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
@ -94,6 +94,104 @@ export class QuickEdit {
this.initializeFileSearchState();
}
/**
* Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt.
* Displays a quick pick for "History" or "ContextProviders" to set the prompt or context provider string.
* Displays a quick pick for "Model" to set the current model title.
* Appends the entered prompt to the history and streams the edit with input and context.
*/
async show(args?: QuickEditShowParams) {
// Clean up state from previous quick picks, e.g. if a user pressed `esc`
this.clear();
const editor = vscode.window.activeTextEditor;
// We only allow users to interact with a quick edit if there is an open editor
if (!editor) {
return;
}
// Set state that is unique to each quick pick instance
this.setActiveEditorAndPrevInput(editor);
if (!this.editorWhenOpened) {
return;
}
const config = await this.configHandler.loadConfig();
if (!!args?.initialPrompt) {
this.initialPrompt = args.initialPrompt;
}
if (!!args?.range) {
this.range = args.range;
}
const selectedLabelOrInputVal = await this._getInitialQuickPickVal();
if (!selectedLabelOrInputVal) {
return;
}
Telemetry.capture("quickEditSelection", {
selection: selectedLabelOrInputVal,
});
let prompt: string | undefined = undefined;
switch (selectedLabelOrInputVal) {
case QuickEditInitialItemLabels.History:
const historyVal = await getHistoryQuickPickVal(this.context);
prompt = historyVal ?? "";
break;
case QuickEditInitialItemLabels.ContextProviders:
const contextProviderVal = await getContextProviderQuickPickVal(
config,
this.ide,
);
this.contextProviderStr = contextProviderVal ?? "";
// Recurse back to let the user write their prompt
this.show(args);
break;
case QuickEditInitialItemLabels.Model:
const curModelTitle = await this.getCurModelTitle();
if (!curModelTitle) {
break;
}
const selectedModelTitle = await getModelQuickPickVal(
curModelTitle,
config,
);
if (selectedModelTitle) {
this._curModelTitle = selectedModelTitle;
}
// Recurse back to let the user write their prompt
this.show(args);
break;
default:
// If it wasn't a label we can assume it was user input
if (selectedLabelOrInputVal) {
prompt = selectedLabelOrInputVal;
appendToHistory(selectedLabelOrInputVal, this.context);
}
}
if (prompt) {
await this._streamEditWithInputAndContext(prompt);
}
}
private async initializeFileSearchState() {
const workspaceDirs = await this.ide.getWorkspaceDirs();
@ -123,22 +221,31 @@ export class QuickEdit {
/**
* Gets the model title the user has chosen, or their default model
*/
private async _getCurModelTitle() {
private async getCurModelTitle() {
const config = await this.configHandler.loadConfig();
if (this._curModelTitle) {
return this._curModelTitle;
}
let defaultModelTitle =
config.experimental?.modelRoles?.inlineEdit ??
(await this.webviewProtocol.request("getDefaultModelTitle", undefined));
const inlineEditModel = config.experimental?.modelRoles?.inlineEdit;
if (!defaultModelTitle) {
defaultModelTitle = config.models[0]?.title!;
if (inlineEditModel) {
return inlineEditModel;
}
return defaultModelTitle;
let defaultModelTitle: string | undefined =
await this.webviewProtocol.request(
"getDefaultModelTitle",
undefined,
false,
);
if (!defaultModelTitle) {
defaultModelTitle = config.models[0].title;
}
return defaultModelTitle || inlineEditModel;
}
/**
@ -148,7 +255,7 @@ export class QuickEdit {
* @example
* // "Edit myFile.ts", "Edit myFile.ts:5-10", "Edit myFile.ts:15"
*/
_getQuickPickTitle = () => {
private getQuickPickTitle = () => {
const { uri } = this.editorWhenOpened.document;
const fileName = vscode.workspace.asRelativePath(uri, true);
@ -167,7 +274,7 @@ export class QuickEdit {
};
private async _streamEditWithInputAndContext(prompt: string) {
const modelTitle = await this._getCurModelTitle();
const modelTitle = await this.getCurModelTitle();
// Extracts all file references from the prompt string,
// which are denoted by an '@' symbol followed by
@ -202,7 +309,13 @@ export class QuickEdit {
}
async _getInitialQuickPickVal(): Promise<string | undefined> {
const modelTitle = await this._getCurModelTitle();
const modelTitle = await this.getCurModelTitle();
if (!modelTitle) {
this.ide.infoPopup("Please configure a model to use Quick Edit");
return undefined;
}
const { uri } = this.editorWhenOpened.document;
const initialItems: vscode.QuickPickItem[] = [
@ -247,7 +360,7 @@ export class QuickEdit {
quickPick.items = initialItems;
quickPick.placeholder =
"Enter a prompt to edit your code (@ to search files, ⏎ to submit)";
quickPick.title = this._getQuickPickTitle();
quickPick.title = this.getQuickPickTitle();
quickPick.ignoreFocusOut = true;
quickPick.value = this.initialPrompt ?? "";
@ -361,94 +474,4 @@ export class QuickEdit {
this.initialPrompt = undefined;
this.range = undefined;
}
/**
* Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt.
* Displays a quick pick for "History" or "ContextProviders" to set the prompt or context provider string.
* Displays a quick pick for "Model" to set the current model title.
* Appends the entered prompt to the history and streams the edit with input and context.
*/
async show(args?: QuickEditShowParams) {
// Clean up state from previous quick picks, e.g. if a user pressed `esc`
this.clear();
const editor = vscode.window.activeTextEditor;
// We only allow users to interact with a quick edit if there is an open editor
if (!editor) {
return;
}
// Set state that is unique to each quick pick instance
this.setActiveEditorAndPrevInput(editor);
if (!this.editorWhenOpened) {
return;
}
const config = await this.configHandler.loadConfig();
if (!!args?.initialPrompt) {
this.initialPrompt = args.initialPrompt;
}
if (!!args?.range) {
this.range = args.range;
}
const selectedLabelOrInputVal = await this._getInitialQuickPickVal();
Telemetry.capture("quickEditSelection", {
selection: selectedLabelOrInputVal,
});
let prompt: string | undefined = undefined;
switch (selectedLabelOrInputVal) {
case QuickEditInitialItemLabels.History:
const historyVal = await getHistoryQuickPickVal(this.context);
prompt = historyVal ?? "";
break;
case QuickEditInitialItemLabels.ContextProviders:
const contextProviderVal = await getContextProviderQuickPickVal(
config,
this.ide,
);
this.contextProviderStr = contextProviderVal ?? "";
// Recurse back to let the user write their prompt
this.show(args);
break;
case QuickEditInitialItemLabels.Model:
const curModelTitle = await this._getCurModelTitle();
const selectedModelTitle = await getModelQuickPickVal(
curModelTitle,
config,
);
if (selectedModelTitle) {
this._curModelTitle = selectedModelTitle;
}
// Recurse back to let the user write their prompt
this.show(args);
break;
default:
// If it wasn't a label we can assume it was user input
if (selectedLabelOrInputVal) {
prompt = selectedLabelOrInputVal;
appendToHistory(selectedLabelOrInputVal, this.context);
}
}
if (prompt) {
await this._streamEditWithInputAndContext(prompt);
}
}
}

View file

@ -160,7 +160,8 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
}),
});
if (!response.ok) {
throw new Error("Network failure");
const text = await response.text();
throw new Error("Error refreshing token: " + text);
}
const data = (await response.json()) as any;
return {

View file

@ -135,22 +135,6 @@ export class VsCodeIdeUtils {
);
}
showMultiFileEdit(edits: FileEdit[]) {
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
const panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
"Continue",
vscode.ViewColumn.One,
);
// panel.webview.html = this.sidebar.getSidebarContent(
// extensionContext,
// panel,
// this.ide,
// "/monaco",
// edits
// );
}
openFile(filepath: string, range?: vscode.Range) {
// vscode has a builtin open/get open files
return openEditorAndRevealRange(filepath, range, vscode.ViewColumn.One);
@ -380,7 +364,9 @@ export class VsCodeIdeUtils {
const lastLine = lines.pop()?.trim();
if (lastLine) {
let i = lines.length - 1;
while (i >= 0 && !lines[i].trim().startsWith(lastLine)) i--;
while (i >= 0 && !lines[i].trim().startsWith(lastLine)) {
i--;
}
terminalContents = lines.slice(Math.max(i, 0)).join("\n");
}
@ -400,7 +386,9 @@ export class VsCodeIdeUtils {
async getAvailableThreads(): Promise<Thread[]> {
const session = vscode.debug.activeDebugSession;
if (!session) return [];
if (!session) {
return [];
}
const threadsResponse = await this._getThreads(session);
return threadsResponse.threads;
@ -449,7 +437,9 @@ export class VsCodeIdeUtils {
stackDepth = 3,
): Promise<string[]> {
const session = vscode.debug.activeDebugSession;
if (!session) return [];
if (!session) {
return [];
}
const sourcesPromises = await session
.customRequest("stackTrace", {
@ -476,7 +466,9 @@ export class VsCodeIdeUtils {
}
private async retrieveSource(sourceContainer: any): Promise<string> {
if (!sourceContainer.source) return "";
if (!sourceContainer.source) {
return "";
}
const sourceRef = sourceContainer.source.sourceReference;
if (sourceRef && sourceRef > 0) {
@ -498,7 +490,7 @@ export class VsCodeIdeUtils {
sourceContainer.endColumn,
),
);
} else if (sourceContainer.line)
} else if (sourceContainer.line) {
// fall back to 5 line of context
return await this.readRangeInFile(
sourceContainer.source.path,
@ -509,7 +501,9 @@ export class VsCodeIdeUtils {
0,
),
);
else return "unavailable";
} else {
return "unavailable";
}
}
private async _getRepo(
@ -557,7 +551,9 @@ export class VsCodeIdeUtils {
let i = 0;
while (!repo?.state?.HEAD?.name) {
if (this._repoWasNone) return undefined;
if (this._repoWasNone) {
return undefined;
}
await new Promise((resolve) => setTimeout(resolve, 1000));
i++;

View file

@ -1,5 +1,6 @@
import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { Message } from "core/util/messenger";
import { Telemetry } from "core/util/posthog";
import fs from "node:fs";
import path from "path";
import { v4 as uuidv4 } from "uuid";
@ -153,6 +154,14 @@ export class VsCodeWebviewProtocol
}
});
} else {
Telemetry.capture(
"webview_protocol_error",
{
messageType: msg.messageType,
errorMsg: message.split("\n\n")[0],
},
false,
);
vscode.window
.showErrorMessage(
message.split("\n\n")[0],
@ -194,29 +203,37 @@ export class VsCodeWebviewProtocol
public request<T extends keyof ToWebviewProtocol>(
messageType: T,
data: ToWebviewProtocol[T][0],
retry: boolean = true,
): Promise<ToWebviewProtocol[T][1]> {
const messageId = uuidv4();
return new Promise(async (resolve) => {
let i = 0;
while (!this.webview) {
if (i >= 10) {
resolve(undefined);
return;
} else {
await new Promise((res) => setTimeout(res, i >= 5 ? 1000 : 500));
i++;
if (retry) {
let i = 0;
while (!this.webview) {
if (i >= 10) {
resolve(undefined);
return;
} else {
await new Promise((res) => setTimeout(res, i >= 5 ? 1000 : 500));
i++;
}
}
}
this.send(messageType, data, messageId);
const disposable = this.webview.onDidReceiveMessage(
(msg: Message<ToWebviewProtocol[T][1]>) => {
if (msg.messageId === messageId) {
resolve(msg.data);
disposable?.dispose();
}
},
);
if (this.webview) {
const disposable = this.webview.onDidReceiveMessage(
(msg: Message<ToWebviewProtocol[T][1]>) => {
if (msg.messageId === messageId) {
resolve(msg.data);
disposable?.dispose();
}
},
);
} else if (!retry) {
resolve(undefined);
}
});
}
}

View file

@ -1,9 +1,9 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2020",
"target": "ES2022",
"lib": ["ES2022", "dom", "es6", "es5", "dom.iterable", "scripthost"],
"outDir": "out/tsc/src",
"lib": ["ES2021", "dom", "es6", "es5", "dom.iterable", "scripthost"],
"sourceMap": true,
"rootDir": "../../",
"strict": true /* enable all strict type-checking options */,

Some files were not shown because too many files have changed in this diff Show more