diff --git a/.changes/extensions/vscode/0.8.46.md b/.changes/extensions/vscode/0.8.46.md new file mode 100644 index 000000000..176439b9e --- /dev/null +++ b/.changes/extensions/vscode/0.8.46.md @@ -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 diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 7c7057df9..ee3fb2e99 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -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 diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index a04591c89..6fca2c0ad 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -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 diff --git a/.vscode/launch.json b/.vscode/launch.json index 9a8a7ccab..54d282cc8 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -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", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 60d6200b5..2192b2b8d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. diff --git a/binary/build.js b/binary/build.js index 506fcb18e..d2f01ee35 100644 --- a/binary/build.js +++ b/binary/build.js @@ -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; diff --git a/binary/package-lock.json b/binary/package-lock.json index dc4c7cb58..9378d2eef 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -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", diff --git a/binary/tsconfig.json b/binary/tsconfig.json index 3c95ceef0..215a5aee7 100644 --- a/binary/tsconfig.json +++ b/binary/tsconfig.json @@ -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, diff --git a/core/.gitignore b/core/.gitignore index 646c15e7c..ad1c54334 100644 --- a/core/.gitignore +++ b/core/.gitignore @@ -3,4 +3,5 @@ target **/.DS_Store npm-debug.log* .env -.continue-test \ No newline at end of file +.continue-test +testDir \ No newline at end of file diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 912d6cc1d..c67ce1f0a 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -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( diff --git a/core/commands/index.ts b/core/commands/index.ts index 2b1a67bbd..fd075c6ff 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -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, diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index e0d507a7a..0a6fc327d 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -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, ]; diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts new file mode 100644 index 000000000..ed5fa4dec --- /dev/null +++ b/core/commands/slash/onboard.ts @@ -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 { + 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; diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index ce5c17119..dff0b065b 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -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 { diff --git a/core/config/load.ts b/core/config/load.ts index 3077768d8..a9b2ba94f 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -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."); } diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index bc5be2da7..92d558aaf 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -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("")[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, + ), + }; +} diff --git a/core/config/types.ts b/core/config/types.ts index d950c15f7..97083bcd5 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -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" diff --git a/core/context/providers/DatabaseContextProvider.ts b/core/context/providers/DatabaseContextProvider.ts index d1a837c45..81a0a2710 100644 --- a/core/context/providers/DatabaseContextProvider.ts +++ b/core/context/providers/DatabaseContextProvider.ts @@ -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, diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 462fe0db4..c388fb6dc 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -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"; diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 6c1f9f578..923669c74 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -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, }); diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 9d07ae5cc..d1e7342fa 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -70,6 +70,7 @@ export async function retrieveContextItemsFromEmbeddings( nFinal, nRetrieve, tags, + pathSep: await extras.ide.pathSep(), embeddingsProvider: extras.embeddingsProvider, reranker: extras.reranker, filterDirectory, diff --git a/core/control-plane/schema.ts b/core/control-plane/schema.ts index 5557eff13..756798937 100644 --- a/core/control-plane/schema.ts +++ b/core/control-plane/schema.ts @@ -13,6 +13,7 @@ const modelDescriptionSchema = z.object({ "gemini", "mistral", "bedrock", + "sagemaker", "cloudflare", "azure", ]), diff --git a/core/core.ts b/core/core.ts index afa23aff1..6718cdf7d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -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); diff --git a/core/index.d.ts b/core/index.d.ts index ed508a4cc..d3ff2a4b8 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -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 = Pick< T, @@ -592,6 +594,7 @@ type ModelProvider = | "gemini" | "mistral" | "bedrock" + | "sagemaker" | "deepinfra" | "flowise" | "groq" diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index a5ec68f8b..8fc1ccb95 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -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], ); } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 9bacf81a9..984704aa2 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -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 { + protected async getIndexesToBuild(): Promise { 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 { + 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 { + 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 { + 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 { + const pathSep = await this.ide.pathSep(); + const path = filepath.split(pathSep); + return path[path.length - 1]; + } } diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 3a312b719..198232a95 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -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, + 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 { + 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 { + 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 { + 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 { 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 { + return new Promise((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`; + } } diff --git a/core/indexing/TestCodebaseIndex.ts b/core/indexing/TestCodebaseIndex.ts new file mode 100644 index 000000000..234bcbc3e --- /dev/null +++ b/core/indexing/TestCodebaseIndex.ts @@ -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 { + 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 { + 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); + } +} diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index d80bb1c4f..008f90c62 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -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, + 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 { 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 { + 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 { + 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((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`; + } } diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index 2bdf446a8..97665ab03 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -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; +} \ No newline at end of file diff --git a/core/indexing/chunk/code.ts b/core/indexing/chunk/code.ts index ac0811212..7e3fff2b3 100644 --- a/core/indexing/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -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; } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 74e53fe51..1e8a8245c 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -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, diff --git a/core/indexing/embeddings/BaseEmbeddingsProvider.ts b/core/indexing/embeddings/BaseEmbeddingsProvider.ts index f4ea7af2e..d23d61af1 100644 --- a/core/indexing/embeddings/BaseEmbeddingsProvider.ts +++ b/core/indexing/embeddings/BaseEmbeddingsProvider.ts @@ -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; get maxChunkSize(): number { - return this.options.maxChunkSize ?? MAX_CHUNK_SIZE; + return this.options.maxChunkSize ?? DEFAULT_MAX_CHUNK_SIZE; } static getBatchedChunks(chunks: string[]): string[][] { diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 2ff68b9f0..643b61c32 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -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 +} diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 2111bc9c1..26ca80cb6 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -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 { - const add = results.addTag; + const add = [...results.compute, ...results.addTag]; const remove = [...results.del, ...results.removeTag]; await Promise.all([ ...remove.map(({ cacheKey }) => { diff --git a/core/indexing/types.ts b/core/indexing/types.ts index f952ea8df..91111dc05 100644 --- a/core/indexing/types.ts +++ b/core/indexing/types.ts @@ -11,7 +11,7 @@ export enum IndexResultType { export type MarkCompleteCallback = ( items: PathAndCacheKey[], resultType: IndexResultType, -) => void; +) => Promise; export interface CodebaseIndex { artifactId: string; diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 2d8cd6e07..014753daf 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -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 { + 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 { - 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 { + const options = { ...defaultOptions, ..._options }; + yield* new DFSWalker(path, ide, options).walk(); } diff --git a/core/jest.global-setup.ts b/core/jest.global-setup.ts index ee9cddde4..cf374a702 100644 --- a/core/jest.global-setup.ts +++ b/core/jest.global-setup.ts @@ -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 }); + } } diff --git a/core/llm/asyncEncoder.ts b/core/llm/asyncEncoder.ts index 722664ead..ed6425df2 100644 --- a/core/llm/asyncEncoder.ts +++ b/core/llm/asyncEncoder.ts @@ -5,22 +5,23 @@ import * as path from "path"; export interface AsyncEncoder { encode(text: string): Promise; - decode(tokens: number[]): string; + decode(tokens: number[]): Promise; + close(): Promise; } 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 { return this.workerPool.exec("encode", [text]); } - decode(tokens: number[]): string { - return llamaTokenizer.decode(tokens); + async decode(tokens: number[]): Promise { + 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 { - 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 { + return this.workerPool.exec("decode", [tokens]); } + + // TODO: this should be called somewhere before exit or potentially with a shutdown hook + public async close(): Promise { + 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); } \ No newline at end of file diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 1dc172001..e1d184b80 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -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", diff --git a/core/llm/constants.ts b/core/llm/constants.ts index a31dbbe3d..cc1866d4b 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -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, }; diff --git a/core/llm/index.ts b/core/llm/index.ts index 2d37c40d6..ca3c032a6 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -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, diff --git a/core/llm/llamaTokenizerWorkerPool.mjs b/core/llm/llamaTokenizerWorkerPool.mjs index 2131f4a1a..1ef82c872 100644 --- a/core/llm/llamaTokenizerWorkerPool.mjs +++ b/core/llm/llamaTokenizerWorkerPool.mjs @@ -5,6 +5,11 @@ function encode(segment) { return llamaTokenizer.encode(segment); } +function decode(tokens) { + return llamaTokenizer.decode(tokens); +} + workerpool.worker({ + decode, encode, }); \ No newline at end of file diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 419f49ad5..226671c52 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -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[] { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 366f6bd60..cea8ec524 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -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") { diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts new file mode 100644 index 000000000..6a5890e67 --- /dev/null +++ b/core/llm/llms/SageMaker.ts @@ -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 = { + 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 { + 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 { + 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; diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts new file mode 100644 index 000000000..d0ad32816 --- /dev/null +++ b/core/llm/llms/Vllm.ts @@ -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; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 29ca63c39..747a10c6a 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -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, diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index fe66d87c2..cd084207e 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -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, - inputData: any, - helpers?: [string, Handlebars.HelperDelegate][], -): Promise { - const promises: { [key: string]: Promise } = {}; - 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, diff --git a/core/llm/tiktokenWorkerPool.mjs b/core/llm/tiktokenWorkerPool.mjs new file mode 100644 index 000000000..9e0462f33 --- /dev/null +++ b/core/llm/tiktokenWorkerPool.mjs @@ -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, +}); \ No newline at end of file diff --git a/core/package-lock.json b/core/package-lock.json index 0a01b07f3..28570648f 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -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", diff --git a/core/package.json b/core/package.json index bc9236403..82a8157b7 100644 --- a/core/package.json +++ b/core/package.json @@ -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", diff --git a/core/promptFiles/createNewPromptFile.ts b/core/promptFiles/createNewPromptFile.ts new file mode 100644 index 000000000..d686e0d72 --- /dev/null +++ b/core/promptFiles/createNewPromptFile.ts @@ -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 "❌ " +- If you didn't find any problems, an h3 like "✅ " +- 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: + +\`\`\` +### ✅ + +### ❌ + + +\`\`\` + +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 { + 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); +} diff --git a/core/promptFiles/getContextProviderHelpers.ts b/core/promptFiles/getContextProviderHelpers.ts new file mode 100644 index 000000000..263724efa --- /dev/null +++ b/core/promptFiles/getContextProviderHelpers.ts @@ -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, + }, + }; +} diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts new file mode 100644 index 000000000..2ab9dc893 --- /dev/null +++ b/core/promptFiles/getPromptFiles.ts @@ -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 []; + } +} diff --git a/core/promptFiles/handlebarUtils.ts b/core/promptFiles/handlebarUtils.ts new file mode 100644 index 000000000..ada9fa6b7 --- /dev/null +++ b/core/promptFiles/handlebarUtils.ts @@ -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; +} { + const promises: { [key: string]: Promise } = {}; + + 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, + 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 }, +): Promise { + await Promise.all(Object.values(promises)); + + for (const id in promises) { + renderedString = renderedString.replace(`__${id}__`, await promises[id]); + } + + return renderedString; +} diff --git a/core/promptFiles/index.ts b/core/promptFiles/index.ts new file mode 100644 index 000000000..c3afdec76 --- /dev/null +++ b/core/promptFiles/index.ts @@ -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 }; diff --git a/core/promptFiles/renderTemplatedString.ts b/core/promptFiles/renderTemplatedString.ts new file mode 100644 index 000000000..d31cce0b9 --- /dev/null +++ b/core/promptFiles/renderTemplatedString.ts @@ -0,0 +1,30 @@ +import { + compileAndRenderTemplate, + prepareTemplateAndData, + registerHelpers, + resolveHelperPromises, +} from "./handlebarUtils"; + +export async function renderTemplatedString( + template: string, + readFile: (filepath: string) => Promise, + inputData: any, + availableHelpers?: Array<[string, Handlebars.HelperDelegate]>, +): Promise { + 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); +} diff --git a/core/promptFiles/slashCommandFromPromptFile.ts b/core/promptFiles/slashCommandFromPromptFile.ts new file mode 100644 index 000000000..e81f13615 --- /dev/null +++ b/core/promptFiles/slashCommandFromPromptFile.ts @@ -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("")) { + systemMessage = prompt.split("")[1].split("")[0].trim(); + prompt = prompt.split("")[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); + } + }, + }; +} diff --git a/core/promptFiles/updateChatHistory.ts b/core/promptFiles/updateChatHistory.ts new file mode 100644 index 000000000..8ebc6f038 --- /dev/null +++ b/core/promptFiles/updateChatHistory.ts @@ -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, + ), + }; +} diff --git a/core/test/config/ConfigHandler.test.ts b/core/test/config/ConfigHandler.test.ts new file mode 100644 index 000000000..ef35789cb --- /dev/null +++ b/core/test/config/ConfigHandler.test.ts @@ -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"); + }); +}); diff --git a/core/test/context/providers/index.test.ts b/core/test/context/providers/index.test.ts new file mode 100644 index 000000000..a31d10e46 --- /dev/null +++ b/core/test/context/providers/index.test.ts @@ -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 { + 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); + }); + }); +}); diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts new file mode 100644 index 000000000..97c1815b0 --- /dev/null +++ b/core/test/fixtures.ts @@ -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)), +); diff --git a/core/test/indexing/CodebaseIndexer.skip.ts b/core/test/indexing/CodebaseIndexer.skip.ts deleted file mode 100644 index df2d6518b..000000000 --- a/core/test/indexing/CodebaseIndexer.skip.ts +++ /dev/null @@ -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, - ); - }); -}); diff --git a/core/test/indexing/CodebaseIndexer.test.ts b/core/test/indexing/CodebaseIndexer.test.ts new file mode 100644 index 000000000..6d7d73c8d --- /dev/null +++ b/core/test/indexing/CodebaseIndexer.test.ts @@ -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 { + 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); + }); +}); diff --git a/core/test/indexing/chunk/chunk.test.ts b/core/test/indexing/chunk/chunk.test.ts new file mode 100644 index 000000000..e45c11c79 --- /dev/null +++ b/core/test/indexing/chunk/chunk.test.ts @@ -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); +} diff --git a/core/test/llm/asyncEncoder.test.ts b/core/test/llm/asyncEncoder.test.ts new file mode 100644 index 000000000..f181a05ca --- /dev/null +++ b/core/test/llm/asyncEncoder.test.ts @@ -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); + }); +}); \ No newline at end of file diff --git a/core/test/testUtils/testDir.ts b/core/test/testUtils/testDir.ts index 33a636d08..557906cef 100644 --- a/core/test/testUtils/testDir.ts +++ b/core/test/testUtils/testDir.ts @@ -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, ""); } } } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 978fa0829..330776518 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -45,12 +45,17 @@ class FileSystemIde implements IDE { async getGitHubAuthToken(): Promise { 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 { return Promise.resolve(dir); @@ -78,8 +83,13 @@ class FileSystemIde implements IDE { return Promise.resolve(undefined); } - getTags(artifactId: string): Promise { - return Promise.resolve([]); + async getTags(artifactId: string): Promise { + const directory =(await this.getWorkspaceDirs())[0] + return [{ + artifactId, + branch: await this.getBranch(directory), + directory + }] } getIdeInfo(): Promise { diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 428c90d94..f4ab86c60 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -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; } } diff --git a/docs/docs/customization/slash-commands.md b/docs/docs/customization/slash-commands.md index 661f7e5e6..85985c55e 100644 --- a/docs/docs/customization/slash-commands.md +++ b/docs/docs/customization/slash-commands.md @@ -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: diff --git a/docs/docs/development-data.md b/docs/docs/development-data.md index 6432197b3..3f230d0ed 100644 --- a/docs/docs/development-data.md +++ b/docs/docs/development-data.md @@ -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) diff --git a/docs/docs/features/prompt-files.md b/docs/docs/features/prompt-files.md index aacd12dcb..89063c8c9 100644 --- a/docs/docs/features/prompt-files.md +++ b/docs/docs/features/prompt-files.md @@ -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: +## 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 `` 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 , 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 diff --git a/docs/docs/reference/Model Providers/openai.md b/docs/docs/reference/Model Providers/openai.md index 10c86206d..628ec8c42 100644 --- a/docs/docs/reference/Model Providers/openai.md +++ b/docs/docs/reference/Model Providers/openai.md @@ -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) diff --git a/docs/docs/reference/Model Providers/sagemaker.md b/docs/docs/reference/Model Providers/sagemaker.md new file mode 100644 index 000000000..189818548 --- /dev/null +++ b/docs/docs/reference/Model Providers/sagemaker.md @@ -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. +``` diff --git a/docs/docs/reference/Model Providers/vllm.md b/docs/docs/reference/Model Providers/vllm.md new file mode 100644 index 000000000..71a5f3cba --- /dev/null +++ b/docs/docs/reference/Model Providers/vllm.md @@ -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) diff --git a/docs/docs/reference/Model Providers/watsonx.md b/docs/docs/reference/Model Providers/watsonx.md index 1d672fee3..b6a239946 100644 --- a/docs/docs/reference/Model Providers/watsonx.md +++ b/docs/docs/reference/Model Providers/watsonx.md @@ -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. diff --git a/docs/docs/setup/model-providers.md b/docs/docs/setup/model-providers.md index cf265c7b6..ab774d242 100644 --- a/docs/docs/setup/model-providers.md +++ b/docs/docs/setup/model-providers.md @@ -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 diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index 886f129c8..144e8cd59 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -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. diff --git a/docs/sidebars.js b/docs/sidebars.js index f38b4aec6..84493e2bd 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -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", diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 9715204c2..180454880 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -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": { diff --git a/extensions/intellij/README.md b/extensions/intellij/README.md index 76b1693e6..3ea53bf93 100644 --- a/extensions/intellij/README.md +++ b/extensions/intellij/README.md @@ -1,7 +1,5 @@ -![readme](media/readme.png) -

Continue

@@ -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)
diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 9356c4252..cb39f4eee 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -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 diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 9715204c2..180454880 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -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": { diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index af5780a28..844377fb3 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -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 diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 9715204c2..180454880 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -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": { diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 5f3636e75..fcbba3140 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -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": { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e8848611a..e8a3b9674 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -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", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 92677807c..64ce17a70 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -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", diff --git a/extensions/vscode/scripts/esbuild.js b/extensions/vscode/scripts/esbuild.js index 9aa62fa7a..f3d2c09db 100644 --- a/extensions/vscode/scripts/esbuild.js +++ b/extensions/vscode/scripts/esbuild.js @@ -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 () => { diff --git a/extensions/vscode/scripts/package.js b/extensions/vscode/scripts/package.js index af2e76193..17594333e 100644 --- a/extensions/vscode/scripts/package.js +++ b/extensions/vscode/scripts/package.js @@ -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", ); }); diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 95aaf0010..f7ca0e5d7 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -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))); diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 695881931..b2ec0dea7 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -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 = diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 6baa27b06..d63b92e1a 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -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 diff --git a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts index 07b176560..8f0c8adfe 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts @@ -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 | 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 diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index 4be583ccd..58f6696c7 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -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 { - 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); - } - } } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 3f60c301b..7b6385962 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -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 { diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 51f614ff2..15f79ddfd 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -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 { 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 { 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 { - 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++; diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 3496691c5..f515995b8 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -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( messageType: T, data: ToWebviewProtocol[T][0], + retry: boolean = true, ): Promise { 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) => { - if (msg.messageId === messageId) { - resolve(msg.data); - disposable?.dispose(); - } - }, - ); + + if (this.webview) { + const disposable = this.webview.onDidReceiveMessage( + (msg: Message) => { + if (msg.messageId === messageId) { + resolve(msg.data); + disposable?.dispose(); + } + }, + ); + } else if (!retry) { + resolve(undefined); + } }); } } diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b160ec053..639fc167c 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -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 */, diff --git a/gui/package-lock.json b/gui/package-lock.json index d2cf7916d..23ff1c5ac 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -29,7 +29,7 @@ "dompurify": "^3.0.6", "downshift": "^7.6.0", "lodash": "^4.17.21", - "minisearch": "^6.3.0", + "minisearch": "^7.0.2", "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", @@ -89,6 +89,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", @@ -111,6 +112,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", @@ -17252,8 +17254,9 @@ } }, "node_modules/minisearch": { - "version": "6.3.0", - "license": "MIT" + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.0.2.tgz", + "integrity": "sha512-Pf0sFXaCgRpOBDr4G8wTbVAEH9o9rvJzCMwj0TMe3L/NfUuG188xabfx6Vm3vD/Dv5L500n7JeiMB9Mq3sWMfQ==" }, "node_modules/monaco-editor": { "version": "0.49.0", diff --git a/gui/package.json b/gui/package.json index 0d4ab0fd5..2b6bff3d1 100644 --- a/gui/package.json +++ b/gui/package.json @@ -32,7 +32,7 @@ "dompurify": "^3.0.6", "downshift": "^7.6.0", "lodash": "^4.17.21", - "minisearch": "^6.3.0", + "minisearch": "^7.0.2", "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 8ea591827..ab1dd5257 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -1,7 +1,15 @@ import DOMPurify from "dompurify"; import { themeIcons } from "seti-file-icons"; -const FileIcon = ({ filename, height, width }) => { +const FileIcon = ({ + filename, + height, + width, +}: { + filename: string; + height: string; + width: string; +}) => { const filenameParts = filename.includes(" (") ? filename.split(" ") : [filename, ""]; diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index bce4d9a83..f556e824a 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -34,7 +34,7 @@ function AddDocsDialog() { }, 100); }, [ref]); - function onSubmit(e) { + function onSubmit(e: any) { e.preventDefault(); const siteIndexingConfig: SiteIndexingConfig = { diff --git a/gui/src/components/dialogs/KeyboardShortcuts.tsx b/gui/src/components/dialogs/KeyboardShortcuts.tsx index f9335c78c..95f7ee282 100644 --- a/gui/src/components/dialogs/KeyboardShortcuts.tsx +++ b/gui/src/components/dialogs/KeyboardShortcuts.tsx @@ -33,7 +33,7 @@ const StyledKeyDiv = styled.div` align-items: center; `; -const keyToName = { +const keyToName: { [key: string]: string } = { "⌘": "Cmd", "⌃": "Ctrl", "⇧": "Shift", diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index f8921ee1b..95e8b0bec 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -1,5 +1,5 @@ import { - ArrowUturnLeftIcon, + ArrowPathIcon, BarsArrowDownIcon, CubeIcon, HandThumbDownIcon, @@ -15,7 +15,6 @@ import { defaultBorderRadius, lightGray, vscBackground, - vscButtonBackground, vscInputBackground, } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -123,103 +122,101 @@ function StepContainer(props: StepContainerProps) { /> )} - {(isHovered || typeof feedback !== "undefined") && !active && ( -
- {props.modelTitle && ( -
- - {props.modelTitle} -
-
- )} - {truncatedEarly && ( - { - props.onContinueGeneration(); - }} - > - - - )} - - - { - props.onRetry(); + {(props.isLast || isHovered || typeof feedback !== "undefined") && + !active && ( +
- +
{props.modelTitle}
+
+ + )} + + {truncatedEarly && ( + { + props.onContinueGeneration(); + }} + > + + + )} + + - - {feedback === false || ( - - { - sendFeedback(true); - }} - /> - - )} - {feedback === true || ( - - { - sendFeedback(false); - }} - /> - - )} - - { - props.onDelete(); + { + props.onRetry(); }} - /> - -
- )} + > + +
+ {feedback === false || ( + + { + sendFeedback(true); + }} + /> + + )} + {feedback === true || ( + + { + sendFeedback(false); + }} + /> + + )} + + { + props.onDelete(); + }} + /> + +
+ )}
); diff --git a/gui/src/components/index.tsx b/gui/src/components/index.tsx index 7dfe1ea9a..a186d0e6b 100644 --- a/gui/src/components/index.tsx +++ b/gui/src/components/index.tsx @@ -191,7 +191,7 @@ const TooltipStyles = { overflow: "hidden", }; -export function StyledTooltip(props) { +export function StyledTooltip(props: any) { return ; } diff --git a/gui/src/components/loaders/IndexingProgressBar.tsx b/gui/src/components/loaders/IndexingProgressBar.tsx index 270b55284..6fcb38e48 100644 --- a/gui/src/components/loaders/IndexingProgressBar.tsx +++ b/gui/src/components/loaders/IndexingProgressBar.tsx @@ -138,7 +138,7 @@ const IndexingProgressBar = ({
Indexing error - click to retry - {getIndexingErrMsg(indexingState.desc)} + {/* {getIndexingErrMsg(indexingState.desc)} */}
{tooltipPortalDiv && ReactDOM.createPortal( diff --git a/gui/src/components/mainInput/CodeBlockExtension.tsx b/gui/src/components/mainInput/CodeBlockExtension.tsx index 13617a14c..4f9c670af 100644 --- a/gui/src/components/mainInput/CodeBlockExtension.tsx +++ b/gui/src/components/mainInput/CodeBlockExtension.tsx @@ -13,12 +13,12 @@ const CodeBlockComponent = ({ selected, editor, updateAttributes, -}) => { +}: any) => { const dispatch = useDispatch(); const item: ContextItemWithId = node.attrs.item; const contextItems = useSelector( - (state: RootState) => state.state.contextItems + (state: RootState) => state.state.contextItems, ); return ( @@ -27,8 +27,8 @@ const CodeBlockComponent = ({ item.id === contextItems[0]?.id ? "#d0d" : selected - ? vscBadgeBackground - : undefined + ? vscBadgeBackground + : undefined } item={item} onDelete={() => { diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 54791cc91..9d37725c4 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -32,6 +32,16 @@ const ContextItemDiv = styled.div` } `; +export const ContextItems = styled.span` + margin-left: 5px; + font-size: ${getFontSize() - 1}px; + color: ${lightGray}; + + &:hover { + text-decoration: underline; + } +`; + interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; } @@ -41,10 +51,16 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { const [open, setOpen] = React.useState(false); - if (!props.contextItems || props.contextItems.length === 0) { + const ctxItems = props.contextItems; + + if (!ctxItems || ctxItems.length === 0) { return null; } + const contextItemsText = `${ctxItems.length} context ${ + ctxItems.length > 1 ? "items" : "item" + }`; + function openContextItem(contextItem: ContextItemWithId) { if (contextItem.description.startsWith("http")) { window.open(contextItem.description, "_blank"); @@ -99,7 +115,7 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { style={{ color: lightGray }} > )} - Context Used + {contextItemsText} {open && (
{ paddingTop: "2px", }} > - {props.contextItems?.map((contextItem, idx) => { + {ctxItems?.map((contextItem, idx) => { if (contextItem.description.startsWith("http")) { return ( { contextItem.description .split(" ") .shift() - .split("#") + ?.split("#") .shift() || "" } height="1.6em" @@ -165,7 +181,7 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { /> ) : ( diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 1ffe3ad24..574a945d0 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -110,8 +110,8 @@ function ContinueInputBox(props: ContinueInputBoxProps) { diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index fc07b32e0..7ad231a39 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -2,12 +2,9 @@ import { ArrowRightIcon, ArrowUpOnSquareIcon, AtSymbolIcon, - BeakerIcon, BookOpenIcon, CodeBracketIcon, - Cog6ToothIcon, CommandLineIcon, - CubeIcon, ExclamationCircleIcon, ExclamationTriangleIcon, FolderIcon, @@ -15,10 +12,11 @@ import { GlobeAltIcon, HashtagIcon, MagnifyingGlassIcon, - PaintBrushIcon, + PencilIcon, PlusIcon, SparklesIcon, TrashIcon, + BoltIcon, } from "@heroicons/react/24/outline"; import { Editor } from "@tiptap/react"; import { @@ -62,16 +60,11 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { docs: BookOpenIcon, issue: ExclamationCircleIcon, trash: TrashIcon, - "/edit": PaintBrushIcon, + "/edit": PencilIcon, "/clear": TrashIcon, - "/test": BeakerIcon, - "/config": Cog6ToothIcon, "/comment": HashtagIcon, "/share": ArrowUpOnSquareIcon, "/cmd": CommandLineIcon, - "/codebase": SparklesIcon, - "/so": GlobeAltIcon, - "/issue": ExclamationCircleIcon, }; function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { @@ -81,41 +74,41 @@ function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { ); } - const provider = - props.item.type === "contextProvider" - ? props.item.id - : props.item.type === "slashCommand" - ? props.item.id - : props.item.type; + const provider = (() => { + switch (props.item.type) { + case "contextProvider": + case "slashCommand": + return props.item.id; + default: + return props.item.type; + } + })(); - const iconClass = `${props.className} flex-shrink-0`; + const IconComponent = + ICONS_FOR_DROPDOWN[provider] ?? + (props.item.type === "contextProvider" ? AtSymbolIcon : BoltIcon); - let fallbackIcon; - const Icon = ICONS_FOR_DROPDOWN[provider]; - if (!Icon) { - fallbackIcon = - props.item.type === "contextProvider" ? ( - - ) : ( - - ); - } else { - fallbackIcon = ; + const fallbackIcon = ( + + ); + + if (!props.item.icon) { + return fallbackIcon; } - if (props.item.icon) { - return ( - - ); - } - - return fallbackIcon; + return ( + + ); } const ItemsDiv = styled.div` @@ -212,6 +205,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { description: "Add a new documentation source", }); } + setAllItems(items); }, [subMenuTitle, props.items, props.editor]); diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 3be8e714d..8ab8f190e 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -196,6 +196,7 @@ function TipTapEditor(props: TipTapEditorProps) { ); const defaultModel = useSelector(defaultModelSelector); + const defaultModelRef = useUpdatingRef(defaultModel); const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems); const availableContextProvidersRef = useUpdatingRef( @@ -267,16 +268,16 @@ function TipTapEditor(props: TipTapEditorProps) { props: { handleDOMEvents: { paste(view, event) { - console.log("Pasting image"); + const model = defaultModelRef.current; const items = event.clipboardData.items; for (const item of items) { const file = item.getAsFile(); file && modelSupportsImages( - defaultModel.provider, - defaultModel.model, - defaultModel.title, - defaultModel.capabilities, + model.provider, + model.model, + model.title, + model.capabilities, ) && handleImageFile(file).then((resp) => { if (!resp) return; diff --git a/gui/src/components/mainInput/TutorialCard.tsx b/gui/src/components/mainInput/TutorialCard.tsx index f499e95aa..ed59371b1 100644 --- a/gui/src/components/mainInput/TutorialCard.tsx +++ b/gui/src/components/mainInput/TutorialCard.tsx @@ -53,7 +53,7 @@ export function TutorialCard({ onClose }: TutorialCardProps) { className="align-middle pr-3" /> - Highlight code and press {getMetaKeyLabel() + "L"} o + Highlight code and press {getMetaKeyLabel() + "L"} to add it to the chat window diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/getSuggestion.ts index f5f186318..196fe09a2 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/getSuggestion.ts @@ -16,8 +16,8 @@ function getSuggestion( items, allowSpaces: true, render: () => { - let component; - let popup; + let component: any; + let popup: any; const onExit = () => { popup?.[0]?.destroy(); @@ -26,7 +26,7 @@ function getSuggestion( }; return { - onStart: (props) => { + onStart: (props: any) => { component = new ReactRenderer(MentionList, { props: { ...props, enterSubmenu, onClose: onExit }, editor: props.editor, @@ -51,7 +51,7 @@ function getSuggestion( onOpen(); }, - onUpdate(props) { + onUpdate(props: any) { component.updateProps({ ...props, enterSubmenu }); if (!props.clientRect) { @@ -63,7 +63,7 @@ function getSuggestion( }); }, - onKeyDown(props) { + onKeyDown(props: any) { if (props.event.key === "Escape") { popup[0].hide(); @@ -112,7 +112,7 @@ export function getContextProviderDropdownOptions( inSubmenu: MutableRefObject, ideMessenger: IIdeMessenger, ) { - const items = async ({ query }) => { + const items = async ({ query }: { query: string }) => { if (inSubmenu.current) { const results = getSubmenuContextItemsRef.current( inSubmenu.current, @@ -186,7 +186,7 @@ export function getSlashCommandDropdownOptions( onOpen: () => void, ideMessenger: IIdeMessenger, ) { - const items = async ({ query }) => { + const items = async ({ query }: { query: string }) => { const options = [ ...availableSlashCommandsRef.current, { diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 63bff4257..a47261cb2 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -126,7 +126,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { onClick={(e) => { e.stopPropagation(); e.preventDefault(); - props.onEdit(); + props.onEdit?.(); }} {...(props.editing && { color: "#f0f4" })} > @@ -137,7 +137,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { text="Delete" onClick={(e) => { e.stopPropagation(); - props.onDelete(); + props.onDelete?.(); }} > @@ -161,7 +161,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { />
- {codeBlockRef.current?.scrollHeight > MAX_PREVIEW_HEIGHT && ( + {(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && ( void; @@ -17,7 +20,9 @@ interface QuickModelSetupProps { } function QuickModelSetup(props: QuickModelSetupProps) { - const [selectedProvider, setSelectedProvider] = useState(providers["openai"]); + const [selectedProvider, setSelectedProvider] = useState( + providers["openai"]!, + ); const [selectedModel, setSelectedModel] = useState( selectedProvider.packages[0], ); @@ -91,7 +96,9 @@ function QuickModelSetup(props: QuickModelSetupProps) { if (selectedModel.params.model.startsWith("codestral")) { apiKeyUrl = "https://console.mistral.ai/codestral"; } - ideMessenger.post("openUrl", apiKeyUrl); + if (apiKeyUrl) { + ideMessenger.post("openUrl", apiKeyUrl); + } }} > Get API Key @@ -110,7 +117,8 @@ function QuickModelSetup(props: QuickModelSetupProps) { { - ideMessenger.post("openUrl", selectedProvider.downloadUrl); + selectedProvider.downloadUrl && + ideMessenger.post("openUrl", selectedProvider.downloadUrl); }} > Download {selectedProvider.title} diff --git a/gui/src/components/modelSelection/quickSetup/QuickSetupListBox.tsx b/gui/src/components/modelSelection/quickSetup/QuickSetupListBox.tsx index 1d7c081cc..9a187fd2a 100644 --- a/gui/src/components/modelSelection/quickSetup/QuickSetupListBox.tsx +++ b/gui/src/components/modelSelection/quickSetup/QuickSetupListBox.tsx @@ -57,7 +57,7 @@ function QuickSetupListBox({ + className={({ active }: { active: boolean }) => `relative cursor-default select-none py-2 pl-10 pr-4 ${ active ? "bg-amber-100 text-amber-900" : "text-gray-900" }` diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index e67217c25..fed23e1dc 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -214,6 +214,7 @@ export class IdeMessenger implements IIdeMessenger { } return { + modelTitle: next.value.content?.modelTitle, prompt: next.value.content?.prompt, completion: next.value.content?.completion, completionOptions: next.value.content?.completionOptions, diff --git a/gui/src/editorInset/EditorInset.tsx b/gui/src/editorInset/EditorInset.tsx index d1be4f65e..f22e6a5f7 100644 --- a/gui/src/editorInset/EditorInset.tsx +++ b/gui/src/editorInset/EditorInset.tsx @@ -25,7 +25,7 @@ function EditorInset() { useSetup(dispatch); - const elementRef = useRef(null); + const elementRef = useRef(null); const ideMessenger = useContext(IdeMessengerContext); @@ -46,7 +46,7 @@ function EditorInset() { return ( { diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index db07f3e50..94e372d3f 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -5,6 +5,7 @@ import { ChatHistory, ChatHistoryItem, ChatMessage, + ContextItemWithId, InputModifiers, MessageContent, PromptLog, @@ -21,6 +22,7 @@ import resolveEditorContent from "../components/mainInput/resolveInput"; import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { + addContextItems, addPromptCompletionPair, clearLastResponse, initNewActiveMessage, @@ -56,6 +58,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const cancelToken = abortController.signal; try { + if (!defaultModel) { + throw new Error("Default model not defined"); + } const gen = ideMessenger.llmStreamChat( defaultModel.title, cancelToken, @@ -115,9 +120,15 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { input: string, historyIndex: number, selectedCode: RangeInFile[], + contextItems: ContextItemWithId[], ) { const abortController = new AbortController(); const cancelToken = abortController.signal; + + if (!defaultModel) { + throw new Error("Default model not defined"); + } + const modelTitle = defaultModel.title; const checkActiveInterval = setInterval(() => { @@ -171,10 +182,11 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { modifiers, ideMessenger, ); + dispatch(addContextItems(contextItems)); // Automatically use currently open file if (!modifiers.noContext && (history.length === 0 || index === 0)) { - const usingFreeTrial = defaultModel.provider === "free-trial"; + const usingFreeTrial = defaultModel?.provider === "free-trial"; const currentFilePath = await ideMessenger.ide.getCurrentFile(); if (typeof currentFilePath === "string") { @@ -252,9 +264,10 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { commandInput, historyIndex, selectedCode, + contextItems, ); } - } catch (e) { + } catch (e: any) { console.log("Continue: error streaming response: ", e); ideMessenger.post("errorPopup", { message: `Error streaming response: ${e.message}`, diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 615ccd7bd..4956a6ed3 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -111,14 +111,14 @@ function useHistory(dispatch: Dispatch) { return json; } - async function loadLastSession(): Promise { + async function loadLastSession(): Promise { const lastSessionId = getLocalStorage("lastSessionId"); if (lastSessionId) { return await loadSession(lastSessionId); } } - function getLastSessionId(): string { + function getLastSessionId(): string | undefined { return getLocalStorage("lastSessionId"); } diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index 262b45eee..b41526ce9 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -197,33 +197,51 @@ function useSubmenuContextProviders() { return; } setLoaded(true); - contextProviderDescriptions.forEach(async (description) => { - const minisearch = new MiniSearch({ - fields: ["title", "description"], - storeFields: ["id", "title", "description"], - }); - const items = await ideMessenger.request("context/loadSubmenuItems", { - title: description.title, - }); - minisearch.addAll(items); - setMinisearches((prev) => ({ ...prev, [description.title]: minisearch })); - if (description.title === "file") { - const openFiles = await getOpenFileItems(); - setFallbackResults((prev) => ({ + const loadSubmenuItems = async () => { + for (const description of contextProviderDescriptions) { + const minisearch = new MiniSearch({ + fields: ["title", "description"], + storeFields: ["id", "title", "description"], + }); + const items = await ideMessenger.request("context/loadSubmenuItems", { + title: description.title, + }); + + try { + minisearch.addAll(items); + } catch (itemError) { + console.error( + "Error adding item to minisearch:", + itemError.message, + itemError.stack, + ); + } + + setMinisearches((prev) => ({ ...prev, - file: [ - ...openFiles, - ...items.slice(0, MAX_LENGTH - openFiles.length), - ], - })); - } else { - setFallbackResults((prev) => ({ - ...prev, - [description.title]: items.slice(0, MAX_LENGTH), + [description.title]: minisearch, })); + + if (description.title === "file") { + const openFiles = await getOpenFileItems(); + setFallbackResults((prev) => ({ + ...prev, + file: [ + ...openFiles, + ...items.slice(0, MAX_LENGTH - openFiles.length), + ], + })); + } else { + setFallbackResults((prev) => ({ + ...prev, + [description.title]: items.slice(0, MAX_LENGTH), + })); + } } - }); + }; + + loadSubmenuItems(); }, [contextProviderDescriptions, loaded]); useWebviewListener("configUpdate", async () => { diff --git a/gui/src/pages/AddNewModel/ConfigureProvider.tsx b/gui/src/pages/AddNewModel/ConfigureProvider.tsx index f4a199c21..b46db1931 100644 --- a/gui/src/pages/AddNewModel/ConfigureProvider.tsx +++ b/gui/src/pages/AddNewModel/ConfigureProvider.tsx @@ -161,7 +161,7 @@ function ConfigureProvider() { />
- {/* The WatsonX Authentication coukd be done by two different ways + {/* The Watsonx Authentication coukd be done by two different ways 1 ==> Using Api key 2 ==> Using Credentials */} {providerName === "watsonx" ? ( diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 21fddbb17..1c7756e3d 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -722,7 +722,7 @@ export const models: { [key: string]: ModelPackage } = { isOpenSource: false, }, graniteChat: { - title: "WatsonX - Granite Chat", + title: "Watsonx - Granite Chat", description: "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.", params: { @@ -735,27 +735,26 @@ export const models: { [key: string]: ModelPackage } = { isOpenSource: false, }, graniteCode: { - title: "WatsonX - Granite Code", + title: "Watsonx - Granite Code", description: "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.", params: { - model: "ibm/granite-13b-instruct-v2", + model: "ibm/granite-20b-code-instruct", contextLength: 20_000, - title: "Granite Code", - systemMessage: `You are Granite Chat, an AI language model developed by IBM. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior. You always respond to greetings (for example, hi, hello, g'day, morning, afternoon, evening, night, what's up, nice to meet you, sup, etc) with "Hello! I am Granite Chat, created by IBM. How can I help you today?". Please do not say anything else and do not start a conversation.`, + title: "Granite Code" }, providerOptions: ["watsonx"], - icon: "WatsonX.png", + icon: "Watsonx.png", isOpenSource: false, }, MistralLarge: { - title: "WatsonX - Mistral", + title: "Watsonx - Mistral", description: "Mistral Large, the most advanced Large Language Model (LLM) developed by Mistral Al, is an exceptionally powerful model.", params: { model: "mistralai/mistral-large", contextLength: 20_000, - title: "WatsonX - Mistral", + title: "Watsonx - Mistral", }, providerOptions: ["watsonx"], icon: "mistral.png", diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 6d6f51e73..4d83876ba 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -19,7 +19,7 @@ export interface InputDescriptor { required?: boolean; description?: string; [key: string]: any; - // the following are used only for WatsonX provider + // the following are used only for Watsonx provider // these attributes are used to determine whether the input is used in Api Authentication or Credentials section isWatsonxAuthenticatedByApiKey?: boolean; isWatsonxAuthenticatedByCredentials?: boolean; @@ -279,7 +279,6 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n title: "Groq", }, }, - , ], apiKeyUrl: "https://console.groq.com/keys", }, @@ -482,7 +481,7 @@ After it's up and running, you can start using Continue.`, ], }, watsonx: { - title: "WatsonX", + title: "Watsonx", provider: "watsonx", refPage: "watsonX", description: @@ -492,7 +491,7 @@ After it's up and running, you can start using Continue.`, { inputType: "text", key: "watsonxUrl", - label: "WatsonX URL", + label: "Watsonx URL", placeholder: "http://.dataplatform.cloud.ibm.com", required: true, isWatsonxAuthenticatedByApiKey: true, @@ -501,7 +500,7 @@ After it's up and running, you can start using Continue.`, { inputType: "text", key: "watsonxApiKey", - label: "WatsonX API Key", + label: "Watsonx API Key", placeholder: "Enter your API key", required: true, isWatsonxAuthenticatedByApiKey: true, @@ -509,7 +508,7 @@ After it's up and running, you can start using Continue.`, { inputType: "text", key: "watsonxProjectId", - label: "WatsonX Project Id", + label: "Watsonx Project Id", placeholder: "Enter your project Id", required: true, isWatsonxAuthenticatedByApiKey: true, @@ -518,7 +517,7 @@ After it's up and running, you can start using Continue.`, { inputType: "text", key: "watsonxUsername", - label: "WatsonX Username", + label: "Watsonx Username", placeholder: "Enter your Username", required: true, isWatsonxAuthenticatedByCredentials: true, @@ -526,7 +525,7 @@ After it's up and running, you can start using Continue.`, { inputType: "text", key: "watsonxPassword", - label: "WatsonX Password", + label: "Watsonx Password", placeholder: "Enter your password", required: true, isWatsonxAuthenticatedByCredentials: true, @@ -545,10 +544,16 @@ After it's up and running, you can start using Continue.`, placeholder: "ibm/granite-13b-chat-v2", isWatsonxAttribute: true, }, + { + inputType: "text", + key: "watsonxStopToken", + label: "Stop Token", + placeholder: "<|im_end|>", + }, ...completionParamsInputsConfigs, ], - icon: "WatsonX.png", + icon: "Watsonx.png", tags: [ModelProviderTags.RequiresApiKey], packages: [ models.graniteCode, diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index c03712c60..caaff7ea6 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -107,11 +107,11 @@ const StepsDiv = styled.div` // } .thread-message { - margin: 16px 8px 0 8px; - } - .thread-message:not(:first-child) { - border-top: 1px solid ${lightGray}22; + margin: 12px 4px 0 4px; } + // .thread-message:not(:first-child) { + // border-top: 1px solid ${lightGray}22; + // } `; const NewSessionButton = styled.div` @@ -166,7 +166,7 @@ const ThreadUserName = styled.div` color: ${lightGray}; `; -function fallbackRender({ error, resetErrorBoundary }) { +function fallbackRender({ error, resetErrorBoundary }: any) { // Call resetErrorBoundary() to reset the error boundary and retry the render. return ( @@ -207,7 +207,7 @@ function GUI() { const state = useSelector((state: RootState) => state.state); const [showTutorialCard, setShowTutorialCard] = useState( - getLocalStorage("showTutorialCard"), + getLocalStorage("showTutorialCard") ?? true, ); const onCloseTutorialCard = () => { @@ -483,10 +483,7 @@ function GUI() { onDelete={() => { dispatch(deleteMessage(index)); }} - modelTitle={ - item.promptLogs?.[0]?.completionOptions?.model ?? - "" - } + modelTitle={item.promptLogs?.[0]?.modelTitle ?? ""} /> diff --git a/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx b/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx index 1f6c38e2a..0bff4deab 100644 --- a/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx +++ b/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx @@ -80,7 +80,7 @@ function AutocompleteModelDropdown({ + className={({ active }: { active: boolean }) => `relative cursor-default select-none py-2 pl-10 pr-4 ${ active ? "bg-amber-100 text-amber-900" : "text-gray-900" }` diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index 6a56499bb..f41ad42ff 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -20,7 +20,7 @@ export const selectSlashCommands = createSelector( export const selectContextProviderDescriptions = createSelector( [(store: RootState) => store.state.config.contextProviders], (providers) => { - return providers.filter((desc) => desc.type === "submenu") || []; + return providers?.filter((desc) => desc.type === "submenu") || []; }, ); diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts index f75a83125..0d6671162 100644 --- a/gui/src/redux/slices/uiStateSlice.ts +++ b/gui/src/redux/slices/uiStateSlice.ts @@ -4,7 +4,7 @@ type UiState = { bottomMessageCloseTimeout: NodeJS.Timeout | undefined; displayBottomMessageOnBottom: boolean; showDialog: boolean; - dialogMessage: string | JSX.Element; + dialogMessage: string | JSX.Element | undefined; dialogEntryOn: boolean; }; @@ -21,13 +21,13 @@ export const uiStateSlice = createSlice({ reducers: { setBottomMessage: ( state, - action: PayloadAction + action: PayloadAction, ) => { state.bottomMessage = action.payload; }, setBottomMessageCloseTimeout: ( state, - action: PayloadAction + action: PayloadAction, ) => { if (state.bottomMessageCloseTimeout) { clearTimeout(state.bottomMessageCloseTimeout); @@ -36,13 +36,13 @@ export const uiStateSlice = createSlice({ }, setDialogMessage: ( state, - action: PayloadAction + action: PayloadAction, ) => { state.dialogMessage = action.payload; }, setDialogEntryOn: ( state, - action: PayloadAction + action: PayloadAction, ) => { state.dialogEntryOn = action.payload; }, @@ -51,7 +51,7 @@ export const uiStateSlice = createSlice({ }, setDisplayBottomMessageOnBottom: ( state, - action: PayloadAction + action: PayloadAction, ) => { state.displayBottomMessageOnBottom = action.payload; }, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 16ac22ad9..86f6bf21e 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -25,7 +25,7 @@ const rootReducer = combineReducers({ export type RootState = ReturnType; -const windowIDTransform = (windowID) => +const windowIDTransform = (windowID: string) => createTransform( // transform state on its way to being serialized and persisted. (inboundState, key) => { @@ -34,7 +34,7 @@ const windowIDTransform = (windowID) => // transform state being rehydrated (outboundState, key) => { return outboundState[windowID] || {}; - } + }, ); const saveSubsetFilters = [ diff --git a/gui/src/util/freeTrial.ts b/gui/src/util/freeTrial.ts index 60d789cd4..83e9ea510 100644 --- a/gui/src/util/freeTrial.ts +++ b/gui/src/util/freeTrial.ts @@ -6,6 +6,6 @@ export const FREE_TRIAL_LIMIT_REQUESTS = 50; * * @returns {boolean} true if the user has passed the free trial limit, false otherwise. */ -export function hasPassedFTL() { - return getLocalStorage("ftc") > FREE_TRIAL_LIMIT_REQUESTS; +export function hasPassedFTL(): boolean { + return (getLocalStorage("ftc") ?? 0) > FREE_TRIAL_LIMIT_REQUESTS; } diff --git a/extensions/vscode/manual-testing-sandbox/example.ipynb b/manual-testing-sandbox/example.ipynb similarity index 100% rename from extensions/vscode/manual-testing-sandbox/example.ipynb rename to manual-testing-sandbox/example.ipynb diff --git a/extensions/vscode/manual-testing-sandbox/nested-folder/helloNested.py b/manual-testing-sandbox/nested-folder/helloNested.py similarity index 100% rename from extensions/vscode/manual-testing-sandbox/nested-folder/helloNested.py rename to manual-testing-sandbox/nested-folder/helloNested.py diff --git a/extensions/vscode/manual-testing-sandbox/readme.md b/manual-testing-sandbox/readme.md similarity index 100% rename from extensions/vscode/manual-testing-sandbox/readme.md rename to manual-testing-sandbox/readme.md diff --git a/extensions/vscode/manual-testing-sandbox/test.css b/manual-testing-sandbox/test.css similarity index 100% rename from extensions/vscode/manual-testing-sandbox/test.css rename to manual-testing-sandbox/test.css diff --git a/manual-testing-sandbox/test.csv b/manual-testing-sandbox/test.csv new file mode 100644 index 000000000..49ae6b845 --- /dev/null +++ b/manual-testing-sandbox/test.csv @@ -0,0 +1,26 @@ +Date,Temperature,Damage Incident +04/12/1981,66,0 +11/12/1981,70,1 +3/22/82,69,0 +6/27/82,80,NA +01/11/1982,68,0 +04/04/1983,67,0 +6/18/83,72,0 +8/30/83,73,0 +11/28/83,70,0 +02/03/1984,57,1 +04/06/1984,63,1 +8/30/84,70,1 +10/05/1984,78,0 +11/08/1984,67,0 +1/24/85,53,1 +04/12/1985,67,0 +4/29/85,75,0 +6/17/85,70,0 +7/29/85,81,0 +8/27/85,76,0 +10/03/1985,79,0 +10/30/85,75,1 +11/26/85,76,0 +01/12/1986,58,1 +1/28/86,31,Challenger Accident diff --git a/extensions/vscode/manual-testing-sandbox/test.js b/manual-testing-sandbox/test.js similarity index 100% rename from extensions/vscode/manual-testing-sandbox/test.js rename to manual-testing-sandbox/test.js diff --git a/extensions/vscode/manual-testing-sandbox/test.rs b/manual-testing-sandbox/test.rs similarity index 100% rename from extensions/vscode/manual-testing-sandbox/test.rs rename to manual-testing-sandbox/test.rs diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 9d58ddffa..0e20ba7cb 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -51,6 +51,7 @@ export const modelDescriptionSchema = z.object({ "gemini", "mistral", "bedrock", + "sagemaker", "cloudflare", "azure", "continue-proxy",