diff --git a/.changes/extensions/vscode/0.8.55.md b/.changes/extensions/vscode/0.8.55.md new file mode 100644 index 000000000..4800ad907 --- /dev/null +++ b/.changes/extensions/vscode/0.8.55.md @@ -0,0 +1,9 @@ +## 0.8.55 - 2024-10-25 +### Added +* Web context provider +* Cerebras inference provider +* Automatic descriptions for previous chats +* Discord context provider +* Improved full screen UI +### Changed +* Easier way to accept/reject/re-prompt after cmd/ctrl+I diff --git a/.changes/unreleased/Added-20241014-231551.yaml b/.changes/unreleased/Added-20241014-231551.yaml deleted file mode 100644 index 1e323fab1..000000000 --- a/.changes/unreleased/Added-20241014-231551.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Web context provider -time: 2024-10-14T23:15:51.670444-07:00 diff --git a/.changes/unreleased/Added-20241014-231622.yaml b/.changes/unreleased/Added-20241014-231622.yaml deleted file mode 100644 index 82e129b6b..000000000 --- a/.changes/unreleased/Added-20241014-231622.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Cerebras inference provider -time: 2024-10-14T23:16:22.754491-07:00 diff --git a/.changes/unreleased/Added-20241014-231639.yaml b/.changes/unreleased/Added-20241014-231639.yaml deleted file mode 100644 index 89ff18abc..000000000 --- a/.changes/unreleased/Added-20241014-231639.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Automatic descriptions for previous chats -time: 2024-10-14T23:16:39.451261-07:00 diff --git a/.changes/unreleased/Added-20241014-231657.yaml b/.changes/unreleased/Added-20241014-231657.yaml deleted file mode 100644 index e6a93349e..000000000 --- a/.changes/unreleased/Added-20241014-231657.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Discord context provider -time: 2024-10-14T23:16:57.089953-07:00 diff --git a/.changes/unreleased/Added-20241014-231714.yaml b/.changes/unreleased/Added-20241014-231714.yaml deleted file mode 100644 index f53eeca37..000000000 --- a/.changes/unreleased/Added-20241014-231714.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Added -body: Improved full screen UI -time: 2024-10-14T23:17:14.574917-07:00 diff --git a/.changes/unreleased/Added-20241102-002724.yaml b/.changes/unreleased/Added-20241102-002724.yaml new file mode 100644 index 000000000..3426d6546 --- /dev/null +++ b/.changes/unreleased/Added-20241102-002724.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New Edit mode in sidebar (cmd/ctrl+I) +time: 2024-11-02T00:27:24.40964-07:00 diff --git a/.changes/unreleased/Added-20241102-002744.yaml b/.changes/unreleased/Added-20241102-002744.yaml new file mode 100644 index 000000000..b7d894747 --- /dev/null +++ b/.changes/unreleased/Added-20241102-002744.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Significantly faster and more accurate docs crawler by default +time: 2024-11-02T00:27:44.408045-07:00 diff --git a/.changes/unreleased/Added-20241108-113942.yaml b/.changes/unreleased/Added-20241108-113942.yaml new file mode 100644 index 000000000..987643345 --- /dev/null +++ b/.changes/unreleased/Added-20241108-113942.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: OpenAI predicted outputs support +time: 2024-11-08T11:39:42.277047-08:00 diff --git a/.changes/unreleased/Added-20241108-114100.yaml b/.changes/unreleased/Added-20241108-114100.yaml new file mode 100644 index 000000000..af7cb5444 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114100.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improve codebase retrieval with BM25 +time: 2024-11-08T11:41:00.002716-08:00 diff --git a/.changes/unreleased/Added-20241108-114423.yaml b/.changes/unreleased/Added-20241108-114423.yaml new file mode 100644 index 000000000..fc3a6eaf7 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114423.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Grok from xAI +time: 2024-11-08T11:44:23.761084-08:00 diff --git a/.changes/unreleased/Added-20241108-114437.yaml b/.changes/unreleased/Added-20241108-114437.yaml new file mode 100644 index 000000000..fab18b954 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114437.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Chat enhancements including sticking input to bottom +time: 2024-11-08T11:44:37.408176-08:00 diff --git a/.changes/unreleased/Added-20241108-114450.yaml b/.changes/unreleased/Added-20241108-114450.yaml new file mode 100644 index 000000000..14644f3e9 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114450.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New UI for cmd+I in sidebar +time: 2024-11-08T11:44:50.682952-08:00 diff --git a/.changes/unreleased/Added-20241108-114612.yaml b/.changes/unreleased/Added-20241108-114612.yaml new file mode 100644 index 000000000..68d8b27d1 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114612.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Nebius LLM provider +time: 2024-11-08T11:46:12.94828-08:00 diff --git a/.changes/unreleased/Added-20241108-114622.yaml b/.changes/unreleased/Added-20241108-114622.yaml new file mode 100644 index 000000000..e91ddb398 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114622.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Ask Sage LLM provider +time: 2024-11-08T11:46:22.626907-08:00 diff --git a/.changes/unreleased/Added-20241108-114649.yaml b/.changes/unreleased/Added-20241108-114649.yaml new file mode 100644 index 000000000..0e7a0c9d0 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114649.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improved reference for config.json +time: 2024-11-08T11:46:49.648545-08:00 diff --git a/.changes/unreleased/Added-20241108-114753.yaml b/.changes/unreleased/Added-20241108-114753.yaml new file mode 100644 index 000000000..8cb7f1805 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114753.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New @web context provider +time: 2024-11-08T11:47:53.447346-08:00 diff --git a/.changes/unreleased/Added-20241108-114813.yaml b/.changes/unreleased/Added-20241108-114813.yaml new file mode 100644 index 000000000..cd5ba1067 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114813.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Updates for llama3.2 +time: 2024-11-08T11:48:13.830692-08:00 diff --git a/.changes/unreleased/Changed-20241014-231738.yaml b/.changes/unreleased/Changed-20241014-231738.yaml deleted file mode 100644 index f0628aad7..000000000 --- a/.changes/unreleased/Changed-20241014-231738.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Changed -body: Easier way to accept/reject/re-prompt after cmd/ctrl+I -time: 2024-10-14T23:17:38.086964-07:00 diff --git a/.changes/unreleased/Changed-20241108-114549.yaml b/.changes/unreleased/Changed-20241108-114549.yaml new file mode 100644 index 000000000..d340736b6 --- /dev/null +++ b/.changes/unreleased/Changed-20241108-114549.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Improved @docs crawler +time: 2024-11-08T11:45:49.381554-08:00 diff --git a/.changes/unreleased/Changed-20241108-114850.yaml b/.changes/unreleased/Changed-20241108-114850.yaml new file mode 100644 index 000000000..ab6c2a037 --- /dev/null +++ b/.changes/unreleased/Changed-20241108-114850.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Many improvements to make autocomplete more eager +time: 2024-11-08T11:48:50.486502-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114322.yaml b/.changes/unreleased/Fixed-20241108-114322.yaml new file mode 100644 index 000000000..e896eac4d --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114322.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: OSR-related fixes for non-Mac users +time: 2024-11-08T11:43:22.623155-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114707.yaml b/.changes/unreleased/Fixed-20241108-114707.yaml new file mode 100644 index 000000000..95c70c844 --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114707.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: Fixes for inline edit in JetBrains +time: 2024-11-08T11:47:07.953304-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114905.yaml b/.changes/unreleased/Fixed-20241108-114905.yaml new file mode 100644 index 000000000..eb590eeb4 --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114905.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Brought back the Apply button for all code blocks +time: 2024-11-08T11:49:05.021499-08:00 diff --git a/.eslintrc.shared.json b/.eslintrc.shared.json new file mode 100644 index 000000000..f4b9c4c78 --- /dev/null +++ b/.eslintrc.shared.json @@ -0,0 +1,36 @@ +{ + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaVersion": 6, + "sourceType": "module" + }, + "plugins": ["@typescript-eslint", "import"], + "rules": { + "@typescript-eslint/semi": "warn", + "curly": "warn", + "eqeqeq": "warn", + "no-throw-literal": "warn", + "semi": "off", + "import/order": [ + "warn", + { + "groups": [ + "builtin", + "external", + "internal", + "parent", + "sibling", + "index", + "object", + "type" + ], + "alphabetize": { + "order": "asc", + "caseInsensitive": true + }, + "newlines-between": "always" + } + ] + }, + "ignorePatterns": ["out", "dist", "**/*.d.ts"] +} diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 1fed6b72b..dce9178bf 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -4,8 +4,8 @@ ## Checklist -- [ ] The base branch of this PR is `dev`, rather than `main` -- [ ] The relevant docs, if any, have been updated or created +- [] The base branch of this PR is `dev`, rather than `main` +- [] The relevant docs, if any, have been updated or created ## Screenshots diff --git a/.github/workflows/auto-assign.yaml b/.github/workflows/auto-assign.yaml index 284dc7f25..3108307e5 100644 --- a/.github/workflows/auto-assign.yaml +++ b/.github/workflows/auto-assign.yaml @@ -16,3 +16,9 @@ jobs: repo-token: ${{ secrets.CI_GITHUB_TOKEN }} assignees: sestinj,Patrick-Erichsen numOfAssignee: 1 + - name: "Add default labels" + uses: actions-ecosystem/action-add-labels@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + labels: | + "needs-triage" diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml index d909a279a..12607a0b9 100644 --- a/.github/workflows/dev_pr.yaml +++ b/.github/workflows/dev_pr.yaml @@ -20,6 +20,12 @@ jobs: with: node-version-file: ".nvmrc" + - name: Cache root node_modules + uses: actions/cache@v3 + with: + path: node_modules + key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }} + - name: Cache extension node_modules uses: actions/cache@v3 with: @@ -44,6 +50,10 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + - name: root install + run: | + npm ci + - name: extensions/vscode install run: | cd extensions/vscode @@ -71,6 +81,7 @@ jobs: run: | cd extensions/vscode npx tsc --noEmit + npm run lint - name: core checks run: | diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 9fc410b38..b28e29c0c 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -97,7 +97,6 @@ jobs: with: node-version-file: ".nvmrc" - # Cache node_modules - name: Cache core node_modules uses: actions/cache@v3 with: diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 459774b74..31b64bae1 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -255,11 +255,3 @@ jobs: # with: # github_token: ${{ secrets.GITHUB_TOKEN }} # branch: ${{ github.ref }} - - # 5 Send to Discord Webhook - - name: Discord Commits - uses: Sniddl/discord-commits@1.7 - with: - webhook: ${{ secrets.DISCORD_WEBHOOK }} - template: "avatar-with-link" - include-extras: true diff --git a/.github/workflows/ts-check.yaml b/.github/workflows/ts-check.yaml index f73016fa5..97bc39d7c 100644 --- a/.github/workflows/ts-check.yaml +++ b/.github/workflows/ts-check.yaml @@ -21,6 +21,12 @@ jobs: with: node-version-file: ".nvmrc" + - name: Cache root node_modules + uses: actions/cache@v3 + with: + path: node_modules + key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }} + - name: Cache extension node_modules uses: actions/cache@v3 with: @@ -45,6 +51,10 @@ jobs: path: binary/node_modules key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + - name: Install Root Dependencies + run: | + npm ci + - name: Install extension Dependencies run: | cd extensions/vscode @@ -72,11 +82,13 @@ jobs: run: | cd core npx tsc --noEmit + npm run lint - name: tsc extensions/vscode run: | cd extensions/vscode npx tsc --noEmit + npm run lint - name: tsc binary run: | diff --git a/.gitignore b/.gitignore index bc9856690..106cef892 100644 --- a/.gitignore +++ b/.gitignore @@ -166,3 +166,6 @@ extensions/intellij/.idea/** **/.idea/workspace.xml **/.idea/usage.statistics.xml **/.idea/shelf/ + +extensions/intellij/bin +extensions/.continue-debug/ \ No newline at end of file diff --git a/.idea/.name b/.idea/.name index c0d78d1d5..389f6bc71 100644 --- a/.idea/.name +++ b/.idea/.name @@ -1 +1 @@ -Continue IntelliJ Extension \ No newline at end of file +continue-intellij-extension \ No newline at end of file diff --git a/.idea/continue.iml b/.idea/continue.iml new file mode 100644 index 000000000..d6ebd4805 --- /dev/null +++ b/.idea/continue.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index efa79f7df..2b4b06721 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -4,7 +4,7 @@ - + diff --git a/.idea/modules.xml b/.idea/modules.xml index 0a26ef9e0..c8a08c311 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -2,9 +2,7 @@ - - - + \ No newline at end of file diff --git a/.idea/scopes/Continue.xml b/.idea/scopes/Continue.xml index dce173a74..3b28a76b1 100644 --- a/.idea/scopes/Continue.xml +++ b/.idea/scopes/Continue.xml @@ -1,3 +1,3 @@ - + \ No newline at end of file diff --git a/.prettierrc b/.prettierrc index 46664808a..7b5484dd7 100644 --- a/.prettierrc +++ b/.prettierrc @@ -2,5 +2,8 @@ "tabWidth": 2, "useTabs": false, "trailingComma": "all", + "semi": true, + "singleQuote": false, + "bracketSpacing": true, "plugins": ["prettier-plugin-tailwindcss"] } diff --git a/.prompts/test.prompt b/.prompts/test.prompt deleted file mode 100644 index e2f5d8662..000000000 --- a/.prompts/test.prompt +++ /dev/null @@ -1,19 +0,0 @@ -temperature: 0.5 -maxTokens: 4096 -name: jest -description: Write Jest unit tests ---- - -You are an expert programmer - - -{{{ input }}} - -Write unit tests for the above selected code, following each of these instructions: -- Use `jest` -- Properly set up and tear down -- Include important edge cases -- The tests should be complete and sophisticated -- Give the tests just as chat output, don't edit any file -- Don't explain how to set up `jest` -- Write a single code block, making sure to label with the language being used (e.g. "```typscript") \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index 60c99a924..dfe474f40 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -20,7 +20,10 @@ "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], "preLaunchTask": "vscode-extension:build", "env": { - "CONTROL_PLANE_ENV": "local" + "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" + // "staging" for the preview deployment "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" + // "local" for entirely local development of control plane/proxy + // "CONTROL_PLANE_ENV": "staging" } }, { @@ -36,7 +39,7 @@ "cwd": "${workspaceFolder}/binary", "env": { "CONTINUE_DEVELOPMENT": "true", - "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/binary/.continue" + "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" } }, { @@ -135,24 +138,5 @@ "NODE_OPTIONS": "--experimental-vm-modules" } } - // { - // "name": "[openai-adapters] Jest Test Debugger, Current Open File", - // "type": "node", - // "request": "launch", - // "runtimeArgs": [ - // "--inspect-brk", - // "${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js", - // "--runInBand", - // "--config", - // "${workspaceRoot}/packages/openai-adapters/jest.config.mjs", - // "${relativeFile}" - // ], - // "cwd": "${workspaceRoot}/packages/openai-adapters", - // "console": "integratedTerminal", - // "internalConsoleOptions": "neverOpen", - // "env": { - // "NODE_OPTIONS": "--experimental-vm-modules" - // } - // } ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index eaf1da238..b77c6d9b0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -14,10 +14,26 @@ } }, "search.exclude": { - "**/core/vendor/**": true, - "**/gui/dist": true, - "**/extensions/vscode/gui/**": true, - "**/extensions/vscode/out/**": true + "**/package-lock.json": true, + "binary/bin/**": true, + "binary/build/**": true, + "binary/out/**": true, + "binary/tmp/**": true, + "core/llm/llamaTokenizer.js": true, + "core/llm/llamaTokenizer.mjs": true, + "core/vendor/**": true, + "docs/.docusaurus/**": true, + "extensions/intellij/build/**": true, + "extensions/vscode/bin/**": true, + "extensions/vscode/build/**": true, + "extensions/vscode/gui/**": true, + "extensions/vscode/models/all-MiniLM-L6-v2/**": true, + "extensions/vscode/out/**": true, + "extensions/vscode/tag-qry/**": true, + "extensions/vscode/textmate-syntaxes/**": true, + "extensions/vscode/tree-sitter/**": true, + "gui/dist/**": true + // "sync/**": true }, "eslint.workingDirectories": ["./core"] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index cbf610b11..8331b5380 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -9,7 +9,7 @@ "vscode-extension:tsc", // To build the React app that is used in the extension "vscode-extension:continue-ui:build", - // To bundle the code the same way we do for publishing + // // To bundle the code the same way we do for publishing "vscode-extension:esbuild", // Start the React app that is used in the extension "gui:dev" @@ -41,7 +41,7 @@ "background": { "activeOnStart": true, "beginsPattern": ">", - "endsPattern": ">" + "endsPattern": "VS Code Extension esbuild complete" } } ] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d813a18a2..d1ca16637 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -200,10 +200,9 @@ Continue has support for more than a dozen different LLM "providers", making it While any model that works with a supported provider can be used with Continue, we keep a list of recommended models that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a model: - [config_schema.json](./extensions/vscode/config_schema.json) - This is the JSON Schema definition that is used to validate `config.json`. You'll notice a number of rules defined in "definitions.ModelDescription.allOf". Here is where you write rules that can specify something like "for the provider 'anthropic', only models 'claude-2' and 'claude-instant-1' are allowed. Look through all of these rules and make sure that your model is included for providers that support it. -- [modelData.ts](./gui/src/util/modelData.ts) - This file defines that information that is shown in the model selection UI in the side bar. To add a new model: - 1. create a `ModelPackage` object, following the lead of the many examples near the top of the file - 2. add the `ModelPackage` to the `MODEL_INFO` array if you would like it to be displayed in the "Models" tab - 3. if you would like it to be displayed as an option under any of the providers, go to the `PROVIDER_INFO` object and add it to the `packages` array for each provider that you want it to be displayed under. If it is an OS model that should be valid for most providers offering OS models, you might just be able to add it to the `osModels` array as shorthand. +- [AddNewModel page](./gui/src/pages/AddNewModel) - This directory defines which model options are shown in the side bar model selection UI. To add a new model: + 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file + 2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed) - [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this. - LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models). - [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates. diff --git a/binary/package-lock.json b/binary/package-lock.json index e4844b8ed..0d67a4725 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -47,12 +47,11 @@ "@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/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", - "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -124,7 +123,6 @@ "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", diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 04097f4db..ce1bc2575 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -1,21 +1,12 @@ { "root": true, - "parser": "@typescript-eslint/parser", + "extends": ["../.eslintrc.shared.json"], "parserOptions": { - "ecmaVersion": 6, - "sourceType": "module", "project": "./tsconfig.json" }, - "plugins": ["@typescript-eslint", "import"], "rules": { "quotes": ["warn", "double", {}], "@typescript-eslint/naming-convention": "off", - "@typescript-eslint/semi": "warn", - "curly": "warn", - "eqeqeq": "warn", - "no-throw-literal": "warn", - "semi": "off", "@typescript-eslint/no-floating-promises": "warn" - }, - "ignorePatterns": ["out", "dist", "**/*.d.ts"] + } } diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts new file mode 100644 index 000000000..cb162043a --- /dev/null +++ b/core/autocomplete/CompletionProvider.ts @@ -0,0 +1,304 @@ +import { ConfigHandler } from "../config/ConfigHandler.js"; +import { IDE, ILLM } from "../index.js"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; +import { constructAutocompletePrompt } from "./constructPrompt.js"; +import { AutocompleteSnippet } from "./context/ranking/index.js"; +import { postprocessCompletion } from "./postprocessing/index.js"; +// @prettier-ignore +import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; +import OpenAI from "../llm/llms/OpenAI.js"; +import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; +import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; +import { CompletionStreamer } from "./generation/CompletionStreamer.js"; +import { shouldPrefilter } from "./prefiltering/index.js"; +import { renderPrompt } from "./templating/index.js"; +import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; +import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; +import AutocompleteLruCache from "./util/AutocompleteLruCache.js"; +import { HelperVars } from "./util/HelperVars.js"; +import { AutocompleteInput, AutocompleteOutcome } from "./util/types.js"; + +const autocompleteCache = AutocompleteLruCache.get(); + +// Errors that can be expected on occasion even during normal functioning should not be shown. +// Not worth disrupting the user to tell them that a single autocomplete request didn't go through +const ERRORS_TO_IGNORE = [ + // From Ollama + "unexpected server status", +]; + +export type GetLspDefinitionsFunction = ( + filepath: string, + contents: string, + cursorIndex: number, + ide: IDE, + lang: AutocompleteLanguageInfo, +) => Promise; + +export class CompletionProvider { + private autocompleteCache = AutocompleteLruCache.get(); + public errorsShown: Set = new Set(); + private bracketMatchingService = new BracketMatchingService(); + private debouncer = new AutocompleteDebouncer(); + private completionStreamer: CompletionStreamer; + private loggingService = new AutocompleteLoggingService(); + private contextRetrievalService: ContextRetrievalService; + + constructor( + private readonly configHandler: ConfigHandler, + private readonly ide: IDE, + private readonly _injectedGetLlm: () => Promise, + private readonly _onError: (e: any) => void, + private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, + ) { + this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); + this.contextRetrievalService = new ContextRetrievalService(this.ide); + } + + private async _prepareLlm(): Promise { + const llm = await this._injectedGetLlm(); + + if (!llm) { + return undefined; + } + + // Ignore empty API keys for Mistral since we currently write + // a template provider without one during onboarding + if (llm.providerName === "mistral" && llm.apiKey === "") { + return undefined; + } + + // Set temperature (but don't override) + if (llm.completionOptions.temperature === undefined) { + llm.completionOptions.temperature = 0.01; + } + + if (llm instanceof OpenAI) { + llm.useLegacyCompletionsEndpoint = true; + } else if ( + llm.providerName === "free-trial" && + llm.model !== TRIAL_FIM_MODEL + ) { + llm.model = TRIAL_FIM_MODEL; + } + + return llm; + } + + private onError(e: any) { + if ( + ERRORS_TO_IGNORE.some((err) => + typeof e === "string" ? e.includes(err) : e?.message?.includes(err), + ) + ) { + return; + } + + console.warn("Error generating autocompletion: ", e); + if (!this.errorsShown.has(e.message)) { + this.errorsShown.add(e.message); + this._onError(e); + } + } + + public cancel() { + this.loggingService.cancel(); + } + + public accept(completionId: string) { + const outcome = this.loggingService.accept(completionId); + if (!outcome) { + return; + } + this.bracketMatchingService.handleAcceptedCompletion( + outcome.completion, + outcome.filepath, + ); + } + + public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { + this.loggingService.markDisplayed(completionId, outcome); + } + + private async _getAutocompleteOptions() { + const config = await this.configHandler.loadConfig(); + const options = { + ...DEFAULT_AUTOCOMPLETE_OPTS, + ...config.tabAutocompleteOptions, + }; + return options; + } + + public async provideInlineCompletionItems( + input: AutocompleteInput, + token: AbortSignal | undefined, + ): Promise { + try { + const startTime = Date.now(); + const options = await this._getAutocompleteOptions(); + + // Debounce + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { + return undefined; + } + + const llm = await this._prepareLlm(); + if (!llm) { + return undefined; + } + + const helper = await HelperVars.create( + input, + options, + llm.model, + this.ide, + ); + + if (await shouldPrefilter(helper, this.ide)) { + return undefined; + } + + // Create abort signal if not given + if (!token) { + const controller = this.loggingService.createAbortController( + input.completionId, + ); + token = controller.signal; + } + + ////////// + + // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, + // or they might separately track recently edited ranges) + const extraSnippets = await this._getExtraSnippets(helper); + + let snippets = await constructAutocompletePrompt( + helper, + extraSnippets, + this.contextRetrievalService, + ); + + const { prompt, prefix, suffix, completionOptions } = renderPrompt( + snippets, + await this.ide.getWorkspaceDirs(), + helper, + ); + + // Completion + let completion: string | undefined = ""; + + const cache = await autocompleteCache; + const cachedCompletion = helper.options.useCache + ? await cache.get(helper.prunedPrefix) + : undefined; + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + const multiline = + !helper.options.transform || shouldCompleteMultiline(helper); + + const completionStream = + this.completionStreamer.streamCompletionWithFilters( + token, + llm, + prefix, + suffix, + prompt, + multiline, + completionOptions, + helper, + ); + + for await (const update of completionStream) { + completion += update; + } + + // Don't postprocess if aborted + if (token.aborted) { + return undefined; + } + + const processedCompletion = helper.options.transform + ? postprocessCompletion({ + completion, + prefix: helper.prunedPrefix, + suffix: helper.prunedSuffix, + llm, + }) + : completion; + + completion = processedCompletion; + } + + if (!completion) { + return undefined; + } + + const outcome: AutocompleteOutcome = { + time: Date.now() - startTime, + completion, + prefix, + suffix, + prompt, + modelProvider: llm.providerName, + modelName: llm.model, + completionOptions, + cacheHit, + filepath: helper.filepath, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + ...helper.options, + }; + + ////////// + + // Do some stuff later so as not to block return. Latency matters + const completionToCache = outcome.completion; + setTimeout(async () => { + if (!outcome.cacheHit) { + (await this.autocompleteCache).put(outcome.prefix, completionToCache); + } + }, 100); + + return outcome; + } catch (e: any) { + this.onError(e); + } finally { + this.loggingService.deleteAbortController(input.completionId); + } + } + + private async _getExtraSnippets( + helper: HelperVars, + ): Promise { + let extraSnippets = helper.options.useOtherFiles + ? ((await Promise.race([ + this.getDefinitionsFromLsp( + helper.input.filepath, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, + this.ide, + helper.lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteSnippet[]) + : []; + + const workspaceDirs = await this.ide.getWorkspaceDirs(); + if (helper.options.onlyMyCode) { + extraSnippets = extraSnippets.filter((snippet) => { + return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); + }); + } + + return extraSnippets; + } +} diff --git a/core/autocomplete/NearbyDefinitionsService.ts b/core/autocomplete/NearbyDefinitionsService.ts deleted file mode 100644 index 53178cba7..000000000 --- a/core/autocomplete/NearbyDefinitionsService.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { IDE, Location } from "../index.js"; -import { LANGUAGES } from "./languages.js"; -import { getSymbolsForSnippet } from "./ranking.js"; - -interface FileInfo { - filepath: string; -} - -export class NearbyDefinitionsService { - static N = 10; - - constructor(private readonly ide: IDE) {} - - async getDefinitionsForLine(filepath: string, line: number) { - const lineContent = await this.ide.readRangeInFile(filepath, { - start: { - line, - character: 0, - }, - end: { - line: line + 1, - character: 0, - }, - }); - - // Remove keywords - const lang = LANGUAGES[filepath.split(".").slice(-1)[0]]; - const symbols = Array.from(getSymbolsForSnippet(lineContent)) - .filter((s) => s.length > 0) - .filter((s) => !(lang && lang?.stopWords?.includes(s))); - - return Promise.all( - symbols.map((s) => { - const character = lineContent.indexOf(s); - const pos: Location = { - filepath, - position: { - line, - character, - }, - }; - }), - ); - } -} diff --git a/core/autocomplete/READEME.md b/core/autocomplete/READEME.md new file mode 100644 index 000000000..d5e822273 --- /dev/null +++ b/core/autocomplete/READEME.md @@ -0,0 +1,9 @@ +TODO + +- The generator reuse thing isn't working it seems + +Tests for context: + +- You need a static set of files to test. Ideally you don't have to rewrite the exact same files every time you want to make a new test. +- So put some example files in a few folders. There should be a folder for each language I think. +- You should definitely test each of the services separately diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index e19509bd8..c02be2b01 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -120,7 +120,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa ### I want better completions, should I use GPT-4? -Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/d2bc6359e8ebf647892ec953e418042dc7f8a685/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. +Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. ### I'm not seeing any completions diff --git a/core/autocomplete/shouldCompleteMultiline.test.ts b/core/autocomplete/classification/shouldCompleteMultiline.test.ts similarity index 100% rename from core/autocomplete/shouldCompleteMultiline.test.ts rename to core/autocomplete/classification/shouldCompleteMultiline.test.ts diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts new file mode 100644 index 000000000..75cfdcd70 --- /dev/null +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -0,0 +1,53 @@ +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { HelperVars } from "../util/HelperVars"; + +function isMidlineCompletion(prefix: string, suffix: string): boolean { + return !suffix.startsWith("\n"); +} + +function shouldCompleteMultilineBasedOnLanguage( + language: AutocompleteLanguageInfo, + prefix: string, + suffix: string, +) { + return language.useMultiline?.({ prefix, suffix }) ?? true; +} + +export function shouldCompleteMultiline(helper: HelperVars) { + switch (helper.options.multilineCompletions) { + case "always": + return true; + case "never": + return false; + default: + break; + } + + // Always single-line if an intellisense option is selected + if (helper.input.selectedCompletionInfo) { + return true; + } + + // // Don't complete multi-line if you are mid-line + // if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { + // return false; + // } + + // Don't complete multi-line for single-line comments + if ( + helper.lang.singleLineComment && + helper.fullPrefix + .split("\n") + .slice(-1)[0] + ?.trimStart() + .startsWith(helper.lang.singleLineComment) + ) { + return false; + } + + return shouldCompleteMultilineBasedOnLanguage( + helper.lang, + helper.prunedPrefix, + helper.prunedSuffix, + ); +} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts deleted file mode 100644 index bc826f934..000000000 --- a/core/autocomplete/completionProvider.ts +++ /dev/null @@ -1,783 +0,0 @@ -import ignore from "ignore"; -import OpenAI from "openai"; -import path from "path"; -import { v4 as uuidv4 } from "uuid"; -import { RangeInFileWithContents } from "../commands/util.js"; -import { ConfigHandler } from "../config/ConfigHandler.js"; -import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; -import { streamLines } from "../diff/util.js"; -import { - IDE, - ILLM, - ModelProvider, - Position, - Range, - TabAutocompleteOptions, -} from "../index.js"; -import { logDevData } from "../util/devdata.js"; -import { getBasename, getLastNPathParts } from "../util/index.js"; -import { - COUNT_COMPLETION_REJECTED_AFTER, - DEFAULT_AUTOCOMPLETE_OPTS, -} from "../util/parameters.js"; -import { Telemetry } from "../util/posthog.js"; -import { getRangeInString } from "../util/ranges.js"; - -import AutocompleteLruCache from "./cache.js"; -import { - constructAutocompletePrompt, - languageForFilepath, -} from "./constructPrompt.js"; -import { isOnlyWhitespace } from "./filter.js"; -import { AutocompleteLanguageInfo } from "./languages.js"; -import { postprocessCompletion } from "./postprocessing.js"; -import { AutocompleteSnippet } from "./ranking.js"; -import { RecentlyEditedRange } from "./recentlyEdited.js"; -import { RootPathContextService } from "./services/RootPathContextService.js"; -import { - avoidPathLineAndEmptyComments, - noTopLevelKeywordsMidline, - skipPrefixes, - stopAtLines, - stopAtRepeatingLines, - stopAtSimilarLine, - streamWithNewLines, -} from "./streamTransforms/lineStream.js"; -import { getTemplateForModel } from "./templates.js"; -import { GeneratorReuseManager } from "./util.js"; -// @prettier-ignore -import Handlebars from "handlebars"; -import { getConfigJsonPath } from "../util/paths.js"; -import { BracketMatchingService } from "./services/BracketMatchingService.js"; -import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; -import { - noFirstCharNewline, - onlyWhitespaceAfterEndOfLine, - stopAtStopTokens, -} from "./streamTransforms/charStream.js"; - -export interface AutocompleteInput { - completionId: string; - filepath: string; - pos: Position; - recentlyEditedFiles: RangeInFileWithContents[]; - recentlyEditedRanges: RecentlyEditedRange[]; - clipboardText: string; - // Used for notebook files - manuallyPassFileContents?: string; - // Used for VS Code git commit input box - manuallyPassPrefix?: string; - selectedCompletionInfo?: { - text: string; - range: Range; - }; - injectDetails?: string; -} - -export interface AutocompleteOutcome extends TabAutocompleteOptions { - accepted?: boolean; - time: number; - prefix: string; - suffix: string; - prompt: string; - completion: string; - modelProvider: string; - modelName: string; - completionOptions: any; - cacheHit: boolean; - filepath: string; - gitRepo?: string; - completionId: string; - uniqueId: string; -} - -const autocompleteCache = AutocompleteLruCache.get(); - -const DOUBLE_NEWLINE = "\n\n"; -const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; -const SRC_DIRECTORY = "/src/"; -// Starcoder2 tends to output artifacts starting with the letter "t" -const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; -const PYTHON_ENCODING = "#- coding: utf-8"; -const CODE_BLOCK_END = "```"; - -const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; -const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; - -// Errors that can be expected on occasion even during normal functioning should not be shown. -// Not worth disrupting the user to tell them that a single autocomplete request didn't go through -const ERRORS_TO_IGNORE = [ - // From Ollama - "unexpected server status", -]; - -function formatExternalSnippet( - filepath: string, - snippet: string, - language: AutocompleteLanguageInfo, -) { - const comment = language.singleLineComment; - const lines = [ - `${comment} Path: ${getBasename(filepath)}`, - ...snippet - .trim() - .split("\n") - .map((line) => `${comment} ${line}`), - comment, - ]; - return lines.join("\n"); -} - -let shownGptClaudeWarning = false; -const nonAutocompleteModels = [ - // "gpt", - // "claude", - "mistral", - "instruct", -]; - -export type GetLspDefinitionsFunction = ( - filepath: string, - contents: string, - cursorIndex: number, - ide: IDE, - lang: AutocompleteLanguageInfo, -) => Promise; - -export class CompletionProvider { - private static debounceTimeout: NodeJS.Timeout | undefined = undefined; - private static debouncing = false; - private static lastUUID: string | undefined = undefined; - - constructor( - private readonly configHandler: ConfigHandler, - private readonly ide: IDE, - private readonly getLlm: () => Promise, - private readonly _onError: (e: any) => void, - private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, - ) { - this.generatorReuseManager = new GeneratorReuseManager( - this.onError.bind(this), - ); - this.importDefinitionsService = new ImportDefinitionsService(this.ide); - this.rootPathContextService = new RootPathContextService( - this.importDefinitionsService, - this.ide, - ); - } - - private importDefinitionsService: ImportDefinitionsService; - private rootPathContextService: RootPathContextService; - private generatorReuseManager: GeneratorReuseManager; - private autocompleteCache = AutocompleteLruCache.get(); - public errorsShown: Set = new Set(); - private bracketMatchingService = new BracketMatchingService(); - // private nearbyDefinitionsService = new NearbyDefinitionsService(); - - private onError(e: any) { - console.warn("Error generating autocompletion: ", e); - if ( - ERRORS_TO_IGNORE.some((err) => - typeof e === "string" ? e.includes(err) : e?.message?.includes(err), - ) - ) { - return; - } - if (!this.errorsShown.has(e.message)) { - this.errorsShown.add(e.message); - this._onError(e); - } - } - - public cancel() { - this._abortControllers.forEach((abortController, id) => { - abortController.abort(); - }); - this._abortControllers.clear(); - } - - // Key is completionId - private _abortControllers = new Map(); - private _logRejectionTimeouts = new Map(); - private _outcomes = new Map(); - - public accept(completionId: string) { - if (this._logRejectionTimeouts.has(completionId)) { - clearTimeout(this._logRejectionTimeouts.get(completionId)); - this._logRejectionTimeouts.delete(completionId); - } - - if (this._outcomes.has(completionId)) { - const outcome = this._outcomes.get(completionId)!; - outcome.accepted = true; - logDevData("autocomplete", outcome); - void Telemetry.capture( - "autocomplete", - { - accepted: outcome.accepted, - modelName: outcome.modelName, - modelProvider: outcome.modelProvider, - time: outcome.time, - cacheHit: outcome.cacheHit, - }, - true, - ); - this._outcomes.delete(completionId); - - this.bracketMatchingService.handleAcceptedCompletion( - outcome.completion, - outcome.filepath, - ); - } - } - - public cancelRejectionTimeout(completionId: string) { - if (this._logRejectionTimeouts.has(completionId)) { - clearTimeout(this._logRejectionTimeouts.get(completionId)!); - this._logRejectionTimeouts.delete(completionId); - } - - if (this._outcomes.has(completionId)) { - this._outcomes.delete(completionId); - } - } - - public async provideInlineCompletionItems( - input: AutocompleteInput, - token: AbortSignal | undefined, - ): Promise { - try { - // Debounce - const uuid = uuidv4(); - CompletionProvider.lastUUID = uuid; - - const config = await this.configHandler.loadConfig(); - const options = { - ...DEFAULT_AUTOCOMPLETE_OPTS, - ...config.tabAutocompleteOptions, - }; - - // Check whether we're in the continue config.json file - if (input.filepath === getConfigJsonPath()) { - return undefined; - } - - // Check whether autocomplete is disabled for this file - if (options.disableInFiles) { - // Relative path needed for `ignore` - const workspaceDirs = await this.ide.getWorkspaceDirs(); - let filepath = input.filepath; - for (const workspaceDir of workspaceDirs) { - if (filepath.startsWith(workspaceDir)) { - filepath = path.relative(workspaceDir, filepath); - break; - } - } - - // Worst case we can check filetype glob patterns - if (filepath === input.filepath) { - filepath = getBasename(filepath); - } - - // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); - if (pattern.ignores(filepath)) { - return undefined; - } - } - - // Create abort signal if not given - if (!token) { - const controller = new AbortController(); - token = controller.signal; - this._abortControllers.set(input.completionId, controller); - } - - // Allow disabling autocomplete from config.json - if (options.disable) { - return undefined; - } - - // Debounce - if (CompletionProvider.debouncing) { - CompletionProvider.debounceTimeout?.refresh(); - const lastUUID = await new Promise((resolve) => - setTimeout(() => { - resolve(CompletionProvider.lastUUID); - }, options.debounceDelay), - ); - if (uuid !== lastUUID) { - return undefined; - } - } else { - CompletionProvider.debouncing = true; - CompletionProvider.debounceTimeout = setTimeout(async () => { - CompletionProvider.debouncing = false; - }, options.debounceDelay); - } - - // Get completion - const llm = await this.getLlm(); - - if (!llm) { - return undefined; - } - - // Ignore empty API keys for Mistral since we currently write - // a template provider without one during onboarding - if (llm.providerName === "mistral" && llm.apiKey === "") { - return undefined; - } - - // Set temperature (but don't overrride) - if (llm.completionOptions.temperature === undefined) { - llm.completionOptions.temperature = 0.01; - } - - // Set model-specific options - const LOCAL_PROVIDERS: ModelProvider[] = [ - "ollama", - "lmstudio", - "llama.cpp", - "llamafile", - "text-gen-webui", - ]; - if ( - !config.tabAutocompleteOptions?.maxPromptTokens && - LOCAL_PROVIDERS.includes(llm.providerName) - ) { - options.maxPromptTokens = 500; - } - - const outcome = await this.getTabCompletion(token, options, llm, input); - - if (!outcome?.completion) { - return undefined; - } - - /** - * This check is most likely not needed because we do trim the LLM output - * elsewhere in the code. That said, I'm not yet confident enough to - * remove this. - */ - if (isOnlyWhitespace(outcome.completion)) { - return undefined; - } - - // Do some stuff later so as not to block return. Latency matters - const completionToCache = outcome.completion; - setTimeout(async () => { - if (!outcome.cacheHit) { - (await this.autocompleteCache).put(outcome.prefix, completionToCache); - } - }, 100); - - return outcome; - } catch (e: any) { - this.onError(e); - } finally { - this._abortControllers.delete(input.completionId); - } - } - - _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined = - undefined; - - markDisplayed(completionId: string, outcome: AutocompleteOutcome) { - const logRejectionTimeout = setTimeout(() => { - // Wait 10 seconds, then assume it wasn't accepted - outcome.accepted = false; - logDevData("autocomplete", outcome); - const { prompt, completion, ...restOfOutcome } = outcome; - void Telemetry.capture( - "autocomplete", - { - ...restOfOutcome, - }, - true, - ); - this._logRejectionTimeouts.delete(completionId); - }, COUNT_COMPLETION_REJECTED_AFTER); - this._outcomes.set(completionId, outcome); - this._logRejectionTimeouts.set(completionId, logRejectionTimeout); - - // If the previously displayed completion is still waiting for rejection, - // and this one is a continuation of that (the outcome.completion is the same modulo prefix) - // then we should cancel the rejection timeout - const previous = this._lastDisplayedCompletion; - const now = Date.now(); - if (previous && this._logRejectionTimeouts.has(previous.id)) { - const previousOutcome = this._outcomes.get(previous.id); - const c1 = previousOutcome?.completion.split("\n")[0] ?? ""; - const c2 = outcome.completion.split("\n")[0]; - if ( - previousOutcome && - (c1.endsWith(c2) || - c2.endsWith(c1) || - c1.startsWith(c2) || - c2.startsWith(c1)) - ) { - this.cancelRejectionTimeout(previous.id); - } else if (now - previous.displayedAt < 500) { - // If a completion isn't shown for more than - this.cancelRejectionTimeout(previous.id); - } - } - - this._lastDisplayedCompletion = { - id: completionId, - displayedAt: now, - }; - } - - async getTabCompletion( - token: AbortSignal, - options: TabAutocompleteOptions, - llm: ILLM, - input: AutocompleteInput, - ): Promise { - const startTime = Date.now(); - - const { - filepath, - pos, - recentlyEditedFiles, - recentlyEditedRanges, - clipboardText, - manuallyPassFileContents, - manuallyPassPrefix, - } = input; - const fileContents = - manuallyPassFileContents ?? (await this.ide.readFile(filepath)); - const fileLines = fileContents.split("\n"); - - // Filter - const lang = languageForFilepath(filepath); - const line = fileLines[pos.line] ?? ""; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= line.length) { - return undefined; - } - } - - // Model - if (!llm) { - return; - } - if (llm instanceof OpenAI) { - llm.useLegacyCompletionsEndpoint = true; - } else if ( - llm.providerName === "free-trial" && - llm.model !== TRIAL_FIM_MODEL - ) { - llm.model = TRIAL_FIM_MODEL; - } - - if ( - !shownGptClaudeWarning && - nonAutocompleteModels.some((model) => llm.model.includes(model)) && - !llm.model.toLowerCase().includes("deepseek") && - !llm.model.toLowerCase().includes("codestral") - ) { - shownGptClaudeWarning = true; - throw new Error( - `Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`, - ); - } - - // Prompt - let fullPrefix = - getRangeInString(fileContents, { - start: { line: 0, character: 0 }, - end: input.selectedCompletionInfo?.range.start ?? pos, - }) + (input.selectedCompletionInfo?.text ?? ""); - - if (input.injectDetails) { - const lines = fullPrefix.split("\n"); - fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ - lang.singleLineComment - } ${input.injectDetails - .split("\n") - .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; - } - - const fullSuffix = getRangeInString(fileContents, { - start: pos, - end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, - }); - - // First non-whitespace line below the cursor - let lineBelowCursor = ""; - let i = 1; - while ( - lineBelowCursor.trim() === "" && - pos.line + i <= fileLines.length - 1 - ) { - lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; - i++; - } - - let extrasSnippets = options.useOtherFiles - ? ((await Promise.race([ - this.getDefinitionsFromLsp( - filepath, - fullPrefix + fullSuffix, - fullPrefix.length, - this.ide, - lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]) - : []; - - const workspaceDirs = await this.ide.getWorkspaceDirs(); - if (options.onlyMyCode) { - extrasSnippets = extrasSnippets.filter((snippet) => { - return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); - }); - } - - let { prefix, suffix, completeMultiline, snippets } = - await constructAutocompletePrompt( - filepath, - pos.line, - fullPrefix, - fullSuffix, - clipboardText, - lang, - options, - recentlyEditedRanges, - recentlyEditedFiles, - llm.model, - extrasSnippets, - this.importDefinitionsService, - this.rootPathContextService, - ); - - // If prefix is manually passed - if (manuallyPassPrefix) { - prefix = manuallyPassPrefix; - suffix = ""; - } - - // Template prompt - const { - template, - completionOptions, - compilePrefixSuffix = undefined, - } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); - - let prompt: string; - const filename = getBasename(filepath); - const reponame = getBasename(workspaceDirs[0] ?? "myproject"); - - // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix - // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint - if (compilePrefixSuffix) { - [prefix, suffix] = compilePrefixSuffix( - prefix, - suffix, - filepath, - reponame, - snippets, - ); - } - - if (typeof template === "string") { - const compiledTemplate = Handlebars.compile(template); - - // Format snippets as comments and prepend to prefix - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - prefix = `${formattedSnippets}\n\n${prefix}`; - } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { - // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts( - filepath, - 2, - )}\n${prefix}`; - } - - prompt = compiledTemplate({ - prefix, - suffix, - filename, - reponame, - language: lang.name, - }); - } else { - // Let the template function format snippets - prompt = template( - prefix, - suffix, - filepath, - reponame, - lang.name, - snippets, - ); - } - - // Completion - let completion = ""; - - const cache = await autocompleteCache; - const cachedCompletion = options.useCache - ? await cache.get(prefix) - : undefined; - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; - } else { - const stop = [ - ...(completionOptions?.stop || []), - ...multilineStops, - ...commonStops, - ...(llm.model.toLowerCase().includes("starcoder2") - ? STARCODER2_T_ARTIFACTS - : []), - ...(lang.stopWords ?? []), - ...lang.topLevelKeywords.map((word) => `\n${word}`), - ]; - - let langMultilineDecision = lang.useMultiline?.({ prefix, suffix }); - let multiline: boolean = false; - if (langMultilineDecision) { - multiline = langMultilineDecision; - } else { - multiline = - !input.selectedCompletionInfo && // Only ever single-line if using intellisense selected value - options.multilineCompletions !== "never" && - (options.multilineCompletions === "always" || completeMultiline); - } - - // Try to reuse pending requests if what the user typed matches start of completion - const generator = this.generatorReuseManager.getGenerator( - prefix, - () => - llm.supportsFim() - ? llm.streamFim(prefix, suffix, { - ...completionOptions, - stop, - }) - : llm.streamComplete(prompt, { - ...completionOptions, - raw: true, - stop, - }), - multiline, - ); - - // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion - const fullStop = () => - this.generatorReuseManager.currentGenerator?.cancel(); - - // LLM - let cancelled = false; - const generatorWithCancellation = async function* () { - for await (const update of generator) { - if (token.aborted) { - cancelled = true; - return; - } - yield update; - } - }; - let charGenerator = generatorWithCancellation(); - charGenerator = noFirstCharNewline(charGenerator); - charGenerator = onlyWhitespaceAfterEndOfLine( - charGenerator, - lang.endOfLine, - fullStop, - ); - charGenerator = stopAtStopTokens(charGenerator, stop); - charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, - prefix, - suffix, - filepath, - multiline, - ); - - let lineGenerator = streamLines(charGenerator); - lineGenerator = stopAtLines(lineGenerator, fullStop); - lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLineAndEmptyComments( - lineGenerator, - lang.singleLineComment, - ); - lineGenerator = skipPrefixes(lineGenerator); - lineGenerator = noTopLevelKeywordsMidline( - lineGenerator, - lang.topLevelKeywords, - fullStop, - ); - - for (const lineFilter of lang.lineFilters ?? []) { - lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); - } - - lineGenerator = streamWithNewLines(lineGenerator); - - const finalGenerator = stopAtSimilarLine( - lineGenerator, - lineBelowCursor, - fullStop, - ); - - try { - for await (const update of finalGenerator) { - completion += update; - } - } catch (e: any) { - if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) { - return undefined; - } - throw e; - } - - if (cancelled) { - return undefined; - } - - const processedCompletion = postprocessCompletion({ - completion, - prefix, - suffix, - llm, - }); - - if (!processedCompletion) { - return undefined; - } - completion = processedCompletion; - } - - const time = Date.now() - startTime; - return { - time, - completion, - prefix, - suffix, - prompt, - modelProvider: llm.providerName, - modelName: llm.model, - completionOptions, - cacheHit, - filepath: input.filepath, - completionId: input.completionId, - gitRepo: await this.ide.getRepoName(input.filepath), - uniqueId: await this.ide.getUniqueId(), - ...options, - }; - } -} diff --git a/core/autocomplete/languages.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts similarity index 85% rename from core/autocomplete/languages.ts rename to core/autocomplete/constants/AutocompleteLanguageInfo.ts index be414098a..18bbf2ff9 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -1,16 +1,18 @@ -import { LineFilter } from "./streamTransforms/lineStream"; +import { BracketMatchingService } from "../filtering/BracketMatchingService"; +import { + CharacterFilter, + LineFilter, +} from "../filtering/streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; topLevelKeywords: string[]; - singleLineComment: string; + singleLineComment?: string; endOfLine: string[]; stopWords?: string[]; lineFilters?: LineFilter[]; - useMultiline?: (args: { - prefix: string; - suffix: string; - }) => boolean | undefined; + charFilters?: CharacterFilter[]; + useMultiline?: (args: { prefix: string; suffix: string }) => boolean; } // TypeScript @@ -256,10 +258,8 @@ export const YAML: AutocompleteLanguageInfo = { } else { seenListItem = true; } - yield line; - } else { - yield line; } + yield line; } }, // Don't allow consecutive lines of same key @@ -268,18 +268,39 @@ export const YAML: AutocompleteLanguageInfo = { for await (const line of lines) { if (line.includes(":")) { const key = line.split(":")[0]; - if (key !== lastKey) { + if (key === lastKey) { + break; + } else { yield line; lastKey = key; - } else { - break; } + } else { + yield line; } } }, ], }; +export const Json: AutocompleteLanguageInfo = { + name: "JSON", + topLevelKeywords: [], + singleLineComment: "//", + endOfLine: [",", "}", "]"], + charFilters: [ + function matchBrackets({ chars, prefix, suffix, filepath, multiline }) { + const bracketMatchingService = new BracketMatchingService(); + return bracketMatchingService.stopOnUnmatchedClosingBracket( + chars, + prefix, + suffix, + filepath, + multiline, + ); + }, + ], +}; + export const Markdown: AutocompleteLanguageInfo = { name: "Markdown", topLevelKeywords: [], @@ -289,7 +310,7 @@ export const Markdown: AutocompleteLanguageInfo = { const singleLineStarters = ["- ", "* ", /^\d+\. /, "> ", "```", /^#{1,6} /]; let currentLine = prefix.split("\n").pop(); if (!currentLine) { - return undefined; + return true; } currentLine = currentLine.trim(); for (const starter of singleLineStarters) { @@ -301,7 +322,7 @@ export const Markdown: AutocompleteLanguageInfo = { return false; } } - return undefined; + return true; }, }; @@ -309,6 +330,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { ts: Typescript, js: Typescript, tsx: Typescript, + json: Json, jsx: Typescript, ipynb: Python, py: Python, @@ -346,3 +368,9 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { yml: YAML, md: Markdown, }; + +export function languageForFilepath( + filepath: string, +): AutocompleteLanguageInfo { + return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript; +} diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 17b78fa01..2c5d43f42 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,215 +1,87 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { TabAutocompleteOptions } from "../index.js"; - -import { - countTokens, - pruneLinesFromBottom, - pruneLinesFromTop, -} from "../llm/countTokens.js"; -import { AstPath, getAst, getTreePathAtCursor } from "./ast.js"; -import { - AutocompleteLanguageInfo, - LANGUAGES, - Typescript, -} from "./languages.js"; +import { Position, Range } from "../index.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, - getSymbolsForSnippet, - rankSnippets, + rankAndOrderSnippets, removeRangeFromSnippets, type AutocompleteSnippet, -} from "./ranking.js"; -import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; -import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; -import { RootPathContextService } from "./services/RootPathContextService.js"; -import { shouldCompleteMultiline } from "./shouldCompleteMultiline.js"; +} from "./context/ranking/index.js"; +import { HelperVars } from "./util/HelperVars.js"; -export function languageForFilepath( - filepath: string, -): AutocompleteLanguageInfo { - return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript; +function filterSnippetsAlreadyInCaretWindow( + snippets: AutocompleteSnippet[], + caretWindow: string, +): AutocompleteSnippet[] { + return snippets + .map((snippet) => ({ ...snippet })) + .filter( + (s) => + s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), + ); +} + +function getRangeOfPrefixAndSuffixWithBuffer( + prefix: string, + suffix: string, + caretPos: Position, +): Range { + // Remove prefix range from snippets + const prefixLines = prefix.split("\n").length; + const suffixLines = suffix.split("\n").length; + const buffer = 8; + const prefixSuffixRangeWithBuffer = { + start: { + line: caretPos.line - prefixLines - buffer, + character: 0, + }, + end: { + line: caretPos.line + suffixLines + buffer, + character: 0, + }, + }; + + return prefixSuffixRangeWithBuffer; } export async function constructAutocompletePrompt( - filepath: string, - cursorLine: number, - fullPrefix: string, - fullSuffix: string, - clipboardText: string, - language: AutocompleteLanguageInfo, - options: TabAutocompleteOptions, - recentlyEditedRanges: RecentlyEditedRange[], - recentlyEditedFiles: RangeInFileWithContents[], - modelName: string, + helper: HelperVars, extraSnippets: AutocompleteSnippet[], - importDefinitionsService: ImportDefinitionsService, - rootPathContextService: RootPathContextService, -): Promise<{ - prefix: string; - suffix: string; - useFim: boolean; - completeMultiline: boolean; - snippets: AutocompleteSnippet[]; -}> { - // Construct basic prefix - const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage; - const prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName); - - // Construct suffix - const maxSuffixTokens = Math.min( - options.maxPromptTokens - countTokens(prefix, modelName), - options.maxSuffixPercentage * options.maxPromptTokens, + contextRetrievalService: ContextRetrievalService, +): Promise { + let snippets = await contextRetrievalService.retrieveCandidateSnippets( + helper, + extraSnippets, ); - const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); - // Calculate AST Path - let treePath: AstPath | undefined; - try { - const ast = await getAst(filepath, fullPrefix + fullSuffix); - if (ast) { - treePath = await getTreePathAtCursor(ast, fullPrefix.length); - } - } catch (e) { - console.error("Failed to parse AST", e); - } - - // Find external snippets - let snippets: AutocompleteSnippet[] = []; - - if (options.useOtherFiles) { - snippets.push(...extraSnippets); - - const windowAroundCursor = - fullPrefix.slice( - -options.slidingWindowSize * options.slidingWindowPrefixPercentage, - ) + - fullSuffix.slice( - options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage), - ); - - // This was much too slow, and not super useful - // const slidingWindowMatches = await slidingWindowMatcher( - // recentlyEditedFiles, - // windowAroundCursor, - // 3, - // options.slidingWindowSize, - // ); - // snippets.push(...slidingWindowMatches); - - // snippets.push( - // ...recentlyEditedRanges.map((r) => ({ - // ...r, - // contents: r.lines.join("\n"), - // })), - // ); - - if (options.useRecentlyEdited) { - const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0]; - if (currentLinePrefix?.length > options.recentLinePrefixMatchMinLength) { - const matchingRange = findMatchingRange( - recentlyEditedRanges, - currentLinePrefix, - ); - if (matchingRange) { - snippets.push({ - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }); - } - } - } - - // Use imports - if (options.useImports) { - const importSnippets = []; - const fileInfo = importDefinitionsService.get(filepath); - if (fileInfo) { - const { imports } = fileInfo; - // Look for imports of any symbols around the current range - const textAroundCursor = - fullPrefix.split("\n").slice(-5).join("\n") + - fullSuffix.split("\n").slice(0, 3).join("\n"); - const symbols = Array.from( - getSymbolsForSnippet(textAroundCursor), - ).filter((symbol) => !language.topLevelKeywords.includes(symbol)); - for (const symbol of symbols) { - const rifs = imports[symbol]; - if (Array.isArray(rifs)) { - importSnippets.push(...rifs); - } - } - } - snippets.push(...importSnippets); - } - - if (options.useRootPathContext && treePath) { - const ctx = await rootPathContextService.getContextForPath( - filepath, - treePath, - ); - snippets.push(...ctx); - } - - // Filter out empty snippets and ones that are already in the prefix/suffix - snippets = snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && - !(prefix + suffix).includes(s.contents.trim()), - ); - - // Rank / order the snippets - const scoredSnippets = rankSnippets(snippets, windowAroundCursor); - - // Fill maxSnippetTokens with snippets - const maxSnippetTokens = - options.maxPromptTokens * options.maxSnippetPercentage; - - // Remove prefix range from snippets - const prefixLines = prefix.split("\n").length; - const suffixLines = suffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: cursorLine - prefixLines - buffer, - character: 0, - }, - end: { - line: cursorLine + suffixLines + buffer, - character: 0, - }, - }; - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - filepath.split("://").slice(-1)[0], - prefixSuffixRangeWithBuffer, - ); - - // Filter snippets for those with best scores (must be above threshold) - finalSnippets = finalSnippets.filter( - (snippet) => snippet.score >= options.recentlyEditedSimilarityThreshold, - ); - finalSnippets = fillPromptWithSnippets( - scoredSnippets, - maxSnippetTokens, - modelName, - ); - - snippets = finalSnippets; - } - - return { - prefix, - suffix, - useFim: true, - completeMultiline: await shouldCompleteMultiline( - treePath, - fullPrefix, - fullSuffix, - language, - ), + snippets = filterSnippetsAlreadyInCaretWindow( snippets, - }; + helper.prunedCaretWindow, + ); + + const scoredSnippets = rankAndOrderSnippets(snippets, helper); + + // This might be redundant with filterSnippetsAlreadyInCaretWindow + let finalSnippets = removeRangeFromSnippets( + scoredSnippets, + helper.filepath.split("://").slice(-1)[0], + getRangeOfPrefixAndSuffixWithBuffer( + helper.prunedPrefix, + helper.prunedSuffix, + helper.pos, + ), + ); + + // Filter snippets below similarity threshold + finalSnippets = finalSnippets.filter( + (snippet) => + snippet.score >= helper.options.recentlyEditedSimilarityThreshold, + ); + + finalSnippets = fillPromptWithSnippets( + scoredSnippets, + helper.maxSnippetTokens, + helper.modelName, + ); + + return finalSnippets; } diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts new file mode 100644 index 000000000..a12d1962e --- /dev/null +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -0,0 +1,123 @@ +import { IDE } from "../.."; +import { HelperVars } from "../util/HelperVars"; +import { RecentlyEditedRange } from "../util/types"; +import { ImportDefinitionsService } from "./ImportDefinitionsService"; +import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; +import { RootPathContextService } from "./root-path-context/RootPathContextService"; + +export class ContextRetrievalService { + private importDefinitionsService: ImportDefinitionsService; + private rootPathContextService: RootPathContextService; + + constructor(private readonly ide: IDE) { + this.importDefinitionsService = new ImportDefinitionsService(this.ide); + this.rootPathContextService = new RootPathContextService( + this.importDefinitionsService, + this.ide, + ); + } + + public async retrieveCandidateSnippets( + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + ) { + if (helper.options.useOtherFiles === false) { + return []; + } + + let snippets: AutocompleteSnippet[] = []; + + // Snippets injected by the IDE for IDE-specific reasons + snippets.push(...extraSnippets); + + // If a recently edited range has a line that is a perfect match with the start of the current line + snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper)); + + // Import definitions of any symbols in near range of the caret + snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); + + // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ + if (helper.options.useRootPathContext && helper.treePath) { + snippets.push( + ...(await this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + )), + ); + } + + return snippets; + } + + private getSnippetsFromRecentlyEditedRanges( + helper: HelperVars, + ): AutocompleteSnippet[] { + if (helper.options.useRecentlyEdited === false) { + return []; + } + + const currentLinePrefix = helper.prunedPrefix + .trim() + .split("\n") + .slice(-1)[0]; + if ( + currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength + ) { + const matchingRange = this.findMatchingRange( + helper.input.recentlyEditedRanges, + currentLinePrefix, + ); + + if (matchingRange) { + return [ + { + ...matchingRange, + contents: matchingRange.lines.join("\n"), + score: 0.8, + }, + ]; + } + } + + return []; + } + + private async getSnippetsFromImportDefinitions( + helper: HelperVars, + ): Promise { + if (helper.options.useImports === false) { + return []; + } + + const importSnippets = []; + const fileInfo = this.importDefinitionsService.get(helper.filepath); + if (fileInfo) { + const { imports } = fileInfo; + // Look for imports of any symbols around the current range + const textAroundCursor = + helper.fullPrefix.split("\n").slice(-5).join("\n") + + helper.fullSuffix.split("\n").slice(0, 3).join("\n"); + const symbols = Array.from(getSymbolsForSnippet(textAroundCursor)).filter( + (symbol) => !helper.lang.topLevelKeywords.includes(symbol), + ); + for (const symbol of symbols) { + const rifs = imports[symbol]; + if (Array.isArray(rifs)) { + importSnippets.push(...rifs); + } + } + } + return importSnippets; + } + + findMatchingRange( + recentlyEditedRanges: RecentlyEditedRange[], + linePrefix: string, + ): RecentlyEditedRange | undefined { + return recentlyEditedRanges.find((recentlyEditedRange) => { + return recentlyEditedRange.lines.some((line) => + line.startsWith(linePrefix), + ); + }); + } +} diff --git a/core/autocomplete/services/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts similarity index 100% rename from core/autocomplete/services/ImportDefinitionsService.ts rename to core/autocomplete/context/ImportDefinitionsService.ts diff --git a/core/autocomplete/services/NearbyDefinitionsService.ts b/core/autocomplete/context/NearbyDefinitionsService.ts similarity index 89% rename from core/autocomplete/services/NearbyDefinitionsService.ts rename to core/autocomplete/context/NearbyDefinitionsService.ts index 12d6f7947..6e4cece83 100644 --- a/core/autocomplete/services/NearbyDefinitionsService.ts +++ b/core/autocomplete/context/NearbyDefinitionsService.ts @@ -1,6 +1,6 @@ import { IDE, Location } from "../.."; -import { LANGUAGES } from "../languages"; -import { getSymbolsForSnippet } from "../ranking"; +import { LANGUAGES } from "../constants/AutocompleteLanguageInfo"; +import { getSymbolsForSnippet } from "./ranking"; interface FileInfo { filepath: string; diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/context/ranking/index.ts similarity index 89% rename from core/autocomplete/ranking.ts rename to core/autocomplete/context/ranking/index.ts index 48e01d5ff..e761d994e 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,6 +1,7 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { Range } from "../index.js"; -import { countTokens } from "../llm/countTokens.js"; +import { RangeInFileWithContents } from "../../../commands/util.js"; +import { Range } from "../../../index.js"; +import { countTokens } from "../../../llm/countTokens.js"; +import { HelperVars } from "../../util/HelperVars.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; @@ -41,10 +42,20 @@ export function jaccardSimilarity(a: string, b: string): number { /** * Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array. */ -export function rankSnippets( +export function rankAndOrderSnippets( ranges: AutocompleteSnippet[], - windowAroundCursor: string, + helper: HelperVars, ): Required[] { + const windowAroundCursor = + helper.fullPrefix.slice( + -helper.options.slidingWindowSize * + helper.options.slidingWindowPrefixPercentage, + ) + + helper.fullSuffix.slice( + helper.options.slidingWindowSize * + (1 - helper.options.slidingWindowPrefixPercentage), + ); + const snippets: Required[] = ranges.map((snippet) => ({ score: snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor), @@ -119,7 +130,8 @@ function mergeOverlappingRangeContents( } /** - * Fill the allowed space with snippets + * Fill the allowed space with snippets. + * It is assumed that the snippets are sorted by score. */ export function fillPromptWithSnippets( snippets: Required[], diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts similarity index 91% rename from core/autocomplete/slidingWindow.ts rename to core/autocomplete/context/ranking/slidingWindow.ts index 72aa1a5ee..54ec763f2 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,5 +1,5 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { AutocompleteSnippet, jaccardSimilarity } from "./ranking.js"; +import { RangeInFileWithContents } from "../../../commands/util.js"; +import { AutocompleteSnippet, jaccardSimilarity } from "./index.js"; function* slidingWindow( content: string, diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts new file mode 100644 index 000000000..ccce0b6ac --- /dev/null +++ b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts @@ -0,0 +1,97 @@ +import fs from "fs"; +import path from "path"; +import { Range } from "../../.."; +import { testIde } from "../../../test/util/fixtures"; +import { getAst, getTreePathAtCursor } from "../../util/ast"; +import { ImportDefinitionsService } from "../ImportDefinitionsService"; +import { RootPathContextService } from "./RootPathContextService"; + +function splitTextAtRange(fileContent: string, range: Range): [string, string] { + const lines = fileContent.split("\n"); + let currentPos = 0; + + if (range.start.line === range.end.line) { + // If range is on the same line, calculate position once + for (let i = 0; i < range.start.line; i++) { + currentPos += lines[i].length + 1; // +1 for the newline character + } + const startPos = currentPos + range.start.character; + const endPos = currentPos + range.end.character; + return [fileContent.slice(0, startPos), fileContent.slice(endPos)]; + } + + // Calculate position of range start + for (let i = 0; i < range.start.line; i++) { + currentPos += lines[i].length + 1; + } + const startPos = currentPos + range.start.character; + + // Calculate position of range end + currentPos = 0; + for (let i = 0; i < range.end.line; i++) { + currentPos += lines[i].length + 1; + } + const endPos = currentPos + range.end.character; + + return [fileContent.slice(0, startPos), fileContent.slice(endPos)]; +} + +export async function testRootPathContext( + folderName: string, + relativeFilepath: string, + rangeToFill: Range, + expectedSnippets: string[], +) { + const ide = testIde; + const importDefinitionsService = new ImportDefinitionsService(ide); + const service = new RootPathContextService(importDefinitionsService, ide); + + // Copy the folder to the test directory + const folderPath = path.join( + __dirname, + "autocomplete", + "context", + "root-path-context", + "test", + folderName, + ); + const workspaceDir = (await ide.getWorkspaceDirs())[0]; + const testFolderPath = path.join(workspaceDir, folderName); + fs.cpSync(folderPath, testFolderPath, { + recursive: true, + force: true, + }); + + // Get results of root path context + const startPath = path.join(testFolderPath, relativeFilepath); + const [prefix, suffix] = splitTextAtRange( + fs.readFileSync(startPath, "utf8"), + rangeToFill, + ); + const fileContents = prefix + suffix; + const ast = await getAst(startPath, fileContents); + if (!ast) { + throw new Error("AST is undefined"); + } + + const treePath = await getTreePathAtCursor(ast, prefix.length); + const snippets = await service.getContextForPath(startPath, treePath); + + expectedSnippets.forEach((expectedSnippet) => { + const found = snippets.find((snippet) => + snippet.contents.includes(expectedSnippet), + ); + expect(found).toBeDefined(); + }); +} + +describe("RootPathContextService", () => { + it("should be true", async () => { + await testRootPathContext( + "typescript", + "file1.ts", + { start: { line: 3, character: 2 }, end: { line: 3, character: 24 } }, + ["export interface Person", "export interface Address"], + ); + }); +}); diff --git a/core/autocomplete/services/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts similarity index 93% rename from core/autocomplete/services/RootPathContextService.ts rename to core/autocomplete/context/root-path-context/RootPathContextService.ts index 69426aab8..ba99b2e83 100644 --- a/core/autocomplete/services/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -1,11 +1,11 @@ import { createHash } from "crypto"; import { LRUCache } from "lru-cache"; import Parser from "web-tree-sitter"; -import { IDE } from "../.."; -import { getQueryForFile, TSQueryType } from "../../util/treeSitter"; -import { AstPath } from "../ast"; +import { IDE } from "../../.."; +import { getQueryForFile, TSQueryType } from "../../../util/treeSitter"; +import { AstPath } from "../../util/ast"; +import { ImportDefinitionsService } from "../ImportDefinitionsService"; import { AutocompleteSnippet } from "../ranking"; -import { ImportDefinitionsService } from "./ImportDefinitionsService"; export class RootPathContextService { private cache = new LRUCache({ diff --git a/core/autocomplete/context/root-path-context/test/typescript/file1.ts b/core/autocomplete/context/root-path-context/test/typescript/file1.ts new file mode 100644 index 000000000..c67ae91e2 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/typescript/file1.ts @@ -0,0 +1,13 @@ +import { Address, Person } from "./types"; + +function getAddress(person: Person): Address { + return person.address; +} + +class Group { + people: Person[]; + + constructor(people: Person[]) { + this.people = people; + } +} diff --git a/core/autocomplete/context/root-path-context/test/typescript/types.ts b/core/autocomplete/context/root-path-context/test/typescript/types.ts new file mode 100644 index 000000000..272ec27d7 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/typescript/types.ts @@ -0,0 +1,11 @@ +export interface Person { + firstName: string; + lastName: string; + age: number; + address: Address; +} + +export interface Address { + street: string; + city: string; +} diff --git a/core/autocomplete/filter.ts b/core/autocomplete/filter.ts deleted file mode 100644 index 5b2b66df0..000000000 --- a/core/autocomplete/filter.ts +++ /dev/null @@ -1,4 +0,0 @@ -export function isOnlyWhitespace(completion: string): boolean { - const whitespaceRegex = /^[\s]+$/; - return whitespaceRegex.test(completion); -} diff --git a/core/autocomplete/services/BracketMatchingService.ts b/core/autocomplete/filtering/BracketMatchingService.ts similarity index 97% rename from core/autocomplete/services/BracketMatchingService.ts rename to core/autocomplete/filtering/BracketMatchingService.ts index 3734df2be..d4415259e 100644 --- a/core/autocomplete/services/BracketMatchingService.ts +++ b/core/autocomplete/filtering/BracketMatchingService.ts @@ -84,9 +84,13 @@ export class BracketMatchingService { // Add corresponding open brackets from suffix to stack // because we overwrite them and the diff is displayed, and this allows something to be edited after that for (let i = 0; i < suffix.length; i++) { - if (suffix[i] === " ") {continue;} + if (suffix[i] === " ") { + continue; + } const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; - if (!openBracket) {break;} + if (!openBracket) { + break; + } stack.unshift(openBracket); } diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts new file mode 100644 index 000000000..8d7f3e23f --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -0,0 +1,87 @@ +import { streamLines } from "../../../diff/util"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters"; +import { HelperVars } from "../../util/HelperVars"; +import { stopAtStopTokens } from "./charStream"; +import { + avoidEmptyComments, + avoidPathLine, + showWhateverWeHaveAtXMs, + skipPrefixes, + stopAtLines, + stopAtRepeatingLines, + stopAtSimilarLine, + streamWithNewLines, +} from "./lineStream"; + +export class StreamTransformPipeline { + async *transform( + generator: AsyncGenerator, + prefix: string, + suffix: string, + multiline: boolean, + stopTokens: string[], + fullStop: () => void, + helper: HelperVars, + ): AsyncGenerator { + let charGenerator = generator; + + charGenerator = stopAtStopTokens(generator, stopTokens); + for (const charFilter of helper.lang.charFilters ?? []) { + charGenerator = charFilter({ + chars: charGenerator, + prefix, + suffix, + filepath: helper.filepath, + multiline, + }); + } + + let lineGenerator = streamLines(charGenerator); + + lineGenerator = stopAtLines(lineGenerator, fullStop); + lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); + lineGenerator = avoidEmptyComments( + lineGenerator, + helper.lang.singleLineComment, + ); + lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); + lineGenerator = skipPrefixes(lineGenerator); + + for (const lineFilter of helper.lang.lineFilters ?? []) { + lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); + } + + lineGenerator = stopAtSimilarLine( + lineGenerator, + this.getLineBelowCursor(helper), + fullStop, + ); + + lineGenerator = showWhateverWeHaveAtXMs( + lineGenerator, + helper.options.showWhateverWeHaveAtXMs ?? + (DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs as number), + ); + + const finalGenerator = streamWithNewLines(lineGenerator); + for await (const update of finalGenerator) { + yield update; + } + } + + private getLineBelowCursor(helper: HelperVars): string { + let lineBelowCursor = ""; + let i = 1; + while ( + lineBelowCursor.trim() === "" && + helper.pos.line + i <= helper.fileLines.length - 1 + ) { + lineBelowCursor = + helper.fileLines[ + Math.min(helper.pos.line + i, helper.fileLines.length - 1) + ]; + i++; + } + return lineBelowCursor; + } +} diff --git a/core/autocomplete/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts similarity index 98% rename from core/autocomplete/charStream.test.ts rename to core/autocomplete/filtering/streamTransforms/charStream.test.ts index b5504ad63..7ab8923fc 100644 --- a/core/autocomplete/charStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.test.ts @@ -1,4 +1,4 @@ -import { stopAtStopTokens } from "./streamTransforms/charStream"; +import { stopAtStopTokens } from "./charStream"; describe("stopAtStopTokens", () => { async function* createMockStream(chunks: string[]): AsyncGenerator { diff --git a/core/autocomplete/streamTransforms/charStream.ts b/core/autocomplete/filtering/streamTransforms/charStream.ts similarity index 100% rename from core/autocomplete/streamTransforms/charStream.ts rename to core/autocomplete/filtering/streamTransforms/charStream.ts diff --git a/core/autocomplete/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts similarity index 94% rename from core/autocomplete/lineStream.test.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.test.ts index ace94eaa4..810ab9eec 100644 --- a/core/autocomplete/lineStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts @@ -1,5 +1,5 @@ import { jest } from "@jest/globals"; -import * as lineStream from "./streamTransforms/lineStream"; +import * as lineStream from "./lineStream"; describe("lineStream", () => { let mockFullStop: jest.Mock; @@ -31,21 +31,34 @@ describe("lineStream", () => { }); describe("avoidPathLine", () => { - it("should filter out path lines and empty comments", async () => { + it("should filter out path lines", async () => { const linesGenerator = await getLineGenerator([ "// Path: src/index.ts", "const x = 5;", "//", "console.log(x);", ]); - - const result = lineStream.avoidPathLineAndEmptyComments( - linesGenerator, - "//", - ); + const result = lineStream.avoidPathLine(linesGenerator, "//"); const filteredLines = await getFilteredLines(result); + expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]); + }); + }); - expect(filteredLines).toEqual(["const x = 5;", "console.log(x);"]); + describe("avoidEmptyComments", () => { + it("should filter out empty comments", async () => { + const linesGenerator = await getLineGenerator([ + "// Path: src/index.ts", + "const x = 5;", + "//", + "console.log(x);", + ]); + const result = lineStream.avoidEmptyComments(linesGenerator, "//"); + const filteredLines = await getFilteredLines(result); + expect(filteredLines).toEqual([ + "// Path: src/index.ts", + "const x = 5;", + "console.log(x);", + ]); }); }); diff --git a/core/autocomplete/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts similarity index 89% rename from core/autocomplete/streamTransforms/lineStream.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.ts index 5990bbf3c..0f49cea55 100644 --- a/core/autocomplete/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -1,12 +1,20 @@ import { distance } from "fastest-levenshtein"; -import { DiffLine } from "../.."; -import { LineStream } from "../../diff/util"; +import { DiffLine } from "../../.."; +import { LineStream } from "../../../diff/util"; export type LineFilter = (args: { lines: LineStream; fullStop: () => void; }) => LineStream; +export type CharacterFilter = (args: { + chars: AsyncGenerator; + prefix: string; + suffix: string; + filepath: string; + multiline: boolean; +}) => AsyncGenerator; + function isBracketEnding(line: string): boolean { return line .trim() @@ -14,14 +22,6 @@ function isBracketEnding(line: string): boolean { .some((char) => BRACKET_ENDING_CHARS.includes(char)); } -function commonPrefixLength(a: string, b: string): number { - let i = 0; - while (i < a.length && i < b.length && a[i] === b[i]) { - i++; - } - return i; -} - function isEnglishFirstLine(line: string) { line = line.trim().toLowerCase(); @@ -122,27 +122,45 @@ export async function* noTopLevelKeywordsMidline( } /** - * Filters out unwanted lines from a LineStream, specifically those starting with '// Path: ' or empty comments. + * Filters out lines starting with '// Path: ' from a LineStream. * * @param {LineStream} stream - The input stream of lines to filter. * @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments). - * @yields {string} The filtered lines, excluding unwanted path lines and empty comments. + * @yields {string} The filtered lines, excluding unwanted path lines. */ -export async function* avoidPathLineAndEmptyComments( +export async function* avoidPathLine( stream: LineStream, - comment: string, + comment?: string, ): LineStream { // Snippets are inserted as comments with a line at the start '// Path: '. // Sometimes the model with copy this pattern, which is unwanted for await (const line of stream) { - // Also filter lines that are empty comments - if (line.startsWith(`${comment} Path: `) || line.trim() === comment) { + if (line.startsWith(`${comment} Path: `)) { continue; } yield line; } } +/** + * Filters out empty comment lines from a LineStream. + * + * @param {LineStream} stream - The input stream of lines to filter. + * @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments). + * @yields {string} The filtered lines, excluding empty comments. + */ +export async function* avoidEmptyComments( + stream: LineStream, + comment?: string, +): LineStream { + // Filter lines that are empty comments + for await (const line of stream) { + if (!comment || line.trim() !== comment) { + yield line; + } + } +} + /** * Transforms a LineStream by adding newline characters between lines. * @@ -168,9 +186,7 @@ export async function* streamWithNewLines(stream: LineStream): LineStream { * @returns {boolean} True if the lines are considered repeated, false otherwise. * * @description - * This function checks if two lines are repeated or very similar based on two criteria: - * 1. They have a common prefix longer than 12 characters. - * 2. The Levenshtein distance between them is less than 10% of the length of the second line. + * This function checks if the Levenshtein distance between them is less than 10% of the length of the second line. * Lines shorter than 5 characters are never considered repeated. */ export function lineIsRepeated(a: string, b: string): boolean { @@ -180,10 +196,7 @@ export function lineIsRepeated(a: string, b: string): boolean { const aTrim = a.trim(); const bTrim = b.trim(); - return ( - commonPrefixLength(aTrim, bTrim) > 12 || - distance(aTrim, bTrim) / bTrim.length < 0.1 - ); + return distance(aTrim, bTrim) / bTrim.length < 0.05; } /** @@ -210,9 +223,9 @@ export async function* stopAtSimilarLine( const lineIsBracketEnding = isBracketEnding(trimmedLine); for await (const nextLine of stream) { - if (nextLine === line) { - fullStop(); - break; + if (trimmedLine === "") { + yield nextLine; + continue; } if (lineIsBracketEnding && trimmedLine.trim() === nextLine.trim()) { @@ -220,6 +233,11 @@ export async function* stopAtSimilarLine( continue; } + if (nextLine === line) { + fullStop(); + break; + } + if (lineIsRepeated(nextLine, trimmedLine)) { fullStop(); break; @@ -510,3 +528,19 @@ export async function* logLines( } console.log(`${prefix}:\n${linesToLog.join("\n")}\n\n`); } + +export async function* showWhateverWeHaveAtXMs( + lines: LineStream, + ms: number, +): LineStream { + const startTime = Date.now(); + for await (const line of lines) { + // Always get at least one line + yield line; + + // But after that, soft break at X ms + if (Date.now() - startTime > ms) { + break; + } + } +} diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt new file mode 100644 index 000000000..ff0ba3cb3 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt @@ -0,0 +1,60 @@ +##### Prompt ##### +{ + "active": true, + "department": "Product Development", + "location": { + "country": "USA", + "state": "California", + "city": "San BERNARDINO", + "coordinates": { + + } + }, + "employees": [ + { + "name": "John Doe", + "age": 30, + "position": "Developer", + "skills": ["JavaScript", "React", "Node.js"], + "remote": false, + "salary": { + "currency": "USD", + "amount": 95000 + } + }, + { + "name": "Jane Smith", + "age": 25, + "position": "Designer", + "skills": ["Photoshop", "Illustrator"], + "remote": true, + "salary": { + "currency": "USD", + "amount": 70000 + } + }, + { + "name": "Emily Johnson", + "age": 35, + "position": "Manager", + "teamSize": 8, + "remote": true, + "skills": ["Leadership", "Project Management"],========================================================================== +========================================================================== +Completion: + + "latitude": 34.10834, + "longitude": -117.28977 + } + }, + "employeeCount": 2, + "averageAge": 30, + "remoteFriendly": true, + "salaryRange": { + "min": 70000, + "max": 95000, + "currency": "USD" + }, + "skills": { + "required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"], + "optional": ["Photoshop", "Illustrator"] \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt new file mode 100644 index 000000000..241d141f2 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt @@ -0,0 +1,128 @@ +##### Prompt ##### + }`, + }, + { + description: "Should autocomplete Vue computed property", + filename: "UserComponent.vue", + input: ` + + +`, + llmOutput: `() { + return this.firstName + ' ' + this.lastName; + }`, + expectedCompletion: `() { + return this.firstName + ' ' + this.lastName; + }`, + }, + { + description: "Should autocomplete Vue method using props", + filename: "TodoItem.vue", + input: ` + + +`, + llmOutput: `this.completed`, + expectedCompletion: `this.completed`, + }, + { + description: "Should autocomplete Svelte reactive statement", + filename: "Counter.svelte", + input: ` + + + +`, + llmOutput: `doubledCount = count * 2`, + expectedCompletion: `doubledCount = count * 2`, + }, + + { + description: "Should autocomplete Svelte component inside HTML", + filename: "NestedComponent.svelte", + input: ` + + +
+

Hello Svelte

+ /> +
+`, + llmOutput: `name="World"`, + expectedCompletion: `name="World"`, + }, + + { + description: "Should handle autocomplete in Svelte each block", + filename: "List.svelte", + input: ` + + +
    + {#each items as item} +
  • {item}
  • + {/each<|fim|> +
+`, + llmOutput: `}`, + expectedCompletion: `}`, + }, + +]; +========================================================================== +========================================================================== +Completion: + + + +export default { + components: { + ChildComponent, + }, \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt new file mode 100644 index 000000000..a50bd2fb4 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt @@ -0,0 +1,20 @@ +##### Prompt ##### +{ + "employees": [ + { "name": "John Doe", "age": 30, "position": "Developer" }, + { "name": "Jane Smith", "age": 25, "position": "Designer" }, + { "name": "Emily Johnson", "age": 35, "position": "Manager" } + ], + "active": true +} +========================================================================== +========================================================================== +Completion: + + +} + +{ + "employees": [ + { "name": "John Doe", "age": 30 }, + { "name": "Jane Smith", "age": 25 } \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT new file mode 100644 index 000000000..c4aaf43ec --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT @@ -0,0 +1,29 @@ +##### Prompt ##### +class Calculator: + def __init__(self): + self.result = 0 + + def add(self, number): + self.result += number + return self + + def divid + + def subtract(self, number): + self.result -= number + return self + + def reset(self): + self.result = 0 + return self + + def get_result(self): + return self.result + + +========================================================================== +========================================================================== +Completion: + +self.result /= number + return self \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT new file mode 100644 index 000000000..df8c2011f --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT @@ -0,0 +1,41 @@ +##### Prompt ##### +class Calculator + attr_accessor :result + + def initialize + @result = 0 + end + + def add(number) + @result += number + self + end + + def subtract(number) + @result -= number + self + end + + def power(ne + + def get_result + @result + end + + def reset + @result = 0 + self + end +end + +calc = Calculator.new +calc.add(5).subtract(3) +puts "Result: #{calc.get_result}" +========================================================================== +========================================================================== +Completion: + + + @result ** number + self + end \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT new file mode 100644 index 000000000..582ae5f36 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT @@ -0,0 +1,73 @@ +##### Prompt ##### +use std::io; + +fn main() { + println!("Welcome to the Calculator!"); + + loop { + println!("Please enter an operator (+, -, *, /) or 'q' to quit:"); + let operator = read_input(); + + if operator == "q" { + break; + } + + println!("Please enter the first number:"); + let num1 = read_input().parse::().unwrap(); + + println!("Please enter the second number:"); + let num2 = read_input().parse::().unwrap(); + + let result = match operator.as_str() { + "+" => num1 + num2, + "-" => num1 - num2, + "*" => num1 * num2, + "/" => num1 / num2, + + _ => { + println!("Invalid operator. Please try again."); + continue; + } + }; + + println!("Result: {}", result); + } +} + +fn read_input() -> String { + let mut input = String::new(); + io::stdin() + .read_line(&mut input) + .expect("Failed to read input"); + input.trim().to_string() +} +========================================================================== +========================================================================== +Completion: + + => { + println!("Invalid operator. Please try again."); + continue; + } + }; + + println!("Result: {}", result); + } + + println!("Goodbye!"); +} + + +fn main2() { + println!("Welcome to the Calculator!"); + + loop { + println!("Please enter an operator (+, -, *, /) or 'q' to quit:"); + let operator = read_input(); + + if operator == "q" { + break; + } + + match operator.as_str() { + "+" | "-" | "*" | "/" => (), \ No newline at end of file diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts new file mode 100644 index 000000000..62ef65512 --- /dev/null +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -0,0 +1,49 @@ +import { + AutocompleteFileringTestInput, + testAutocompleteFiltering, +} from "./util"; +import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; +import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; + +const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { + if (tests.some((test) => test.options?.only)) { + return tests.filter((test) => test.options?.only); + } + + return tests; +}; + +describe("llms/Mock", () => { + beforeAll(async () => { + tearDownTestDir(); + setUpTestDir(); + }); + + afterAll(async () => { + tearDownTestDir(); + }); + + describe("Autocomplete Filtering Tests", () => { + beforeEach(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + describe("Should return unmodified LLM output", () => { + it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); + }); + + describe("Should return modified LLM output", () => { + it.each(filterTestCases(TEST_CASES_WITH_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); + }); + }); +}); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts new file mode 100644 index 000000000..683dbc7bc --- /dev/null +++ b/core/autocomplete/filtering/test/testCases.ts @@ -0,0 +1,2085 @@ +import { dedent } from "../../../util"; +import { AutocompleteFileringTestInput } from "./util"; + +export const TEST_CASES_WITH_DIFF: AutocompleteFileringTestInput[] = [ + { + description: "Should handle python multi-line string", + filename: "test.py", + input: `def create_greeting(name): + greeting = """Hello, """ + name + """! +Welcome to our community. We hope you have a great time here. +If you have any questions, feel free to reach out.""" + return greeting + +message = create_greeting("Alice") +print(message) + +multi_line_message = """<|fim|> +print(multi_line_message) +`, + llmOutput: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + expectedCompletion: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +"""`, + }, + { + description: "Should autocomplete Rust match arms", + filename: "main.rs", + input: ` +fn get_status_code_description(code: u16) -> &'static str { + match code { + 200 => "OK", + 404 => "Not Found", + 500 => "Internal Server Error", + <|fim|> + } +} +`, + llmOutput: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status", +`, + expectedCompletion: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status",`, + }, + { + description: "Should complete a Markdown code block", + filename: "test.md", + input: ` +Here is a sample JavaScript function: + +\`\`\`javascript +function sayHello() { + console.log("Hello, <|fim|> +} +\`\`\` +`, + llmOutput: `world!"); +`, + expectedCompletion: `world!");`, + }, + { + description: "Should autocomplete Java when inside a block", + filename: "Main.java", + input: ` +public class Main { + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + System.out.println("Even: " + i); + } else { +<|fim|> + } + } + } +}`, + llmOutput: ` + System.out.println("Odd: " + i); +`, + expectedCompletion: ` + System.out.println("Odd: " + i);`, + }, + { + description: + "Should autocomplete a Markdown heading and preserve formatting", + filename: "test.md", + input: `# My Document + +## Introduction +This is a sample document for testing. + +## <|fim|> +### Conclusion +Thank you for reading. +`, + llmOutput: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + expectedCompletion: `Features +Here is a list of features: +- Feature 1 +- Feature 2`, + }, + { + description: "Should autocomplete a Java method within a class", + filename: "Calculator.java", + input: ` +public class Calculator { + private double result; + + public Calculator() { + this.result = 0.0; + } + + public void add(double number) { + result += number; +<|fim|>`, + llmOutput: ` + } + + public void subtract(double number) { + result -= number; + } +`, + expectedCompletion: ` + } + + public void subtract(double number) { + result -= number; + }`, + }, + { + description: "Should filter out consecutive, repeated YAML keys", + filename: "test.yaml", + input: ` + version: '3' + services: + db: + image: postgres + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass<|fim|> + `, + llmOutput: ` + POSTGRES_DB: mydb + POSTGRES_DB: mydb + `, + expectedCompletion: ` + POSTGRES_DB: mydb + `, + }, + { + description: "Should autocomplete a Markdown list with nested items", + filename: "test.md", + input: ` +- Item 1 +- Item 2 + - Subitem 1 + <|fim|> +- Item 3 +`, + llmOutput: ` - Subitem 2 + - Subitem 3 +`, + expectedCompletion: ` - Subitem 2 + - Subitem 3`, + }, + { + description: "Should enforce bracket matching in JSON files", + filename: "test.json", + input: `{ + "active": true, + "department": "Product Development", + "location": { + "country": "USA", + "state": "California", + "city": "San BERNARDINO", + "coordinates": { + + } + }, + "employees": [ + { + "name": "John Doe", + "age": 30, + "position": "Developer", + "skills": ["JavaScript", "React", "Node.js"], + "remote": false, + "salary": { + "currency": "USD", + "amount": 95000 + } + }, + { + "name": "Jane Smith", + "age": 25, + "position": "Designer", + "skills": ["Photoshop", "Illustrator"], + "remote": true, + "salary": { + "currency": "USD", + "amount": 70000 + } + }, + { + "name": "Emily Johnson", + "age": 35, + "position": "Manager", + "teamSize": 8, + "remote": true, + "skills": ["Leadership", "Project Management"],`, + llmOutput: `"latitude": 34.10834, + "longitude": -117.28977 + } + }, + "employeeCount": 2, + "averageAge": 30, + "remoteFriendly": true, + "salaryRange": { + "min": 70000, + "max": 95000, + "currency": "USD" + }, + "skills": { + "required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"], + "optional": ["Photoshop", "Illustrator"]`, + expectedCompletion: `"latitude": 34.10834, + "longitude": -117.28977 + `, + }, +]; + +export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [ + { + description: "should pass", + filename: "test.js", + input: "console.log('Hello <|fim|>!');", + llmOutput: "World", + expectedCompletion: "World", + }, + { + description: + "Should preserve closing brackets when the opening bracket is not a part of the completion.", + filename: "test.js", + input: dedent` + class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + <|fim|> + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } + } + `, + llmOutput: dedent`if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + expectedCompletion: dedent`if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + }, + { + description: "Should multiline-autocomplete CSS blocks", + input: `body { + font-family: Arial, sans-serif; + font-size: 16px; + color: #333333; +} + +h1 { + font-size: 24px; + font-weight: bold; + color: #000000; +} + +h4<|fim|> + +a { + text-decoration: none; + color: #007bff; +} + +.container { + width: 100%; + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +.button { + display: inline-block; + padding: 10px 20px; + background-color: #007bff; + color: #ffffff;`, + llmOutput: ` { + font-size: 18px; + font-weight: bold; + color: #000000; +}`, + expectedCompletion: ` { + font-size: 18px; + font-weight: bold; + color: #000000; +}`, + filename: "test.css", + }, + { + description: "Should complete CSS rules inside a nested selector", + filename: "styles.css", + input: ` +.container { + display: flex; + justify-content: center; + align-items: center; + width: 100%; + height: 100vh; + + .inner { + <|fim|> + } +} +`, + llmOutput: `width: 50%; + height: 50%; + background-color: #f0f0f0;`, + expectedCompletion: `width: 50%; + height: 50%; + background-color: #f0f0f0;`, + }, + + { + description: + "Should complete a CSS rule when the property is partially typed", + filename: "styles.css", + input: ` +button { + border: 2px solid #000; + border-radius<|fim|> +}`, + llmOutput: `: 5px;`, + expectedCompletion: `: 5px;`, + }, + + { + description: "Should handle CSS autocomplete with a single bracket present", + filename: "styles.css", + input: ` +.card { + box-shadow: 0 4px 8px rgba(0,0,0,0.2); + transition: 0.3s; + padding: 16px; + border-bottom-left-radius: <|fim|>px; + border-bottom-right-radius: 8px; +} +`, + llmOutput: `8`, + expectedCompletion: `8`, + }, + + { + description: "Should autocomplete CSS pseudoclass", + filename: "pseudoClass.css", + input: ` +input:focus { + outline: none; + border: 2px solid <|fim|>; +} +`, + llmOutput: `#4CAF50;`, + expectedCompletion: `#4CAF50;`, + }, + + { + description: "Should handle CSS variable syntax", + filename: "variables.css", + input: ` +:root { + --primary-color: #3498db; + --padding: 10px; +} + +.section { + background-color: var(<|fim|>); + padding: var(--padding); +} +`, + llmOutput: `--primary-color`, + expectedCompletion: `--primary-color`, + }, + { + description: "Should complete CSS grid template columns", + filename: "grid.css", + input: ` +.grid-container { + display: grid; + grid-template-columns: repeat(<|fim|>); + grid-gap: 10px; +} +`, + llmOutput: `3, 1fr`, + expectedCompletion: `3, 1fr`, + }, + + { + description: "Should complete PHP function inside a class with comments", + input: `name = $name; + $this->email = $email; + } + + public function <|fim|> + + public function setEmail($email) { + $this->email = $email; + } +}`, + llmOutput: `getDetails() { + return "Name: " . $this->name . ", Email: " . $this->email; + }`, + expectedCompletion: `getDetails() { + return "Name: " . $this->name . ", Email: " . $this->email; + }`, + filename: "User.php", + }, + + { + description: "Should autocomplete PHP function with inline logic", + input: ` +} + +echo calculateArea(5, 3);`, + llmOutput: `return $length * $width;`, + expectedCompletion: `return $length * $width;`, + filename: "areaCalculator.php", + }, + + { + description: "Should handle PHP completion in the middle of an array", + input: `); + +echo "First color is: " . $colors[0];`, + llmOutput: `"Blue"`, + expectedCompletion: `"Blue"`, + filename: "colors.php", + }, + { + description: "Should autocomplete React return statements (jsx)", + input: `import React from "react"; + +export const Button = ({ + onClick, + children, +}: { + children: React.ReactNode; + onClick: () => void; +}) => { + return ( +<|fim|> + ); +};`, + llmOutput: ``, + expectedCompletion: ``, + filename: "Button.tsx", + }, + { + description: "Should autocomplete React state initialization", + input: `import React, { useState } from "react"; + +export const Counter = () => { + const [count, setCount] = useState(<|fim|>); + + return ( +
+

You clicked {count} times

+ +
+ ); +};`, + llmOutput: `0`, + expectedCompletion: `0`, + filename: "Counter.tsx", + }, + + { + description: "Should autocomplete React effect hook", + input: `import React, { useState, useEffect } from "react"; + +export const Timer = () => { + const [seconds, setSeconds] = useState(0); + + useEffect(() => { + const interval = setInterval(() => { + setSeconds(seconds + 1); + }, 1000); + + <|fim|>; + + return () => clearInterval(interval); + }, [seconds]); + + return ( +
+

{seconds} seconds have passed.

+
+ ); +};`, + llmOutput: `return () => clearInterval(interval);`, + expectedCompletion: `return () => clearInterval(interval);`, + filename: "Timer.tsx", + }, + + { + description: "Should autocomplete React component methods", + input: `import React from "react"; + +class Form extends React.Component { + constructor(props) { + super(props); + this.state = { name: '' }; + } + + handleChange = (event) => { + <|fim|> + } + + handleSubmit = (event) => { + event.preventDefault(); + alert('A name was submitted: ' + this.state.name); + } + + render() { + return ( +
+ + +
+ ); + } +}`, + llmOutput: `this.setState({ name: event.target.value });`, + expectedCompletion: `this.setState({ name: event.target.value });`, + filename: "Form.tsx", + }, + { + description: "Should autocomplete Python function definition", + filename: "test.py", + input: `def calculate_area(length, width): + area = length * width + return area + +def calculate_perimeter(length, width): + <|fim|> +`, + llmOutput: `perimeter = 2 * (length + width) + return perimeter`, + expectedCompletion: `perimeter = 2 * (length + width) + return perimeter`, + }, + { + description: "Should complete Python class method with self", + filename: "test.py", + input: `class BankAccount: + def __init__(self, owner, balance=0): + self.owner = owner + self.balance = balance + + def deposit(self, amount): + self.balance += amount + return self.balance + + def withdraw(self, amount): + <|fim|> +`, + llmOutput: `if amount > self.balance: + return "Insufficient funds" + self.balance -= amount + return self.balance`, + expectedCompletion: `if amount > self.balance: + return "Insufficient funds" + self.balance -= amount + return self.balance`, + }, + { + description: "Should autocomplete Python list comprehension", + filename: "test.py", + input: `squares = [x**2 for x in range(10)] +even_squares = [x for x in squares if x % 2 == 0] +print(even_squares) + +odd_squares = [<|fim|> +print(odd_squares) +`, + llmOutput: `x for x in squares if x % 2 != 0`, + expectedCompletion: `x for x in squares if x % 2 != 0`, + }, + { + description: "Should autocomplete a simple Go function declaration", + filename: "simpleFunction.go", + input: `package main + +import ( + "fmt" +) + +func main() { + fmt.Println("Hello, World!") +} + +func calculateArea<|fim|>`, + llmOutput: `(length float64, width float64) float64 { + return length * width +}`, + expectedCompletion: `(length float64, width float64) float64 { + return length * width +}`, + }, + + { + description: + "Should handle autocomplete in the middle of a Go struct definition", + filename: "structDefinition.go", + input: `package main + +type Person struct { + FirstName string + LastName string + Age int + Address Address +} + +type Address struct { + Street string + City <|fim|> +} + +func main() {}`, + llmOutput: `string + State string + ZipCode string +}`, + expectedCompletion: `string + State string + ZipCode string +}`, + }, + + { + description: "Should autocomplete a missing Go function body bracket", + filename: "missingBracket.go", + input: `package main + +func add(a int, b int) int { + return a + b<|fim|> + +func multiply(a int, b int) int { + return a * b +} + +func main() { + result1 := add(2, 3) + result2 := multiply(4, 5) + println(result1, result2) +}`, + llmOutput: ` +}`, + expectedCompletion: ` +}`, + }, + { + description: + "Should autocomplete SQL query with nested functions and missing bracket", + filename: "_nested_function.sql", + input: `SELECT name, ROUND(AVG(rating), 2) as avg_rating + FROM movies + WHERE release_year > 2000 AND director = 'Christopher Nolan' + GROUP BY name + HAVING avg_rating > <|fim|>`, + llmOutput: `8.5)`, + expectedCompletion: `8.5)`, + }, + { + description: + "Should autocomplete SQL script with employee and product tables", + filename: "database.sql", + input: ` + CREATE TABLE employees ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + age INT NOT NULL, + position VARCHAR(100) + ); + + CREATE TABLE products ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100), + price DECIMAL(8,2) NOT NULL '0.00', + quantity INT NOT NULL DEFAULT '0' + ); + + INSERT INTO employees (name, age, position) VALUES ('John Doe', 30, 'Developer'); + INSERT INTO products (name, price, quantity) VALUES ('Apple', '1.99', '47'); + + SELECT * FROM products ORDER BY name DESC LIMIT 3; + SELECT * FROM products WHERE price > '0'; + SELECT * FROM products WHERE quantity > '100'; + SELECT * FROM employees WHERE age > 25; + `, + llmOutput: " DEFAULT", + expectedCompletion: " DEFAULT", + }, + { + description: + "Should autocomplete SQL query with subquery and alias in SELECT clause", + filename: "complex_query.sql", + input: `SELECT u.id, + u.name, + (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count + FROM users u + WHERE u.active = 1 + <|fim|>`, + llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, + expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, + }, + { + description: + "Should autocomplete multi-line SQL query with CASE statements", + filename: "case_statement.sql", + input: `SELECT order_id, + order_date, + CASE + WHEN status = 'shipped' THEN 'Completed' + WHEN status = 'pending' THEN 'Pending Approval' + <|fim|> + ELSE 'Unknown' + END as order_status + FROM orders`, + llmOutput: `WHEN status = 'cancelled' THEN 'Cancelled'`, + expectedCompletion: `WHEN status = 'cancelled' THEN 'Cancelled'`, + }, + { + description: "Should autocomplete HTML paragraph content", + input: ` + + Document + + +

<|fim|>

+ +`, + llmOutput: `This is a paragraph with some sample text.`, + expectedCompletion: `This is a paragraph with some sample text.`, + filename: "test.html", + }, + { + description: "Should autocomplete HTML attributes within a tag", + input: `
+ > +
+

Title

+

Description text.

+
+
`, + llmOutput: `alt="Description of image"`, + expectedCompletion: `alt="Description of image"`, + filename: "test.html", + }, + { + description: "Should autocomplete HTML nested tags", + input: `
    +
  • Item 1
  • +
  • Item 2
  • +
  • Item 3
  • +
`, + llmOutput: `>Item 4`, + expectedCompletion: `>Item 4`, + filename: "test.html", + }, + + { + description: "Should complete a class method in Ruby", + input: ` +class Greeter + def initialize(name) + @name = name + end + + def greet + puts "Hello, <|fim|> + end +end + +g = Greeter.new("World") +g.greet +`, + llmOutput: "#{@name}!", + expectedCompletion: "#{@name}!", + filename: "greeter.rb", + }, + { + description: "Should complete Ruby if-else block", + input: ` +number = 10 + +if number > 5 + puts "Number is greater than 5" +<|fim|> +end +`, + llmOutput: `else + puts "Number is 5 or less"`, + expectedCompletion: `else + puts "Number is 5 or less"`, + filename: "conditional.rb", + }, + { + description: "Should complete Ruby array method", + input: ` +numbers = [1, 2, 3, 4, 5] +squared_numbers = numbers.<|fim|> +`, + llmOutput: `map { |n| n ** 2 }`, + expectedCompletion: `map { |n| n ** 2 }`, + filename: "array_methods.rb", + }, + { + description: "Should autocomplete Java within a string", + filename: "App.java", + input: ` +public class App { + public static void main(String[] args) { + String message = "Hello, <|fim|>"; + System.out.println(message); + } +}`, + llmOutput: `World`, + expectedCompletion: `World`, + }, + { + description: + "Should autocomplete a C++ class definition with a constructor", + filename: "test.cpp", + input: "class Vehicle { public: Vehicle(<|fim|>); };", + llmOutput: "int wheels, double weight", + expectedCompletion: "int wheels, double weight", + }, + { + description: "Should complete a C++ method declaration inside a class", + filename: "test.cpp", + input: + "class Calculator { public: int add(int a, int b); int subtract(int a, int b);<|fim|> };", + llmOutput: " int multiply(int a, int b);", + expectedCompletion: " int multiply(int a, int b);", + }, + { + description: "Should autocomplete C++ for loop syntax", + filename: "test.cpp", + input: ` + int sum = 0; + for (int i = 0; i < 10; <|fim|>) { + sum += i; + } + `, + llmOutput: "i++", + expectedCompletion: "i++", + }, + { + description: "Should autocomplete JSON object inside an array", + filename: "data.json", + input: `{ + "users": [ + { "id": 1, "name": "Alice" }, + { "id": 2, "name": "Bob" } + <|fim|> + ] +}`, + llmOutput: `, { "id": 3, "name": "Charlie" }`, + expectedCompletion: `, { "id": 3, "name": "Charlie" }`, + }, + { + description: "Should autocomplete within a CSV record", + filename: "test.csv", + input: `Name, Age, City +John Doe, 30, New York +Jane Smith<|fim|>`, + llmOutput: `, 25, Los Angeles`, + expectedCompletion: `, 25, Los Angeles`, + }, + { + description: + "Should complete CSV record when starting in the middle of a word", + filename: "test.csv", + input: `Product, Price, Quantity +Laptop, 1200, 5 +Smart<|fim|>`, + llmOutput: `phone, 800, 10`, + expectedCompletion: `phone, 800, 10`, + }, + { + description: "Should complete CSV structure adding closing brackets", + filename: "test.csv", + input: `ID, Name, JoiningDate +1, Alice, 2023-01-10 +2, B<|fim|>`, + llmOutput: `ob, 2023-02-10`, + expectedCompletion: `ob, 2023-02-10`, + }, + { + description: "Should complete YAML list item and preserve structure", + filename: "test.yaml", + input: ` + services: + - name: web + image: nginx + - name: app<|fim|> + volumes: + - volume1 + - volume2 + `, + llmOutput: ` + image: node + `, + expectedCompletion: ` + image: node + `, + }, + { + description: + "Should complete YAML key-value pair inside a nested structure", + filename: "test.yaml", + input: ` + version: '3' + services: + db: + image: postgres + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass + POSTGRES_DB: mydb<|fim|> + `, + llmOutput: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + expectedCompletion: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + }, + { + description: "Should complete YAML block within an existing block", + filename: "test.yaml", + input: ` + pipelines: + branches: + master: + - step: + name: Build and Test + script: + - npm install + - npm run test + - step: + name: Deploy<|fim|> + `, + llmOutput: ` + script: + - npm run deploy + `, + expectedCompletion: ` + script: + - npm run deploy + `, + }, + { + description: + "Should autocomplete a Rust function implementation inside a struct", + filename: "main.rs", + input: ` +struct Calculator { + result: f64, +} + +impl Calculator { + fn new() -> Self { + Calculator { result: 0.0 } + } + + fn add(&mut self, number: f64) { + self.result += number; + } + + fn subtract(&mut self, number: f64) { + self.result -= number; + } + + fn multiply(&mut self, number: f64) { + self.result *= number; + } + + fn divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } + } + + fn reset(&mut self) { + self.result = 0.0; + } + + fn get_result(&self) -> f64 { + self.result + } + + fn<|fim|> +} +`, + llmOutput: ` divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } +}`, + expectedCompletion: ` divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } +}`, + }, + { + description: "Should autocomplete Rust struct definition", + filename: "main.rs", + input: ` +struct User { + id: u32, + username: String, + email: String, + is_active: bool, + <|fim|> +} + +impl User { + fn new(id: u32, username: String, email: String) -> Self { + User { + id, + username, + email, + is_active: true, + } + } +} +`, + llmOutput: `created_at: String, + updated_at: String,`, + expectedCompletion: `created_at: String, + updated_at: String,`, + }, + { + description: "Haskell: Nested pattern matching with let bindings", + filename: "NestedPattern.hs", + input: `module NestedPattern where + +data Tree a = Leaf a | Node (Tree a) (Tree a) + +sumTree :: Num a => Tree a -> a +sumTree (Leaf x) = x +sumTree (Node left right) = + let leftSum = <|fim|> + rightSum = sumTree right + in leftSum + rightSum`, + llmOutput: `sumTree left`, + expectedCompletion: `sumTree left`, + }, + { + description: "Haskell: Complex function with where clause and guards", + filename: "QuadraticSolver.hs", + input: `module QuadraticSolver where + +solveQuadratic :: (Ord a, Floating a) => a -> a -> a -> Maybe (a, a) +solveQuadratic a b c + | discriminant < 0 = Nothing + | otherwise = Just (x1, x2) + where + discriminant = b^2 - 4*a*c + sqrtD = sqrt discriminant + x1 = (-b + sqrtD) / (2*a) + <|fim|> = (-b - sqrtD) / (2*a)`, + llmOutput: `x2`, + expectedCompletion: `x2`, + }, + { + description: "Haskell: List comprehension with complex filter", + filename: "PrimeNumbers.hs", + input: `module PrimeNumbers where + +primesUpTo :: Int -> [Int] +primesUpTo n = [x | x <- [2..n], isPrime x] + where isPrime num = <|fim|> && all (\d -> num \`mod\` d /= 0) [2..(floor . sqrt $ fromIntegral num)]`, + llmOutput: `num > 1`, + expectedCompletion: `num > 1`, + }, + { + description: "Should autocomplete Dart class methods", + filename: "calculator.dart", + input: ` +class Calculator { + double result = 0.0; + + void add(double number) { + result += number; + } + + void multiply(double number) { + result *= number; + } + + <|fim|> + + double getResult() { + return result; + } +}`, + llmOutput: `void subtract(double number) { + result -= number; + }`, + expectedCompletion: `void subtract(double number) { + result -= number; + }`, + }, + { + description: "Should handle string interpolation in Dart", + filename: "greetings.dart", + input: ` +void main() { + var name = "World"; + print('Hello, <|fim|>!'); +}`, + llmOutput: `\${name}`, + expectedCompletion: `\${name}`, + }, + { + description: "Should autocomplete within a Dart function body", + filename: "counter.dart", + input: ` +class Counter { + int count = 0; + + void increment() { + count++; + } + + void decrement() { + <|fim|> + + void reset() { + count = 0; + } +}`, + llmOutput: `count--;`, + expectedCompletion: `count--;`, + }, + { + description: + "Should autocomplete Clojure function definition with missing closing parenthesis", + input: `(defn calculate-sum [a b] + (let [sum (+ a b)] + (println "The sum is" sum) + sum<|fim|>`, + llmOutput: `))`, + expectedCompletion: `))`, + filename: "test.clj", + }, + { + description: + "Should autocomplete missing part of a Clojure map within a function", + input: `(defn get-user [] + {:username "johndoe" + :email "johndoe@example.com" + :age 30 + <|fim|> + (println "User information loaded"))`, + llmOutput: `:location "Unknown"}`, + expectedCompletion: `:location "Unknown"}`, + filename: "test.clj", + }, + { + description: + "Should autocomplete inside a Clojure vector within a looping construct", + input: `(defn odd-numbers [] + (loop [nums [1 3 5<|fim|> 9 11]] + (when (seq nums) + (println (first nums)) + (recur (rest nums)))))`, + llmOutput: ` 7,`, + expectedCompletion: ` 7,`, + filename: "test.clj", + }, + { + description: "Should autocomplete R function definition", + filename: "calculate.R", + input: ` +calculate_mean <- function(numbers) { + total <- sum(numbers) + <|fim|> +}`, + llmOutput: `mean_value <- total / length(numbers) + return(mean_value)`, + expectedCompletion: `mean_value <- total / length(numbers) + return(mean_value)`, + }, + { + description: "Should complete R loop and print statement", + filename: "loopPrint.R", + input: ` +numbers <- c(1, 2, 3, 4, 5) +for (number in numbers) { + print(<|fim|>) +}`, + llmOutput: `number)`, + expectedCompletion: `number)`, + }, + { + description: "Should autocomplete R data frame creation", + filename: "dataFrame.R", + input: ` +data <- data.frame( + Name = c("Alice", "Bob", "Charlie"), + Age = c(25, 30, 35), + <|fim|> +)`, + llmOutput: `Height = c(165, 180, 175)`, + expectedCompletion: `Height = c(165, 180, 175)`, + }, + { + description: "Should autocomplete R if-else statement", + filename: "condition.R", + input: ` +grade <- 85 +if (grade >= 90) { + print("A") +} else if (grade >= 80) { + <|fim|> +} else { + print("C") +}`, + llmOutput: `print("B")`, + expectedCompletion: `print("B")`, + }, + { + description: "Should autocomplete R ggplot2 plot structure", + filename: "plot.R", + input: ` +library(ggplot2) + +ggplot(data=mtcars, aes(x=wt, y=mpg)) + + geom_point() + + <|fim|>`, + llmOutput: `geom_smooth(method='lm', se=FALSE)`, + expectedCompletion: `geom_smooth(method='lm', se=FALSE)`, + }, + { + description: "Should autocomplete Scala class with a method", + filename: "Person.scala", + input: `class Person(val name: String, val age: Int) { + def greet(): String = { + <|fim|> + } + }`, + llmOutput: `s"Hello, my name is $name and I am $age years old."`, + expectedCompletion: `s"Hello, my name is $name and I am $age years old."`, + }, + + { + description: "Should handle Scala case class with a missing field", + filename: "Person.scala", + input: `case class Address(city: String, postalCode: String) + case class Person(name: String, age: Int, address: Address) + + val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, + llmOutput: `"12345")`, + expectedCompletion: `"12345")`, + }, + + { + description: "Should autocomplete Scala function with missing body bracket", + filename: "Math.scala", + input: `object MathUtils { + def add(a: Int, b: Int): Int = { + a + b<|fim|> + + def multiply(a: Int, b: Int): Int = { + a * b + } + } + + object Main extends App { + println(MathUtils.add(3, 5)) + println(MathUtils.multiply(4, 6)) + }`, + llmOutput: ` + }`, + expectedCompletion: ` + }`, + }, + { + description: "Should autocomplete C function definition", + filename: "math_utils.c", + input: `#include + +int add(int a, int b) { + return a + b; +} + +int multiply(int a, int b) { + return a * b; +} + +int subtract(int a, int b) { + <|fim|> +} + +int main() { + printf("Result: %d", add(2, 3)); + return 0; +}`, + llmOutput: `return a - b;`, + expectedCompletion: `return a - b;`, + }, + + { + description: "Should handle C struct with missing field initialization", + filename: "person.c", + input: `#include + +typedef struct { + char name[50]; + int age; + float height; +} Person; + +int main() { + Person alice = {"Alice", 30, <|fim|>}; + printf("Name: %s, Age: %d, Height: %.2f", alice.name, alice.age, alice.height); + return 0; +}`, + llmOutput: `5.5`, + expectedCompletion: `5.5`, + }, + + { + description: "Should autocomplete C function with missing body bracket", + filename: "area.c", + input: `#include + +double calculateCircleArea(double radius) { + const double pi = 3.14159; + return pi * radius * radius;<|fim|> + +double calculateRectangleArea(double length, double width) { + return length * width; +} + +int main() { + printf("Circle Area: %.2f", calculateCircleArea(5.0)); + printf("Rectangle Area: %.2f", calculateRectangleArea(4.0, 6.0)); + return 0; +}`, + llmOutput: ` +}`, + expectedCompletion: ` +}`, + }, + { + description: "Should autocomplete a simple Kotlin function declaration", + filename: "simpleFunction.kt", + input: ` +fun main() { + println("Hello, World!") +} + +fun calculateArea(length: Double, width: Double): Double <|fim|>`, + llmOutput: `{ + return length * width +}`, + expectedCompletion: `{ + return length * width +}`, + }, + { + description: "Should handle autocomplete inside a Kotlin data class", + filename: "dataClass.kt", + input: ` +data class User( + val id: Int, + val name: String, + val email: String, + <|fim|> +)`, + llmOutput: `val age: Int`, + expectedCompletion: `val age: Int`, + }, + { + description: + "Should complete Kotlin if-else structure with missing brackets", + filename: "controlStructure.kt", + input: ` +fun getMax(a: Int, b: Int): Int { + if (a > b<|fim|> + } else { + return b + } +}`, + llmOutput: `) { + return a`, + expectedCompletion: `) { + return a`, + }, + { + description: "Should autocomplete Solidity function definition", + filename: "SimpleStorage.sol", + input: ` +pragma solidity ^0.8.0; + +contract SimpleStorage { + uint private data; + + function set(uint x) public { + data = x; + } + + function get() public view returns (uint) { + <|fim|> + } +} + `, + llmOutput: `return data;`, + expectedCompletion: `return data;`, + }, + + { + description: "Should autocomplete Solidity event with parameters", + filename: "EventExample.sol", + input: ` +pragma solidity ^0.8.0; + +contract EventExample { + event DataStored(uint indexed id, string content); + + function storeData(uint id, string memory content) public { + emit DataStored(<|fim|>); + } +} + `, + llmOutput: `id, content`, + expectedCompletion: `id, content`, + }, + + { + description: "Should handle Solidity struct definition completion", + filename: "StructDefinition.sol", + input: ` +pragma solidity ^0.8.0; + +contract StructExample { + struct Person { + string name; + uint age; + address wallet; + } + + Person[] private people; + + function addPerson(string memory name, uint age, address wallet) public { + people.push(Person(name, age, wallet)); + } + + function getFirstPerson<|fim|> +} + `, + llmOutput: `() public view returns (string memory, uint, address) { + if (people.length > 0) { + Person storage person = people[0]; + return (person.name, person.age, person.wallet); + } + return ("", 0, address(0)); + }`, + expectedCompletion: `() public view returns (string memory, uint, address) { + if (people.length > 0) { + Person storage person = people[0]; + return (person.name, person.age, person.wallet); + } + return ("", 0, address(0)); + }`, + }, + { + description: "Should autocomplete TypeScript interface properties", + filename: "User.ts", + input: ` +interface User { + id: number; + name: string; + e<|fim|> +} +`, + llmOutput: `mail: string; + age: number; +}`, + expectedCompletion: `mail: string; + age: number; +}`, + }, + + { + description: + "Should autocomplete a TypeScript arrow function inside a variable assignment", + filename: "mathOperations.ts", + input: ` +const addNumbers = (a: number, b: number): number => { + return a + b; +}; + +const multiplyNumbers = (a: number, b: number): number => { + re<|fim|> +} + +console.log(multiplyNumbers(2, 3)); +`, + llmOutput: `turn a * b;`, + expectedCompletion: `turn a * b;`, + }, + + { + description: + "Should handle autocomplete inside a nested TypeScript class method", + filename: "Account.ts", + input: ` +class Account { + private balance: number = 0; + + deposit(amount: number) { + this.balance += amount; + return this.balance; + } + + withdraw(amount: number) { + if (amount > this.balance) { + throw new Error("Insufficient funds"); + } + this.balance -= amount; + return thi<|fim|> + } +} +`, + llmOutput: `s.balance;`, + expectedCompletion: `s.balance;`, + }, + + { + description: "Should autocomplete a TypeScript generic function", + filename: "GenericFunction.ts", + input: ` +function identity(arg: T): T { + return ar<|fim|> +} + +console.log(identity(5)); +`, + llmOutput: `g;`, + expectedCompletion: `g;`, + }, + + { + description: + "Should autocomplete a TypeScript promise within an asynchronous function", + filename: "asyncFunction.ts", + input: ` +async function fetchData(url: string): Promise { + const response = await fetch(url); + <|fim|> + return data; +} + +fetchData('https://api.example.com/data'); +`, + llmOutput: `const data = await response.json();`, + expectedCompletion: `const data = await response.json();`, + }, + + { + description: + "Should autocomplete a C# class with a constructor and property", + filename: "Person.cs", + input: `using System; + +public class Person +{ + public string Name { get; set; } + public int Age { get; set; } + + public Person(string name, int <|fim|> +}`, + llmOutput: `age) + { + Name = name; + Age = age; + }`, + expectedCompletion: `age) + { + Name = name; + Age = age; + }`, + }, + { + description: "Should autocomplete a C# interface method", + filename: "IGreetable.cs", + input: `public interface IGreetable +{ + void <|fim|> +}`, + llmOutput: `Greet();`, + expectedCompletion: `Greet();`, + }, + { + description: "Should autocomplete inside C# method with if condition", + filename: "Calculator.cs", + input: `using System; + +public class Calculator +{ + public int Add(int a, int b) + { + if(<|fim|>) + { + return a + b; + } + return 0; + } +}`, + llmOutput: `a > 0 && b > 0`, + expectedCompletion: `a > 0 && b > 0`, + }, + { + description: "Should complete a simple Julia function", + filename: "simpleFunction.jl", + input: `function calculate_area(length, width) + <|fim|> +end +`, + llmOutput: `return length * width`, + expectedCompletion: `return length * width`, + }, + { + description: "Should autocomplete Julia for loop", + filename: "loop.jl", + input: `numbers = [1, 2, 3, 4, 5] +squared_numbers = [] + +for num in numbers + <|fim|> +end + +println(squared_numbers) +`, + llmOutput: `push!(squared_numbers, num^2)`, + expectedCompletion: `push!(squared_numbers, num^2)`, + }, + { + description: "Should complete a Julia struct definition", + filename: "structDefinition.jl", + input: `struct Person + first_name::String + last_name::String + age::Int + address::Address +end + +struct Address + street::String + city::String + <|fim|> +end +`, + llmOutput: `state::String + zip_code::String`, + expectedCompletion: `state::String + zip_code::String`, + }, + { + description: "Should complete a Julia dictionary access", + filename: "dictionary.jl", + input: `grades = Dict("Alice" => 90, "Bob" => 85, "Eve" => 88) + +function get_grade(student_name) + return grades[<|fim|>] +end + +println(get_grade("Alice")) # Should print 90 +`, + llmOutput: `student_name`, + expectedCompletion: `student_name`, + }, + { + description: "Should complete a Julia module declaration", + filename: "moduleDeclaration.jl", + input: `module MathOperations + +export add, subtract + +function add(a, b) + return a + b +end + +function subtract(a, b) + return a - b +end + +<|fim|> +`, + llmOutput: `end`, + expectedCompletion: `end`, + }, + { + description: "Should complete F# let-binding with function definition", + filename: "mathModule.fs", + input: `module MathModule + +let calculateArea length width = + <|fim|>`, + llmOutput: `length * width`, + expectedCompletion: `length * width`, + }, + + { + description: "Should complete incomplete F# type definition", + filename: "personType.fs", + input: `type Person = { + FirstName: string + LastName: string + Age: int<|fim|> +} + +let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, + llmOutput: ` + Address: string +}`, + expectedCompletion: ` + Address: string +}`, + }, + + { + description: "Should complete F# pattern matching expression", + filename: "patternMatching.fs", + input: `let describeNumber number = + match number with + | 0 -> "Zero" + | 1 -> "One" + | <|fim|>`, + llmOutput: `2 -> "Two" + | _ -> "Other"`, + expectedCompletion: `2 -> "Two" + | _ -> "Other"`, + }, + + { + description: "Should complete F# list comprehension expression", + filename: "listComprehension.fs", + input: `let squares = [ for x in 1..10 -> x * x ] +let evenSquares = [ for x in squares do if x % 2 = 0 then yield x ] +let oddSquares = [<|fim|>]`, + llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, + expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, + }, + { + description: "Should complete an F# recursive function", + filename: "recursiveFunctions.fs", + input: `let rec factorial n = + if n <= 1 then 1 + else n <|fim|> factorial (n - 1)`, + llmOutput: `*`, + expectedCompletion: `*`, + }, + { + description: "Should complete F# member method inside a class type", + filename: "bankAccount.fs", + input: `type BankAccount(owner: string, initialBalance: float) = + let mutable balance = initialBalance + + member this.Deposit amount = + balance <- balance + amount + this + <|fim|>`, + llmOutput: ` + member this.Withdraw amount = + if amount > balance then + failwith "Insufficient funds" + balance <- balance - amount + this`, + expectedCompletion: ` + member this.Withdraw amount = + if amount > balance then + failwith "Insufficient funds" + balance <- balance - amount + this`, + }, + + { + description: "Should complete F# async workflow function", + filename: "asyncWorkflow.fs", + input: `let fetchDataAsync url = + async { + use client = new System.Net.Http.HttpClient() + <|fim|> + }`, + llmOutput: `let! response = client.GetStringAsync(url) + return response`, + expectedCompletion: `let! response = client.GetStringAsync(url) + return response`, + }, + { + description: "Should autocomplete SCSS nested class starting inside a rule", + filename: "styles.scss", + input: `nav { + display: flex; + justify-content: space-between; + .logo { + font-size: 1.5rem; + color: #333; + + .brand<|fim|> + } + + ul { + list-style: none; + display: flex; + gap: 1rem; + } +}`, + llmOutput: `-name { + font-weight: bold; + text-transform: uppercase; +}`, + expectedCompletion: `-name { + font-weight: bold; + text-transform: uppercase; +}`, + }, + + { + description: "Should handle SCSS mixin within a class", + filename: "styles.scss", + input: `.card { + border: 1px solid #ccc; + padding: 10px; + + @include<|fim|> + + &:hover { + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); + } +}`, + llmOutput: ` transition(all 0.3s ease);`, + expectedCompletion: ` transition(all 0.3s ease);`, + }, + + { + description: + "Should autocomplete SCSS variable in the middle of a statement", + filename: "styles.scss", + input: `$primary-color: #007bff; +$secondary-color: #6c757d; + +.button { + background-color: <|fim|> color; + padding: 10px 15px; + border: none; + color: #fff; + border-radius: 4px; +}`, + llmOutput: `$primary-`, + expectedCompletion: `$primary-`, + }, + { + description: "Should autocomplete Vue component method", + filename: "MyComponent.vue", + input: ` + + +`, + llmOutput: `() { + this.count = 0; + }`, + expectedCompletion: `() { + this.count = 0; + }`, + }, + { + description: "Should autocomplete Vue computed property", + filename: "UserComponent.vue", + input: ` + + +`, + llmOutput: `() { + return this.firstName + ' ' + this.lastName; + }`, + expectedCompletion: `() { + return this.firstName + ' ' + this.lastName; + }`, + }, + { + description: "Should autocomplete Vue method using props", + filename: "TodoItem.vue", + input: ` + + +`, + llmOutput: `this.completed`, + expectedCompletion: `this.completed`, + }, + { + description: "Should autocomplete Svelte reactive statement", + filename: "Counter.svelte", + input: ` + + + +`, + llmOutput: `doubledCount = count * 2`, + expectedCompletion: `doubledCount = count * 2`, + }, + + { + description: "Should autocomplete Svelte component inside HTML", + filename: "NestedComponent.svelte", + input: ` + + +
+

Hello Svelte

+ /> +
+`, + llmOutput: `name="World"`, + expectedCompletion: `name="World"`, + }, + + { + description: "Should handle autocomplete in Svelte each block", + filename: "List.svelte", + input: ` + + +
    + {#each items as item} +
  • {item}
  • + {/each<|fim|> +
+`, + llmOutput: `}`, + expectedCompletion: `}`, + }, +]; diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts new file mode 100644 index 000000000..5a9b61a72 --- /dev/null +++ b/core/autocomplete/filtering/test/util.ts @@ -0,0 +1,75 @@ +import fs from "node:fs"; +import path from "node:path"; +import Mock from "../../../llm/llms/Mock"; +import { testConfigHandler, testIde } from "../../../test/util/fixtures"; +import { CompletionProvider } from "../../CompletionProvider"; +import { AutocompleteInput } from "../../util/types"; + +const FIM_DELIMITER = "<|fim|>"; + +function parseFimExample(text: string): { prefix: string; suffix: string } { + const [prefix, suffix] = text.split(FIM_DELIMITER); + return { prefix, suffix }; +} + +export interface AutocompleteFileringTestInput { + description: string; + filename: string; + input: string; + llmOutput: string; + expectedCompletion: string | null; + options?: { + only?: boolean; + }; +} + +export async function testAutocompleteFiltering( + test: AutocompleteFileringTestInput, +) { + const { prefix, suffix } = parseFimExample(test.input); + + // Setup necessary objects + const llm = new Mock({ + model: "mock", + }); + llm.completion = test.llmOutput; + const ide = testIde; + const configHandler = testConfigHandler; + + // Create a real file + const [workspaceDir] = await ide.getWorkspaceDirs(); + const filepath = path.join(workspaceDir, test.filename); + fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, "")); + + // Prepare completion input and provider + const completionProvider = new CompletionProvider( + configHandler, + ide, + async () => llm, + () => {}, + async () => [], + ); + + const line = prefix.split("\n").length - 1; + const character = prefix.split("\n")[line].length; + const autocompleteInput: AutocompleteInput = { + clipboardText: "", + completionId: "test-completion-id", + filepath, + pos: { + line, + character, + }, + recentlyEditedFiles: [], + recentlyEditedRanges: [], + }; + + // Generate a completion + const result = await completionProvider.provideInlineCompletionItems( + autocompleteInput, + undefined, + ); + + // Ensure that we return the text that is wanted to be displayed + expect(result?.completion).toEqual(test.expectedCompletion); +} diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts new file mode 100644 index 000000000..3f46f5033 --- /dev/null +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -0,0 +1,68 @@ +import { CompletionOptions, ILLM } from "../.."; +import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline"; +import { HelperVars } from "../util/HelperVars"; +import { GeneratorReuseManager } from "./GeneratorReuseManager"; + +export class CompletionStreamer { + private streamTransformPipeline = new StreamTransformPipeline(); + private generatorReuseManager: GeneratorReuseManager; + + constructor(onError: (err: any) => void) { + this.generatorReuseManager = new GeneratorReuseManager(onError); + } + + async *streamCompletionWithFilters( + token: AbortSignal, + llm: ILLM, + prefix: string, + suffix: string, + prompt: string, + multiline: boolean, + completionOptions: Partial | undefined, + helper: HelperVars, + ) { + // Try to reuse pending requests if what the user typed matches start of completion + const generator = this.generatorReuseManager.getGenerator( + prefix, + () => + llm.supportsFim() + ? llm.streamFim(prefix, suffix, completionOptions) + : llm.streamComplete(prompt, { + ...completionOptions, + raw: true, + }), + multiline, + ); + + // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion + const fullStop = () => + this.generatorReuseManager.currentGenerator?.cancel(); + + // LLM + const generatorWithCancellation = async function* () { + for await (const update of generator) { + if (token.aborted) { + return; + } + yield update; + } + }; + + const initialGenerator = generatorWithCancellation(); + const transformedGenerator = helper.options.transform + ? this.streamTransformPipeline.transform( + initialGenerator, + prefix, + suffix, + multiline, + completionOptions?.stop || [], + fullStop, + helper, + ) + : initialGenerator; + + for await (const update of transformedGenerator) { + yield update; + } + } +} diff --git a/core/autocomplete/util.ts b/core/autocomplete/generation/GeneratorReuseManager.ts similarity index 52% rename from core/autocomplete/util.ts rename to core/autocomplete/generation/GeneratorReuseManager.ts index d07658d17..7a67e686f 100644 --- a/core/autocomplete/util.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -1,78 +1,4 @@ -export class ListenableGenerator { - private _source: AsyncGenerator; - private _buffer: T[] = []; - private _listeners: Set<(value: T) => void> = new Set(); - private _isEnded = false; - - constructor( - source: AsyncGenerator, - private readonly onError: (e: any) => void, - ) { - this._source = source; - this._start(); - } - - public cancel() { - this._isEnded = true; - } - - private async _start() { - try { - for await (const value of this._source) { - if (this._isEnded) { - break; - } - this._buffer.push(value); - for (const listener of this._listeners) { - listener(value); - } - } - } catch (e) { - this.onError(e); - } finally { - this._isEnded = true; - for (const listener of this._listeners) { - listener(null as any); - } - } - } - - listen(listener: (value: T) => void) { - this._listeners.add(listener); - for (const value of this._buffer) { - listener(value); - } - if (this._isEnded) { - listener(null as any); - } - } - - async *tee(): AsyncGenerator { - try { - let i = 0; - while (i < this._buffer.length) { - yield this._buffer[i++]; - } - while (!this._isEnded) { - let resolve: (value: any) => void; - const promise = new Promise((res) => { - resolve = res; - this._listeners.add(resolve!); - }); - await promise; - this._listeners.delete(resolve!); - - // Possible timing caused something to slip in between - // timers so we iterate over the buffer - while (i < this._buffer.length) { - yield this._buffer[i++]; - } - } - } finally { - // this._listeners.delete(resolve!); - } - } -} +import { ListenableGenerator } from "./ListenableGenerator"; export class GeneratorReuseManager { currentGenerator: ListenableGenerator | undefined; diff --git a/core/autocomplete/generation/ListenableGenerator.ts b/core/autocomplete/generation/ListenableGenerator.ts new file mode 100644 index 000000000..0cc9f664e --- /dev/null +++ b/core/autocomplete/generation/ListenableGenerator.ts @@ -0,0 +1,75 @@ +export class ListenableGenerator { + private _source: AsyncGenerator; + private _buffer: T[] = []; + private _listeners: Set<(value: T) => void> = new Set(); + private _isEnded = false; + + constructor( + source: AsyncGenerator, + private readonly onError: (e: any) => void, + ) { + this._source = source; + this._start(); + } + + public cancel() { + this._isEnded = true; + } + + private async _start() { + try { + for await (const value of this._source) { + if (this._isEnded) { + break; + } + this._buffer.push(value); + for (const listener of this._listeners) { + listener(value); + } + } + } catch (e) { + this.onError(e); + } finally { + this._isEnded = true; + for (const listener of this._listeners) { + listener(null as any); + } + } + } + + listen(listener: (value: T) => void) { + this._listeners.add(listener); + for (const value of this._buffer) { + listener(value); + } + if (this._isEnded) { + listener(null as any); + } + } + + async *tee(): AsyncGenerator { + try { + let i = 0; + while (i < this._buffer.length) { + yield this._buffer[i++]; + } + while (!this._isEnded) { + let resolve: (value: any) => void; + const promise = new Promise((res) => { + resolve = res; + this._listeners.add(resolve!); + }); + await promise; + this._listeners.delete(resolve!); + + // Possible timing caused something to slip in between + // timers so we iterate over the buffer + while (i < this._buffer.length) { + yield this._buffer[i++]; + } + } + } finally { + // this._listeners.delete(resolve!); + } + } +} diff --git a/core/autocomplete/postprocessing.ts b/core/autocomplete/postprocessing/index.ts similarity index 71% rename from core/autocomplete/postprocessing.ts rename to core/autocomplete/postprocessing/index.ts index cb3ada459..127874d68 100644 --- a/core/autocomplete/postprocessing.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -1,6 +1,6 @@ -import type { ILLM } from "../index.js"; -import { longestCommonSubsequence } from "../util/lcs.js"; -import { lineIsRepeated } from "./streamTransforms/lineStream.js"; +import type { ILLM } from "../../index.js"; +import { longestCommonSubsequence } from "../../util/lcs.js"; +import { lineIsRepeated } from "../filtering/streamTransforms/lineStream.js"; function rewritesLineAbove(completion: string, prefix: string): boolean { const lineAbove = prefix @@ -42,6 +42,10 @@ function isExtremeRepetition(completion: string): boolean { } return false; } +export function isOnlyWhitespace(completion: string): boolean { + const whitespaceRegex = /^[\s]+$/; + return whitespaceRegex.test(completion); +} export function postprocessCompletion({ completion, @@ -55,7 +59,7 @@ export function postprocessCompletion({ suffix: string; }): string | undefined { // Don't return empty - if (completion.trim().length <= 0) { + if (isOnlyWhitespace(completion)) { return undefined; } @@ -69,9 +73,6 @@ export function postprocessCompletion({ return undefined; } - // Remove trailing whitespace - completion = completion.trimEnd(); - if (llm.model.includes("codestral")) { // Codestral sometimes starts with an extra space if (completion[0] === " " && completion[1] !== " ") { @@ -81,19 +82,23 @@ export function postprocessCompletion({ } } - // If completion starts with multiple whitespaces, but the cursor is at the end of the line - // then it should probably be on a new line - if ( - (completion.startsWith(" ") || completion.startsWith("\t")) && - !prefix.endsWith("\n") && - (suffix.startsWith("\n") || suffix.trim().length === 0) - ) { - // completion = "\n" + completion; - return undefined; - } + // // If completion starts with multiple whitespaces, but the cursor is at the end of the line + // // then it should probably be on a new line + // if ( + // (completion.startsWith(" ") || completion.startsWith("\t")) && + // !prefix.endsWith("\n") && + // (suffix.startsWith("\n") || suffix.trim().length === 0) + // ) { + // completion = "\n" + completion; + // } // If prefix ends with space and so does completion, then remove the space from completion - if (prefix.endsWith(" ") && completion.startsWith(" ")) { + if ( + prefix.split("\n").pop()?.trim() !== "" && + prefix.endsWith(" ") && + completion.startsWith(" ") + ) { + const test = prefix.split("\n").pop()?.trim() !== ""; completion = completion.slice(1); } diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts new file mode 100644 index 000000000..a7343817d --- /dev/null +++ b/core/autocomplete/prefiltering/index.ts @@ -0,0 +1,78 @@ +import path from "node:path"; +import { IDE } from "../.."; +import { getBasename } from "../../util"; +import { getConfigJsonPath } from "../../util/paths"; +import { HelperVars } from "../util/HelperVars"; + +async function isDisabledForFile( + currentFilepath: string, + disableInFiles: string[] | undefined, + ide: IDE, +) { + if (disableInFiles) { + // Relative path needed for `ignore` + const workspaceDirs = await ide.getWorkspaceDirs(); + let filepath = currentFilepath; + for (const workspaceDir of workspaceDirs) { + const relativePath = path.relative(workspaceDir, filepath); + const relativePathBase = relativePath.split(path.sep).at(0); + const isInWorkspace = + !path.isAbsolute(relativePath) && relativePathBase !== ".."; + if (isInWorkspace) { + filepath = path.relative(workspaceDir, filepath); + break; + } + } + + // Worst case we can check filetype glob patterns + if (filepath === currentFilepath) { + filepath = getBasename(filepath); + } + + // @ts-ignore + const pattern = ignore.default().add(options.disableInFiles); + if (pattern.ignores(filepath)) { + return true; + } + } +} + +async function shouldLanguageSpecificPrefilter(helper: HelperVars) { + const line = helper.fileLines[helper.pos.line] ?? ""; + for (const endOfLine of helper.lang.endOfLine) { + if (line.endsWith(endOfLine) && helper.pos.character >= line.length) { + return true; + } + } +} + +export async function shouldPrefilter( + helper: HelperVars, + ide: IDE, +): Promise { + // Allow disabling autocomplete from config.json + if (helper.options.disable) { + return true; + } + + // Check whether we're in the continue config.json file + if (helper.filepath === getConfigJsonPath()) { + return true; + } + + // Check whether autocomplete is disabled for this file + if ( + await isDisabledForFile(helper.filepath, helper.options.disableInFiles, ide) + ) { + return true; + } + + // if ( + // helper.options.transform && + // (await shouldLanguageSpecificPrefilter(helper)) + // ) { + // return true; + // } + + return false; +} diff --git a/core/autocomplete/recentlyEdited.ts b/core/autocomplete/recentlyEdited.ts deleted file mode 100644 index d0e7817ed..000000000 --- a/core/autocomplete/recentlyEdited.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { RangeInFile } from "../index.js"; - -export type RecentlyEditedRange = RangeInFile & { - timestamp: number; - lines: string[]; - symbols: Set; -}; - -export function findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, -): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); -} diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts deleted file mode 100644 index 422b377bd..000000000 --- a/core/autocomplete/retrieval.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { BranchAndDir, Chunk } from "../index.js"; -import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js"; - -export async function fullTextRetrieve( - prefix: string, - suffix: string, - indexTag: BranchAndDir, -): Promise { - const index = new FullTextSearchCodebaseIndex(); - const searchStrings = prefix.split("\n").slice(-3); - const results: Chunk[] = []; - searchStrings.forEach(async (searchString) => { - const chunks = await index.retrieve( - [indexTag], - searchString, - 3, - undefined, - undefined, - ); - results.push(...chunks); - }); - return results; -} diff --git a/core/autocomplete/shouldCompleteMultiline.ts b/core/autocomplete/shouldCompleteMultiline.ts deleted file mode 100644 index ae114151d..000000000 --- a/core/autocomplete/shouldCompleteMultiline.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { AstPath } from "./ast"; -import { AutocompleteLanguageInfo } from "./languages"; - -const BLOCK_TYPES = ["body", "statement_block"]; - -function shouldCompleteMultilineAst( - treePath: AstPath, - cursorLine: number, -): boolean { - // If at the base of the file, do multiline - if (treePath.length === 1) { - return true; - } - - // If at the first line of an otherwise empty funtion body, do multiline - for (let i = treePath.length - 1; i >= 0; i--) { - const node = treePath[i]; - if ( - BLOCK_TYPES.includes(node.type) && - Math.abs(node.startPosition.row - cursorLine) <= 1 - ) { - let text = node.text; - text = text.slice(text.indexOf("{") + 1); - text = text.slice(0, text.lastIndexOf("}")); - text = text.trim(); - return text.split("\n").length === 1; - } - } - - return false; -} - -function isMidlineCompletion(prefix: string, suffix: string): boolean { - return !suffix.startsWith("\n"); -} - -export async function shouldCompleteMultiline( - treePath: AstPath | undefined, - fullPrefix: string, - fullSuffix: string, - language: AutocompleteLanguageInfo, -): Promise { - // Don't complete multi-line if you are mid-line - if (isMidlineCompletion(fullPrefix, fullSuffix)) { - return false; - } - - // Don't complete multi-line for single-line comments - if ( - fullPrefix - .split("\n") - .slice(-1)[0] - ?.trimStart() - .startsWith(language.singleLineComment) - ) { - return false; - } - - // First, if the line before ends with an opening bracket, then assume multi-line - if ( - ["{", "(", "["].includes( - fullPrefix.split("\n").slice(-2)[0]?.trim().slice(-1)[0], - ) - ) { - return true; - } - - // Use AST to determine whether to complete multiline - let completeMultiline = false; - if (treePath) { - const cursorLine = fullPrefix.split("\n").length - 1; - completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine); - } - return completeMultiline; -} diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templating/AutocompleteTemplate.ts similarity index 97% rename from core/autocomplete/templates.ts rename to core/autocomplete/templating/AutocompleteTemplate.ts index cda8b8a2d..ae8cf1487 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -1,10 +1,10 @@ // Fill in the middle prompts -import { CompletionOptions } from "../index.js"; -import { getLastNPathParts, shortestRelativePaths } from "../util/index.js"; -import { AutocompleteSnippet } from "./ranking.js"; +import { CompletionOptions } from "../../index.js"; +import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; +import { AutocompleteSnippet } from "../context/ranking/index.js"; -interface AutocompleteTemplate { +export interface AutocompleteTemplate { compilePrefixSuffix?: ( prefix: string, suffix: string, diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts new file mode 100644 index 000000000..d4024bf06 --- /dev/null +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -0,0 +1,44 @@ +import { IDE } from "../.."; +import { getRangeInString } from "../../util/ranges"; +import { languageForFilepath } from "../constants/AutocompleteLanguageInfo"; + +import { AutocompleteInput } from "../util/types"; + +/** + * We have to handle a few edge cases in getting the entire prefix/suffix for the current file. + * This is entirely prior to finding snippets from other files + */ +export async function constructInitialPrefixSuffix( + input: AutocompleteInput, + ide: IDE, +): Promise<{ + prefix: string; + suffix: string; +}> { + const lang = languageForFilepath(input.filepath); + + const fileContents = + input.manuallyPassFileContents ?? (await ide.readFile(input.filepath)); + const fileLines = fileContents.split("\n"); + let prefix = + getRangeInString(fileContents, { + start: { line: 0, character: 0 }, + end: input.selectedCompletionInfo?.range.start ?? input.pos, + }) + (input.selectedCompletionInfo?.text ?? ""); + + if (input.injectDetails) { + const lines = prefix.split("\n"); + prefix = `${lines.slice(0, -1).join("\n")}\n${ + lang.singleLineComment + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; + } + + const suffix = getRangeInString(fileContents, { + start: input.pos, + end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, + }); + + return { prefix, suffix }; +} diff --git a/core/autocomplete/templating/getStopTokens.ts b/core/autocomplete/templating/getStopTokens.ts new file mode 100644 index 000000000..fffb5351b --- /dev/null +++ b/core/autocomplete/templating/getStopTokens.ts @@ -0,0 +1,33 @@ +import { CompletionOptions } from "../.."; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; + +const DOUBLE_NEWLINE = "\n\n"; +const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; +// TODO: Do we want to stop completions when reaching a `/src/` string? +const SRC_DIRECTORY = "/src/"; +// Starcoder2 tends to output artifacts starting with the letter "t" +const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; +const PYTHON_ENCODING = "#- coding: utf-8"; +const CODE_BLOCK_END = "```"; + +const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; +const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; + +export function getStopTokens( + completionOptions: Partial | undefined, + lang: AutocompleteLanguageInfo, + model: string, +): string[] { + const stopTokens = [ + ...(completionOptions?.stop || []), + // ...multilineStops, + ...commonStops, + ...(model.toLowerCase().includes("starcoder2") + ? STARCODER2_T_ARTIFACTS + : []), + ...(lang.stopWords ?? []), + // ...lang.topLevelKeywords.map((word) => `\n${word}`), + ]; + + return stopTokens; +} diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts new file mode 100644 index 000000000..05a10bbed --- /dev/null +++ b/core/autocomplete/templating/index.ts @@ -0,0 +1,149 @@ +import Handlebars from "handlebars"; +import { CompletionOptions } from "../.."; +import { getBasename, getLastNPathParts } from "../../util"; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { AutocompleteSnippet } from "../context/ranking"; +import { HelperVars } from "../util/HelperVars"; +import { + AutocompleteTemplate, + getTemplateForModel, +} from "./AutocompleteTemplate"; +import { getStopTokens } from "./getStopTokens"; + +export function formatExternalSnippet( + filepath: string, + snippet: string, + language: AutocompleteLanguageInfo, +) { + const comment = language.singleLineComment; + const lines = [ + `${comment} Path: ${getBasename(filepath)}`, + ...snippet + .trim() + .split("\n") + .map((line) => `${comment} ${line}`), + comment, + ]; + return lines.join("\n"); +} +function renderStringTemplate( + template: string, + prefix: string, + suffix: string, + snippets: AutocompleteSnippet[], + lang: AutocompleteLanguageInfo, + filepath: string, + reponame: string, +) { + const filename = getBasename(filepath); + const compiledTemplate = Handlebars.compile(template); + + // Format snippets as comments and prepend to prefix + const formattedSnippets = snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n"); + if (formattedSnippets.length > 0) { + prefix = `${formattedSnippets}\n\n${prefix}`; + } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { + // If it's an empty file, include the file name as a comment + prefix = `${lang.singleLineComment} ${getLastNPathParts( + filepath, + 2, + )}\n${prefix}`; + } + + const prompt = compiledTemplate({ + prefix, + suffix, + filename, + reponame, + language: lang.name, + }); + return prompt; +} + +function getTemplate(helper: HelperVars): AutocompleteTemplate { + if (helper.options.template) { + return { + template: helper.options.template, + completionOptions: {}, + compilePrefixSuffix: undefined, + }; + } + return getTemplateForModel(helper.modelName); +} + +export function renderPrompt( + snippets: AutocompleteSnippet[], + workspaceDirs: string[], + helper: HelperVars, +): { + prompt: string; + prefix: string; + suffix: string; + completionOptions: Partial | undefined; +} { + // If prefix is manually passed + let prefix = helper.prunedPrefix; + let suffix = helper.prunedSuffix; + + if (helper.input.manuallyPassPrefix) { + prefix = helper.input.manuallyPassPrefix; + suffix = ""; + } + + let prompt: string; + const reponame = getBasename(workspaceDirs[0] ?? "myproject"); + + let { template, compilePrefixSuffix, completionOptions } = + getTemplate(helper); + + // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix + // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint + if (compilePrefixSuffix) { + [prefix, suffix] = compilePrefixSuffix( + prefix, + suffix, + helper.filepath, + reponame, + snippets, + ); + } + + // Templates can be passed as a Handlebars template string or a function + if (typeof template === "string") { + prompt = renderStringTemplate( + template, + prefix, + suffix, + snippets, + helper.lang, + helper.filepath, + reponame, + ); + } else { + prompt = template( + prefix, + suffix, + helper.filepath, + reponame, + helper.lang.name, + snippets, + ); + } + + const stopTokens = getStopTokens( + completionOptions, + helper.lang, + helper.modelName, + ); + + completionOptions = { + ...completionOptions, + stop: stopTokens, + }; + + return { prompt, prefix, suffix, completionOptions }; +} diff --git a/core/autocomplete/util/AutocompleteDebouncer.ts b/core/autocomplete/util/AutocompleteDebouncer.ts new file mode 100644 index 000000000..f8bcc474f --- /dev/null +++ b/core/autocomplete/util/AutocompleteDebouncer.ts @@ -0,0 +1,32 @@ +import { v4 as uuidv4 } from "uuid"; +export class AutocompleteDebouncer { + private debounceTimeout: NodeJS.Timeout | undefined = undefined; + private debouncing = false; + private lastUUID: string | undefined = undefined; + + async delayAndShouldDebounce(debounceDelay: number): Promise { + // Debounce + const uuid = uuidv4(); + this.lastUUID = uuid; + + // Debounce + if (this.debouncing) { + this.debounceTimeout?.refresh(); + const lastUUID = await new Promise((resolve) => + setTimeout(() => { + resolve(this.lastUUID); + }, debounceDelay), + ); + if (uuid !== lastUUID) { + return true; + } + } else { + this.debouncing = true; + this.debounceTimeout = setTimeout(async () => { + this.debouncing = false; + }, debounceDelay); + } + + return false; + } +} diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts new file mode 100644 index 000000000..7fd3d24cb --- /dev/null +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -0,0 +1,119 @@ +import { logDevData } from "../../util/devdata"; +import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters"; +import { Telemetry } from "../../util/posthog"; +import { AutocompleteOutcome } from "./types"; + +export class AutocompleteLoggingService { + // Key is completionId + private _abortControllers = new Map(); + private _logRejectionTimeouts = new Map(); + private _outcomes = new Map(); + _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined = + undefined; + + public createAbortController(completionId: string): AbortController { + const abortController = new AbortController(); + this._abortControllers.set(completionId, abortController); + return abortController; + } + + public deleteAbortController(completionId: string) { + this._abortControllers.delete(completionId); + } + + public cancel() { + this._abortControllers.forEach((abortController, id) => { + abortController.abort(); + }); + this._abortControllers.clear(); + } + + public accept(completionId: string): AutocompleteOutcome | undefined { + if (this._logRejectionTimeouts.has(completionId)) { + clearTimeout(this._logRejectionTimeouts.get(completionId)); + this._logRejectionTimeouts.delete(completionId); + } + + if (this._outcomes.has(completionId)) { + const outcome = this._outcomes.get(completionId)!; + this.logAutocompleteOutcome(outcome); + this._outcomes.delete(completionId); + return outcome; + } + } + + public cancelRejectionTimeout(completionId: string) { + if (this._logRejectionTimeouts.has(completionId)) { + clearTimeout(this._logRejectionTimeouts.get(completionId)!); + this._logRejectionTimeouts.delete(completionId); + } + + if (this._outcomes.has(completionId)) { + this._outcomes.delete(completionId); + } + } + + public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { + const logRejectionTimeout = setTimeout(() => { + // Wait 10 seconds, then assume it wasn't accepted + outcome.accepted = false; + this.logAutocompleteOutcome(outcome); + this._logRejectionTimeouts.delete(completionId); + }, COUNT_COMPLETION_REJECTED_AFTER); + this._outcomes.set(completionId, outcome); + this._logRejectionTimeouts.set(completionId, logRejectionTimeout); + + // If the previously displayed completion is still waiting for rejection, + // and this one is a continuation of that (the outcome.completion is the same modulo prefix) + // then we should cancel the rejection timeout + const previous = this._lastDisplayedCompletion; + const now = Date.now(); + if (previous && this._logRejectionTimeouts.has(previous.id)) { + const previousOutcome = this._outcomes.get(previous.id); + const c1 = previousOutcome?.completion.split("\n")[0] ?? ""; + const c2 = outcome.completion.split("\n")[0]; + if ( + previousOutcome && + (c1.endsWith(c2) || + c2.endsWith(c1) || + c1.startsWith(c2) || + c2.startsWith(c1)) + ) { + this.cancelRejectionTimeout(previous.id); + } else if (now - previous.displayedAt < 500) { + // If a completion isn't shown for more than + this.cancelRejectionTimeout(previous.id); + } + } + + this._lastDisplayedCompletion = { + id: completionId, + displayedAt: now, + }; + } + + private logAutocompleteOutcome(outcome: AutocompleteOutcome) { + outcome.accepted = true; + logDevData("autocomplete", outcome); + const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; + void Telemetry.capture( + "autocomplete", + { + accepted: restOfOutcome.accepted, + cacheHit: restOfOutcome.cacheHit, + completionId: restOfOutcome.completionId, + completionOptions: restOfOutcome.completionOptions, + debounceDelay: restOfOutcome.debounceDelay, + fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], + maxPromptTokens: restOfOutcome.maxPromptTokens, + modelName: restOfOutcome.modelName, + modelProvider: restOfOutcome.modelProvider, + multilineCompletions: restOfOutcome.multilineCompletions, + time: restOfOutcome.time, + useRecentlyEdited: restOfOutcome.useRecentlyEdited, + useRootPathContext: restOfOutcome.useRootPathContext, + }, + true, + ); + } +} diff --git a/core/autocomplete/cache.ts b/core/autocomplete/util/AutocompleteLruCache.ts similarity index 91% rename from core/autocomplete/cache.ts rename to core/autocomplete/util/AutocompleteLruCache.ts index 5005480bf..ec9478c8a 100644 --- a/core/autocomplete/cache.ts +++ b/core/autocomplete/util/AutocompleteLruCache.ts @@ -1,18 +1,17 @@ import { Mutex } from "async-mutex"; import { open } from "sqlite"; import sqlite3 from "sqlite3"; -import { DatabaseConnection } from "../indexing/refreshIndex.js"; -import { getTabAutocompleteCacheSqlitePath } from "../util/paths.js"; +import { + DatabaseConnection, + truncateSqliteLikePattern, +} from "../../indexing/refreshIndex.js"; +import { getTabAutocompleteCacheSqlitePath } from "../../util/paths.js"; export class AutocompleteLruCache { private static capacity = 1000; private mutex = new Mutex(); - db: DatabaseConnection; - - constructor(db: DatabaseConnection) { - this.db = db; - } + constructor(private db: DatabaseConnection) {} static async get(): Promise { const db = await open({ @@ -41,7 +40,7 @@ export class AutocompleteLruCache { // Have to make sure we take the key with shortest length const result = await this.db.get( "SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1", - prefix, + truncateSqliteLikePattern(prefix), ); // Validate that the cached compeltion is a valid completion for the prefix diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts new file mode 100644 index 000000000..a6ecb21a9 --- /dev/null +++ b/core/autocomplete/util/HelperVars.ts @@ -0,0 +1,175 @@ +import { IDE, TabAutocompleteOptions } from "../.."; +import { + countTokens, + pruneLinesFromBottom, + pruneLinesFromTop, +} from "../../llm/countTokens"; +import { + AutocompleteLanguageInfo, + languageForFilepath, +} from "../constants/AutocompleteLanguageInfo"; +import { constructInitialPrefixSuffix } from "../templating/constructPrefixSuffix"; +import { AstPath, getAst, getTreePathAtCursor } from "./ast"; +import { AutocompleteInput } from "./types"; + +/** + * A collection of variables that are often accessed throughout the autocomplete pipeline + * It's noisy to re-calculate all the time or inject them into each function + */ +export class HelperVars { + lang: AutocompleteLanguageInfo; + treePath: AstPath | undefined; + + private _fileContents: string | undefined; + private _fileLines: string[] | undefined; + private _fullPrefix: string | undefined; + private _fullSuffix: string | undefined; + private _prunedPrefix: string | undefined; + private _prunedSuffix: string | undefined; + + private constructor( + public readonly input: AutocompleteInput, + public readonly options: TabAutocompleteOptions, + public readonly modelName: string, + private readonly ide: IDE, + ) { + this.lang = languageForFilepath(input.filepath); + } + + private async init() { + // Don't do anything if already initialized + if (this._fileContents !== undefined) return; + + this._fileContents = + this.input.manuallyPassFileContents ?? + (await this.ide.readFile(this.filepath)); + + this._fileLines = this._fileContents.split("\n"); + + // Construct full prefix/suffix (a few edge cases handled in here) + const { prefix: fullPrefix, suffix: fullSuffix } = + await constructInitialPrefixSuffix(this.input, this.ide); + this._fullPrefix = fullPrefix; + this._fullSuffix = fullSuffix; + + const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix(); + this._prunedPrefix = prunedPrefix; + this._prunedSuffix = prunedSuffix; + + try { + const ast = await getAst(this.filepath, fullPrefix + fullSuffix); + if (ast) { + this.treePath = await getTreePathAtCursor(ast, fullPrefix.length); + } + } catch (e) { + console.error("Failed to parse AST", e); + } + } + + static async create( + input: AutocompleteInput, + options: TabAutocompleteOptions, + modelName: string, + ide: IDE, + ): Promise { + const instance = new HelperVars(input, options, modelName, ide); + await instance.init(); + return instance; + } + + prunePrefixSuffix() { + // Construct basic prefix + const maxPrefixTokens = + this.options.maxPromptTokens * this.options.prefixPercentage; + const prunedPrefix = pruneLinesFromTop( + this.fullPrefix, + maxPrefixTokens, + this.modelName, + ); + + // Construct suffix + const maxSuffixTokens = Math.min( + this.options.maxPromptTokens - countTokens(prunedPrefix, this.modelName), + this.options.maxSuffixPercentage * this.options.maxPromptTokens, + ); + const prunedSuffix = pruneLinesFromBottom( + this.fullSuffix, + maxSuffixTokens, + this.modelName, + ); + + return { + prunedPrefix, + prunedSuffix, + }; + } + + // Fast access + get filepath() { + return this.input.filepath; + } + get pos() { + return this.input.pos; + } + get maxSnippetTokens() { + return this.options.maxPromptTokens * this.options.maxSnippetPercentage; + } + get prunedCaretWindow() { + return this.prunedPrefix + this.prunedSuffix; + } + + // Getters for lazy access + get fileContents(): string { + if (this._fileContents === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fileContents", + ); + } + return this._fileContents; + } + + get fileLines(): string[] { + if (this._fileLines === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fileLines", + ); + } + return this._fileLines; + } + + get fullPrefix(): string { + if (this._fullPrefix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fullPrefix", + ); + } + return this._fullPrefix; + } + + get fullSuffix(): string { + if (this._fullSuffix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fullSuffix", + ); + } + return this._fullSuffix; + } + + get prunedPrefix(): string { + if (this._prunedPrefix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing prunedPrefix", + ); + } + return this._prunedPrefix; + } + + get prunedSuffix(): string { + if (this._prunedSuffix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing prunedSuffix", + ); + } + return this._prunedSuffix; + } +} diff --git a/core/autocomplete/ast.ts b/core/autocomplete/util/ast.ts similarity index 94% rename from core/autocomplete/ast.ts rename to core/autocomplete/util/ast.ts index 139b22dbf..600b84126 100644 --- a/core/autocomplete/ast.ts +++ b/core/autocomplete/util/ast.ts @@ -1,6 +1,6 @@ import Parser from "web-tree-sitter"; -import { RangeInFileWithContents } from "../commands/util.js"; -import { getParserForFile } from "../util/treeSitter.js"; +import { RangeInFileWithContents } from "../../commands/util.js"; +import { getParserForFile } from "../../util/treeSitter.js"; export type AstPath = Parser.SyntaxNode[]; diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts new file mode 100644 index 000000000..44ee9fab1 --- /dev/null +++ b/core/autocomplete/util/types.ts @@ -0,0 +1,43 @@ +import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../.."; +import { RangeInFileWithContents } from "../../commands/util"; + +export type RecentlyEditedRange = RangeInFile & { + timestamp: number; + lines: string[]; + symbols: Set; +}; + +export interface AutocompleteInput { + completionId: string; + filepath: string; + pos: Position; + recentlyEditedFiles: RangeInFileWithContents[]; + recentlyEditedRanges: RecentlyEditedRange[]; + clipboardText: string; + // Used for notebook files + manuallyPassFileContents?: string; + // Used for VS Code git commit input box + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + injectDetails?: string; +} + +export interface AutocompleteOutcome extends TabAutocompleteOptions { + accepted?: boolean; + time: number; + prefix: string; + suffix: string; + prompt: string; + completion: string; + modelProvider: string; + modelName: string; + completionOptions: any; + cacheHit: boolean; + filepath: string; + gitRepo?: string; + completionId: string; + uniqueId: string; +} diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index c39fb2dc0..fc71838df 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -6,7 +6,7 @@ import { fixCodeLlamaFirstLineIndentation, stopAtLines, streamWithNewLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { stripImages } from "../../llm/images"; import { @@ -95,10 +95,10 @@ export async function getPromptParts( } let filePrefix = fullFileContentsList - .slice(curStartLine, maxStartLine) + .slice(curStartLine, maxStartLine - 1) .join("\n"); let fileSuffix = fullFileContentsList - .slice(minEndLine, curEndLine - 1) + .slice(minEndLine, curEndLine + 1) .join("\n"); if (rif.contents.length > 0) { diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index f94c6ee05..472684a7e 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -4,9 +4,10 @@ import CommitMessageCommand from "./commit"; import DraftIssueCommand from "./draftIssue"; import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; +import MultiFileEditSlashCommand from "./multifileEdit"; +import OnboardSlashCommand from "./onboard"; import ReviewMessageCommand from "./review"; import ShareSlashCommand from "./share"; -import OnboardSlashCommand from "./onboard"; export default [ DraftIssueCommand, @@ -18,4 +19,5 @@ export default [ CommitMessageCommand, ReviewMessageCommand, OnboardSlashCommand, + MultiFileEditSlashCommand, ]; diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts new file mode 100644 index 000000000..ffda6b703 --- /dev/null +++ b/core/commands/slash/multifileEdit.ts @@ -0,0 +1,108 @@ +import { SlashCommand } from "../.."; +import { getFullyQualifiedPath } from "../../../extensions/vscode/src/util/util"; +import { VsCodeIde } from "../../../extensions/vscode/src/VsCodeIde"; +import { stripImages } from "../../llm/images"; + +const MultiFileEditSlashCommand: SlashCommand = { + name: "multifile-edit", + description: "Edit multiple files in the codebase at once", + run: async function* ({ llm, contextItems, selectedCode, input, ide }) { + const selectedCodeStr = ( + await Promise.all( + selectedCode.map(async (item) => { + // Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]` + const [filepath, rangeStr] = item.filepath.split(" "); + const fullPath = getFullyQualifiedPath(ide as VsCodeIde, filepath); + + if (!fullPath) { + return ""; + } + + const codeStr = await ide.readRangeInFile(fullPath, item.range); + + // Include the filepath so the model can map it correctly with codeblock outputs + return `\`\`\`${fullPath} ${rangeStr}\n${codeStr}\`\`\``; + }), + ) + ).join("\n"); + + const fileContextItemsStr = contextItems + .filter((item) => item.uri?.type === "file") + .map((item) => item.content) + .join("\n"); + + const filesToEditStr = fileContextItemsStr + "\n" + selectedCodeStr; + + const additionalContextStr = contextItems + .filter((item) => item.uri?.type !== "file") + .map((item) => `${item.description}: ${item.content}`) + .join("\n"); + + const content = createPrompt(filesToEditStr, additionalContextStr, input); + + for await (const chunk of llm.streamChat([{ role: "user", content }])) { + yield stripImages(chunk.content); + } + }, +}; + +function createPrompt( + filesToEditStr: string, + additionalContextStr: string, + input: string, +): string { + return ` +You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: + +1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!" +2. When providing instructions, if a user needs to interact with a CLI, walk them through each step +2. Perform file edits in a logical, sequential ordering +3. For each file edit, provide a brief explanation of the changes +4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. + a. When creating new files, also inlcude the filname in the language specifier of the code block. +6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits + +Remember to be concise and focus on the code changes and their impact. + +Here's an example of how your response should be structured: + + +I'll make the following changes to implement feature X: + +1. First, I'll modify file1.js to add a new function: +\`\`\`javascript /path/to/file1.js +// Entire content of file1.js or changes to be made +\`\`\` + +2. Next, let's create a new test file: +\`\`\`javascript /path/to/file1.test.js +# Entire content of file2.py or changes to be made +\`\`\` + +Summary: +- [Sequential overview of the most important 3-5 edits] + + +Now, let's make the changes based on the engineer's request: + + +${input} + + +Here are the files to base your edits on: + + +${filesToEditStr} + + +And here is any additional context the engineer has provided: + + +${additionalContextStr} + + +Please provide the multi-file edit details based on the engineer's request. + `; +} + +export default MultiFileEditSlashCommand; diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index a615ec70d..a43b694da 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -1,7 +1,7 @@ import * as fs from "node:fs"; import { homedir } from "node:os"; import path from "path"; -import { languageForFilepath } from "../../autocomplete/constructPrompt.js"; +import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../index.js"; import { stripImages } from "../../llm/images.js"; diff --git a/core/config/default.ts b/core/config/default.ts index 634c8c599..814552e75 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -6,7 +6,7 @@ import { } from "../"; export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = { - model: "claude-3-5-sonnet-20240620", + model: "claude-3-5-sonnet-latest", provider: "anthropic", apiKey: "", title: "Claude 3.5 Sonnet", @@ -23,7 +23,7 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [ { title: "Claude 3.5 Sonnet (Free Trial)", provider: "free-trial", - model: "claude-3-5-sonnet-20240620", + model: "claude-3-5-sonnet-latest", systemMessage: "You are an expert software developer. You give helpful and concise responses.", }, diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index ec407974a..5862fab6c 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -6,9 +6,9 @@ import { IdeSettings, SerializedContinueConfig, } from "../../index.js"; +import { ConfigResult } from "../load.js"; import { IProfileLoader } from "./IProfileLoader.js"; import doLoadConfig from "./doLoadConfig.js"; -import { ConfigResult } from "../load.js"; export default class ControlPlaneProfileLoader implements IProfileLoader { private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes @@ -45,7 +45,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { )) as any); const serializedConfig: SerializedContinueConfig = settings; - return doLoadConfig( + const results = await doLoadConfig( this.ide, this.ideSettingsPromise, this.controlPlaneClient, @@ -53,6 +53,11 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { serializedConfig, this.workspaceId, ); + + return { + ...results, + errors: [], // Don't do config validation here, it happens in admin panel + }; } setIsActive(isActive: boolean): void {} diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index aa8806867..7d1255618 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -1,22 +1,20 @@ -import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js"; -import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; -import { - ControlPlaneClient, - DEFAULT_CONTROL_PLANE_PROXY_URL, -} from "../../control-plane/client.js"; -import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import { ContinueConfig, ContinueRcJson, IDE, IdeSettings, SerializedContinueConfig, -} from "../../index.js"; -import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js"; -import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js"; -import { Telemetry } from "../../util/posthog.js"; -import { TTS } from "../../util/tts.js"; -import { ConfigResult, loadFullConfigNode } from "../load.js"; +} from "../../"; +import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js"; +import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; +import { ControlPlaneClient } from "../../control-plane/client.js"; +import { controlPlaneEnv } from "../../control-plane/env.js"; +import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; +import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider"; +import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; +import { Telemetry } from "../../util/posthog"; +import { TTS } from "../../util/tts"; +import { ConfigResult, loadFullConfigNode } from "../load"; export default async function doLoadConfig( ide: IDE, @@ -26,13 +24,7 @@ export default async function doLoadConfig( overrideConfigJson: SerializedContinueConfig | undefined, workspaceId?: string, ): Promise> { - let workspaceConfigs: ContinueRcJson[] = []; - try { - workspaceConfigs = await ide.getWorkspaceConfigs(); - } catch (e) { - console.warn("Failed to load workspace configs"); - } - + const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); const uniqueId = await ide.getUniqueId(); const ideSettings = await ideSettingsPromise; @@ -71,10 +63,13 @@ export default async function doLoadConfig( await TTS.setup(); // Set up control plane proxy if configured - let controlPlaneProxyUrl: string = - (newConfig as any).controlPlane?.useContinueForTeamsProxy === false - ? (newConfig as any).controlPlane?.proxyUrl - : DEFAULT_CONTROL_PLANE_PROXY_URL; + const controlPlane = (newConfig as any).controlPlane; + const useOnPremProxy = + controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl; + let controlPlaneProxyUrl: string = useOnPremProxy + ? controlPlane?.proxyUrl + : controlPlaneEnv.DEFAULT_CONTROL_PLANE_PROXY_URL; + if (!controlPlaneProxyUrl.endsWith("/")) { controlPlaneProxyUrl += "/"; } @@ -127,3 +122,21 @@ async function injectControlPlaneProxyInfo( return config; } + +async function getWorkspaceConfigs(ide: IDE): Promise { + const ideInfo = await ide.getIdeInfo(); + let workspaceConfigs: ContinueRcJson[] = []; + + try { + workspaceConfigs = await ide.getWorkspaceConfigs(); + + // Config is sent over the wire from JB so we need to parse it + if (ideInfo.ideType === "jetbrains") { + workspaceConfigs = (workspaceConfigs as any).map(JSON.parse); + } + } catch (e) { + console.debug("Failed to load workspace configs: ", e); + } + + return workspaceConfigs; +} diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index ebbbd59ab..728090fcc 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -1,11 +1,12 @@ import Handlebars from "handlebars"; import path from "path"; import * as YAML from "yaml"; -import type { IDE, SlashCommand } from ".."; +import type { ChatHistory, ChatHistoryItem, ChatMessage, ContextItem, ContinueSDK, IContextProvider, IDE, SlashCommand } from ".."; import { walkDir } from "../indexing/walkDir"; import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; import { getBasename } from "../util/index"; +import { BaseContextProvider } from "../context"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; @@ -147,28 +148,32 @@ function extractUserInput(input: string, commandName: string): string { return input; } -async function renderPrompt(prompt: string, context: any, userInput: string) { +async function renderPrompt(prompt: string, context: ContinueSDK, 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(false); - const currentFilePath = await context.ide.getCurrentFile(); - const currentFile = currentFilePath - ? await context.ide.readFile(currentFilePath) - : undefined; + const currentFile = await context.ide.getCurrentFile(); + const inputData: Record = { + diff, + input: userInput, + }; + if (currentFile) { + inputData.currentFile = currentFile.path; + } return renderTemplatedString( prompt, context.ide.readFile.bind(context.ide), - { diff, currentFile, input: userInput }, + inputData, helpers, ); } function getContextProviderHelpers( - context: any, + context: ContinueSDK, ): Array<[string, Handlebars.HelperDelegate]> | undefined { - return context.config.contextProviders?.map((provider: any) => [ + return context.config.contextProviders?.map((provider: IContextProvider) => [ provider.description.title, async (helperContext: any) => { const items = await provider.getContextItems(helperContext, { @@ -182,16 +187,16 @@ function getContextProviderHelpers( selectedCode: context.selectedCode, }); - items.forEach((item: any) => + items.forEach((item) => context.addContextItem(createContextItem(item, provider)), ); - return items.map((item: any) => item.content).join("\n\n"); + return items.map((item) => item.content).join("\n\n"); }, ]); } -function createContextItem(item: any, provider: any) { +function createContextItem(item: ContextItem, provider: IContextProvider) { return { ...item, id: { @@ -202,7 +207,7 @@ function createContextItem(item: any, provider: any) { } function updateChatHistory( - history: any[], + history: ChatMessage[], commandName: string, renderedPrompt: string, systemMessage?: string, diff --git a/core/config/types.ts b/core/config/types.ts index 390bc5519..f457812d1 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -49,7 +49,7 @@ declare global { apiBase?: string; cacheBehavior?: CacheBehavior; - engine?: string; + deployment?: string; apiVersion?: string; apiType?: string; region?: string; @@ -322,7 +322,7 @@ declare global { accountId?: string; // Azure options - engine?: string; + deployment?: string; apiVersion?: string; apiType?: string; @@ -338,11 +338,7 @@ declare global { capabilities?: ModelCapability; // IBM watsonx options - watsonxUrl?: string; - watsonxCreds?: string; - watsonxProjectId?: string; - watsonxStopToken?: string; - watsonxApiVersion?: string; + deploymentId?: string; } type RequireAtLeastOne = Pick< T, @@ -467,7 +463,11 @@ declare global { stepIndex: number, ): Promise; getOpenFiles(): Promise; - getCurrentFile(): Promise; + getCurrentFile(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string): Promise<[string, string]>; @@ -602,7 +602,8 @@ declare global { | "watsonx" | "openrouter" | "sambanova" - | "nvidia"; + | "nvidia" + | "nebius"; export type ModelName = | "AUTODETECT" @@ -651,6 +652,7 @@ declare global { | "gemma-7b-it" | "gemma2-9b-it" // Anthropic + | "claude-3-5-sonnet-latest" | "claude-3-5-sonnet-20240620" | "claude-3-opus-20240229" | "claude-3-sonnet-20240229" @@ -768,17 +770,20 @@ declare global { | "gemini" | "continue-proxy" | "deepinfra" - | "voyage"; + | "voyage" + | "watsonx" + | "nebius"; export interface EmbedOptions { apiBase?: string; apiKey?: string; model?: string; - engine?: string; + deployment?: string; apiType?: string; apiVersion?: string; requestOptions?: RequestOptions; maxChunkSize?: number; + projectId?: string; } export interface EmbeddingsProviderDescription extends EmbedOptions { diff --git a/core/config/validation.ts b/core/config/validation.ts index 9da86c6ef..ebcbb623d 100644 --- a/core/config/validation.ts +++ b/core/config/validation.ts @@ -1,4 +1,4 @@ -import { SerializedContinueConfig } from "../"; +import { ModelDescription, SerializedContinueConfig } from "../"; import { Telemetry } from "../util/posthog"; export interface ConfigValidationError { @@ -14,11 +14,11 @@ export interface ConfigValidationError { export function validateConfig(config: SerializedContinueConfig) { const errors: ConfigValidationError[] = []; - // Validate models - if (!Array.isArray(config.models) || config.models.length === 0) { + // Validate chat models + if (!Array.isArray(config.models)) { errors.push({ fatal: true, - message: "The 'models' field should be a non-empty array.", + message: "The 'models' field should be an array.", }); } else { config.models.forEach((model, index) => { @@ -37,6 +37,36 @@ export function validateConfig(config: SerializedContinueConfig) { }); } + // Validate tab autocomplete model(s) + if (config.tabAutocompleteModel) { + function validateTabAutocompleteModel(modelDescription: ModelDescription) { + const modelName = modelDescription.model.toLowerCase(); + const nonAutocompleteModels = [ + // "gpt", + // "claude", + "mistral", + "instruct", + ]; + + if ( + nonAutocompleteModels.some((m) => modelName.includes(m)) && + !modelName.includes("deepseek") && + !modelName.includes("codestral") + ) { + errors.push({ + fatal: false, + message: `${modelDescription.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`, + }); + } + } + + if (Array.isArray(config.tabAutocompleteModel)) { + config.tabAutocompleteModel.forEach(validateTabAutocompleteModel); + } else { + validateTabAutocompleteModel(config.tabAutocompleteModel); + } + } + // Validate slashCommands if (config.slashCommands) { if (!Array.isArray(config.slashCommands)) { diff --git a/core/context/providers/ContinueProxyContextProvider.ts b/core/context/providers/ContinueProxyContextProvider.ts index dc1c9ef22..2dcb91cc8 100644 --- a/core/context/providers/ContinueProxyContextProvider.ts +++ b/core/context/providers/ContinueProxyContextProvider.ts @@ -1,4 +1,4 @@ -import { CONTROL_PLANE_URL } from "../../control-plane/client.js"; +import { controlPlaneEnv } from "../../control-plane/env.js"; import { ContextItem, ContextProviderDescription, @@ -36,7 +36,10 @@ class ContinueProxyContextProvider extends BaseContextProvider { args: LoadSubmenuItemsArgs, ): Promise { const response = await args.fetch( - new URL(`/proxy/context/${this.options.id}/list`, CONTROL_PLANE_URL), + new URL( + `/proxy/context/${this.options.id}/list`, + controlPlaneEnv.CONTROL_PLANE_URL, + ), { method: "GET", headers: { @@ -54,7 +57,10 @@ class ContinueProxyContextProvider extends BaseContextProvider { extras: ContextProviderExtras, ): Promise { const response = await extras.fetch( - new URL(`/proxy/context/${this.options.id}/retrieve`, CONTROL_PLANE_URL), + new URL( + `/proxy/context/${this.options.id}/retrieve`, + controlPlaneEnv.CONTROL_PLANE_URL, + ), { method: "POST", headers: { diff --git a/core/context/providers/CurrentFileContextProvider.ts b/core/context/providers/CurrentFileContextProvider.ts index 575350b49..5e75f85c8 100644 --- a/core/context/providers/CurrentFileContextProvider.ts +++ b/core/context/providers/CurrentFileContextProvider.ts @@ -24,17 +24,15 @@ class CurrentFileContextProvider extends BaseContextProvider { if (!currentFile) { return []; } - const contents = await ide.readFile(currentFile); + const baseName = getBasename(currentFile.path); return [ { - description: currentFile, - content: `This is the currently open file:\n\n\`\`\`${getBasename( - currentFile, - )}\n${contents}\n\`\`\``, - name: getBasename(currentFile), + description: currentFile.path, + content: `This is the currently open file:\n\n\`\`\`${baseName}\n${currentFile.contents}\n\`\`\``, + name: baseName, uri: { type: "file", - value: currentFile, + value: currentFile.path, }, }, ]; diff --git a/core/context/providers/CustomContextProvider.ts b/core/context/providers/CustomContextProvider.ts index ac14dc9f4..f87a4554f 100644 --- a/core/context/providers/CustomContextProvider.ts +++ b/core/context/providers/CustomContextProvider.ts @@ -8,10 +8,7 @@ import type { } from "../../"; class CustomContextProviderClass implements IContextProvider { - custom: CustomContextProvider; - constructor(custom: CustomContextProvider) { - this.custom = custom; - } + constructor(private custom: CustomContextProvider) {} get description(): ContextProviderDescription { return { diff --git a/core/context/providers/DiffContextProvider.ts b/core/context/providers/DiffContextProvider.ts index ae0eb42b8..f2c95083f 100644 --- a/core/context/providers/DiffContextProvider.ts +++ b/core/context/providers/DiffContextProvider.ts @@ -17,7 +17,7 @@ class DiffContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const diff = await extras.ide.getDiff(false); + const diff = await extras.ide.getDiff(this.options.includeUnstaged ?? true); return [ { description: "The current git diff", diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts index d1ac2d6e2..26fb9dc73 100644 --- a/core/context/providers/FileContextProvider.ts +++ b/core/context/providers/FileContextProvider.ts @@ -1,3 +1,4 @@ +import { BaseContextProvider } from "../"; import { ContextItem, ContextProviderDescription, @@ -11,7 +12,6 @@ import { getUniqueFilePath, groupByLastNPathParts, } from "../../util/"; -import { BaseContextProvider } from "../"; const MAX_SUBMENU_ITEMS = 10_000; @@ -21,7 +21,6 @@ class FileContextProvider extends BaseContextProvider { displayTitle: "Files", description: "Type to search", type: "submenu", - dependsOnIndexing: true, }; async getContextItems( diff --git a/core/context/providers/FileTreeContextProvider.ts b/core/context/providers/FileTreeContextProvider.ts index 5b5d99fed..52af97823 100644 --- a/core/context/providers/FileTreeContextProvider.ts +++ b/core/context/providers/FileTreeContextProvider.ts @@ -34,7 +34,6 @@ class FileTreeContextProvider extends BaseContextProvider { description: "Attach a representation of the file tree", type: "normal", renderInlineAs: "", - dependsOnIndexing: true, }; async getContextItems( diff --git a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts index 6c9320f8f..d747f76f1 100644 --- a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts +++ b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts @@ -156,12 +156,17 @@ export class JiraClient { }, ); - if (response.status !== 200) { + if (response.status === 500) { + const text = await response.text(); console.warn( - "Unable to get jira tickets. Response code from API is", - response.status, + "Unable to get Jira tickets. You may need to set 'apiVersion': 2 in your config.json. See full documentation here: https://docs.continue.dev/customize/context-providers#jira-datacenter-support\n\n", + text, ); return Promise.resolve([]); + } else if (response.status !== 200) { + const text = await response.text(); + console.warn("Unable to get Jira tickets: ", text); + return Promise.resolve([]); } const data = (await response.json()) as any; diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 6aefe0301..183ff3cb6 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -7,9 +7,9 @@ import { LoadSubmenuItemsArgs, } from "../../"; import { - groupByLastNPathParts, getBasename, getUniqueFilePath, + groupByLastNPathParts, } from "../../util"; import generateRepoMap from "../../util/generateRepoMap"; @@ -25,7 +25,6 @@ class RepoMapContextProvider extends BaseContextProvider { displayTitle: "Repository Map", description: "Select a folder", type: "submenu", - dependsOnIndexing: true, }; async getContextItems( diff --git a/core/context/rerankers/tei.ts b/core/context/rerankers/tei.ts index 61f38b98b..2d3f9ab12 100644 --- a/core/context/rerankers/tei.ts +++ b/core/context/rerankers/tei.ts @@ -15,6 +15,7 @@ export class HuggingFaceTEIReranker implements Reranker { apiBase?: string; truncate?: boolean; truncation_direction?: string; + apiKey?: string; }, ) {} @@ -24,9 +25,17 @@ export class HuggingFaceTEIReranker implements Reranker { apiBase += "/"; } + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.params.apiKey) { + headers["Authorization"] = `Bearer ${this.params.apiKey}`; + } + const resp = await fetch(new URL("rerank", apiBase), { method: "POST", - headers: { "Content-Type": "application/json" }, + headers, body: JSON.stringify({ query: query, return_text: false, diff --git a/core/context/retrieval/fullTextSearch.ts b/core/context/retrieval/fullTextSearch.ts deleted file mode 100644 index 9c52bd6b6..000000000 --- a/core/context/retrieval/fullTextSearch.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BranchAndDir, Chunk } from "../../index.js"; -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js"; - -export async function retrieveFts( - query: string, - n: number, - tags: BranchAndDir[], - filterDirectory: string | undefined, -): Promise { - const ftsIndex = new FullTextSearchCodebaseIndex(); - - let ftsResults: Chunk[] = []; - try { - if (query.trim() !== "") { - ftsResults = await ftsIndex.retrieve( - tags, - query - .trim() - .split(" ") - .map((element) => `"${element}"`) - .join(" OR "), - n, - filterDirectory, - undefined, - ); - } - return ftsResults; - } catch (e) { - console.warn("Error retrieving from FTS:", e); - return []; - } -} diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 7fdf8ec31..89323d9b2 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -1,34 +1,39 @@ -import { - BranchAndDir, - Chunk, - ContinueConfig, - IDE, - ILLM, -} from "../../../index.js"; -import { chunkDocument } from "../../../indexing/chunk/chunk.js"; -import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js"; -import { retrieveFts } from "../fullTextSearch.js"; -import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js"; +// @ts-ignore +import nlp from "wink-nlp-utils"; + +import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../"; +import { chunkDocument } from "../../../indexing/chunk/chunk"; +import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; +import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; +import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache"; export interface RetrievalPipelineOptions { llm: ILLM; config: ContinueConfig; ide: IDE; - input: string; nRetrieve: number; nFinal: number; tags: BranchAndDir[]; pathSep: string; filterDirectory?: string; + includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model +} + +export interface RetrievalPipelineRunArguments { + query: string; + tags: BranchAndDir[]; + filterDirectory?: string; } export interface IRetrievalPipeline { - run(options: RetrievalPipelineOptions): Promise; + run(args: RetrievalPipelineRunArguments): Promise; } export default class BaseRetrievalPipeline implements IRetrievalPipeline { + private ftsIndex = new FullTextSearchCodebaseIndex(); private lanceDbIndex: LanceDbIndex; + constructor(protected readonly options: RetrievalPipelineOptions) { this.lanceDbIndex = new LanceDbIndex( options.config.embeddingsProvider, @@ -37,6 +42,49 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } + private getCleanedTrigrams( + query: RetrievalPipelineRunArguments["query"], + ): string[] { + let text = nlp.string.removeExtraSpaces(query); + text = nlp.string.stem(text); + + let tokens = nlp.string + .tokenize(text, true) + .filter((token: any) => token.tag === "word") + .map((token: any) => token.value); + + tokens = nlp.tokens.removeWords(tokens); + tokens = nlp.tokens.setOfWords(tokens); + + const cleanedTokens = [...tokens].join(" "); + const trigrams = nlp.string.ngram(cleanedTokens, 3); + + return trigrams; + } + + protected async retrieveFts( + args: RetrievalPipelineRunArguments, + n: number, + ): Promise { + try { + if (args.query.trim() === "") { + return []; + } + + const tokens = this.getCleanedTrigrams(args.query).join(" OR "); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); + } catch (e) { + console.warn("Error retrieving from FTS:", e); + return []; + } + } + protected async retrieveAndChunkRecentlyEditedFiles( n: number, ): Promise { @@ -71,16 +119,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { } } - return chunks; - } - - protected async retrieveFts(input: string, n: number): Promise { - return retrieveFts( - input, - n, - this.options.tags, - this.options.filterDirectory, - ); + return chunks.slice(0, n); } protected async retrieveEmbeddings( @@ -95,7 +134,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } - run(): Promise { + run(args: RetrievalPipelineRunArguments): Promise { throw new Error("Not implemented"); } } diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index f6f83a4f2..052a1fce6 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -1,11 +1,14 @@ -import { Chunk } from "../../../index.js"; -import { requestFilesFromRepoMap } from "../repoMapRequest.js"; -import { deduplicateChunks } from "../util.js"; -import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; +import { Chunk } from "../../../"; +import { requestFilesFromRepoMap } from "../repoMapRequest"; +import { deduplicateChunks } from "../util"; + +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { - async run(): Promise { - const { input, nFinal, filterDirectory } = this.options; + async run(args: RetrievalPipelineRunArguments): Promise { + const { input, nFinal, filterDirectory, includeEmbeddings } = this.options; // We give 1/4 weight to recently edited files, 1/4 to full text search, // and the remaining 1/2 to embeddings @@ -15,12 +18,11 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(input, ftsNFinal); + const ftsChunks = await this.retrieveFts(args, ftsNFinal); - const embeddingsChunks = await this.retrieveEmbeddings( - input, - embeddingsNFinal, - ); + const embeddingsChunks = includeEmbeddings + ? await this.retrieveEmbeddings(input, embeddingsNFinal) + : []; const recentlyEditedFilesChunks = await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index faac97957..6f28a4a89 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -1,17 +1,25 @@ -import { Chunk } from "../../../index.js"; -import { RETRIEVAL_PARAMS } from "../../../util/parameters.js"; -import { requestFilesFromRepoMap } from "../repoMapRequest.js"; -import { deduplicateChunks } from "../util.js"; -import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; +import { Chunk } from "../../.."; +import { RETRIEVAL_PARAMS } from "../../../util/parameters"; +import { requestFilesFromRepoMap } from "../repoMapRequest"; +import { deduplicateChunks } from "../util"; + +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { - private async _retrieveInitial(): Promise { - const { input, nRetrieve, filterDirectory } = this.options; + private async _retrieveInitial( + args: RetrievalPipelineRunArguments, + ): Promise { + const { input, nRetrieve, filterDirectory, includeEmbeddings } = + this.options; let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(input, nRetrieve); - const embeddingsChunks = await this.retrieveEmbeddings(input, nRetrieve); + const ftsChunks = await this.retrieveFts(args, nRetrieve); + const embeddingsChunks = includeEmbeddings + ? await this.retrieveEmbeddings(input, nRetrieve) + : []; const recentlyEditedFilesChunks = await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); @@ -101,9 +109,9 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { return results; } - async run(): Promise { - const intialResults = await this._retrieveInitial(); - const rankedResults = await this._rerank(this.options.input, intialResults); + async run(args: RetrievalPipelineRunArguments): Promise { + let results = await this._retrieveInitial(args); + results = await this._rerank(args.query, results); // // // Expand top reranked results // const expanded = await this._expandRankedResults(results); @@ -117,7 +125,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { // TODO: stitch together results - return rankedResults; + return results; } } diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 618be4808..e4b3e072e 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -6,6 +6,7 @@ import generateRepoMap from "../../util/generateRepoMap"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", "llama3.1", + "llama3.2", "gemini-1.5", "gpt-4", ]; diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 2652bfa0f..8aae10a41 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,8 +1,10 @@ import path from "path"; + import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider"; import { resolveRelativePathInWorkspace } from "../../util/ideUtils"; import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; + import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline"; import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline"; @@ -21,15 +23,17 @@ export async function retrieveContextItemsFromEmbeddings( // transformers.js not supported in JetBrains IDEs right now const isJetBrainsAndTransformersJs = - extras.embeddingsProvider.id === TransformersJsEmbeddingsProvider.model && + extras.embeddingsProvider.providerName === + TransformersJsEmbeddingsProvider.providerName && (await extras.ide.getIdeInfo()).ideType === "jetbrains"; if (isJetBrainsAndTransformersJs) { - throw new Error( - "The 'transformers.js' context provider is not currently supported in JetBrains. " + - "For now, you can use Ollama to set up local embeddings, or use our 'free-trial' " + - "embeddings provider. See here to learn more: " + - "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", + void extras.ide.showToast( + "warning", + "Codebase retrieval is limited when `embeddingsProvider` is empty or set to `transformers.js` in JetBrains. " + + "You can use Ollama to set up local embeddings, use our 'free-trial', " + + "or configure your own. See here to learn more: " + + "https://docs.continue.dev/customize/model-types/embeddings", ); } @@ -85,10 +89,15 @@ export async function retrieveContextItemsFromEmbeddings( input: extras.fullInput, llm: extras.llm, config: extras.config, + includeEmbeddings: !isJetBrainsAndTransformersJs, }; const pipeline = new pipelineType(pipelineOptions); - const results = await pipeline.run(); + const results = await pipeline.run({ + tags, + filterDirectory, + query: extras.fullInput, + }); if (results.length === 0) { throw new Error( diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 16df8f90c..22d5c7cdb 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -1,6 +1,7 @@ import { ConfigJson } from "@continuedev/config-types"; import fetch, { RequestInit, Response } from "node-fetch"; import { ModelDescription } from "../index.js"; +import { controlPlaneEnv } from "./env.js"; export interface ControlPlaneSessionInfo { accessToken: string; @@ -21,19 +22,8 @@ export interface ControlPlaneModelDescription extends ModelDescription {} export const TRIAL_PROXY_URL = "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app"; -export const DEFAULT_CONTROL_PLANE_PROXY_URL = - process.env.CONTROL_PLANE_ENV === "local" - ? "http://localhost:3001/" - : "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/"; -// : "https://control-plane-proxy.continue.dev/"; - -export const CONTROL_PLANE_URL = - process.env.CONTROL_PLANE_ENV === "local" - ? "http://localhost:3001/" - : "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/"; - export class ControlPlaneClient { - private static URL = CONTROL_PLANE_URL; + private static URL = controlPlaneEnv.CONTROL_PLANE_URL; private static ACCESS_TOKEN_VALID_FOR_MS = 1000 * 60 * 5; // 5 minutes private lastAccessTokenRefresh = 0; diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts new file mode 100644 index 000000000..4556ce90f --- /dev/null +++ b/core/control-plane/env.ts @@ -0,0 +1,50 @@ +interface ControlPlaneEnv { + DEFAULT_CONTROL_PLANE_PROXY_URL: string; + CONTROL_PLANE_URL: string; + AUTH_TYPE: string; + WORKOS_CLIENT_ID: string; + APP_URL: string; +} + +export const EXTENSION_NAME = "continue"; + +const WORKOS_CLIENT_ID_PRODUCTION = "client_01J0FW6XN8N2XJAECF7NE0Y65J"; +const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; + +const WORKOS_ENV_ID_PRODUCTION = "continue"; +const WORKOS_ENV_ID_STAGING = "continue-staging"; + +const PRODUCTION_ENV: ControlPlaneEnv = { + DEFAULT_CONTROL_PLANE_PROXY_URL: + "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", + CONTROL_PLANE_URL: + "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", + AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, + WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, + APP_URL: "https://app.continue.dev", +}; + +const STAGING_ENV: ControlPlaneEnv = { + DEFAULT_CONTROL_PLANE_PROXY_URL: + "https://control-plane-api-service-537175798139.us-central1.run.app/", + CONTROL_PLANE_URL: + "https://control-plane-api-service-537175798139.us-central1.run.app/", + AUTH_TYPE: WORKOS_CLIENT_ID_STAGING, + WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, + APP_URL: "https://app-preview.continue.dev", +}; + +const LOCAL_ENV: ControlPlaneEnv = { + DEFAULT_CONTROL_PLANE_PROXY_URL: "http://localhost:3001/", + CONTROL_PLANE_URL: "http://localhost:3001/", + AUTH_TYPE: WORKOS_ENV_ID_STAGING, + WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, + APP_URL: "http://localhost:3000", +}; + +export const controlPlaneEnv = + process.env.CONTROL_PLANE_ENV === "local" + ? LOCAL_ENV + : process.env.CONTROL_PLANE_ENV === "staging" + ? STAGING_ENV + : PRODUCTION_ENV; diff --git a/core/control-plane/schema.ts b/core/control-plane/schema.ts index 756798937..3a984ae33 100644 --- a/core/control-plane/schema.ts +++ b/core/control-plane/schema.ts @@ -16,6 +16,7 @@ const modelDescriptionSchema = z.object({ "sagemaker", "cloudflare", "azure", + "nebius", ]), model: z.string(), apiKey: z.string().optional(), @@ -81,11 +82,12 @@ const embeddingsProviderSchema = z.object({ "cohere", "free-trial", "gemini", + "nebius", ]), apiBase: z.string().optional(), apiKey: z.string().optional(), model: z.string().optional(), - engine: z.string().optional(), + deployment: z.string().optional(), apiType: z.string().optional(), apiVersion: z.string().optional(), requestOptions: z diff --git a/core/core.ts b/core/core.ts index 415540a74..fb794d29c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,6 +1,8 @@ +import ignore from "ignore"; +import path from "path"; import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; -import { CompletionProvider } from "./autocomplete/completionProvider"; +import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { setupBestConfig, @@ -17,18 +19,19 @@ import { ControlPlaneClient } from "./control-plane/client"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { GlobalContext } from "./util/GlobalContext"; +import { ChatDescriber } from "./util/chatDescriber"; import { logDevData } from "./util/devdata"; import { DevDataSqliteDb } from "./util/devdataSqlite"; import { fetchwithRequestOptions } from "./util/fetchWithOptions"; import historyManager from "./util/history"; import type { IMessenger, Message } from "./util/messenger"; -import { editConfigJson } from "./util/paths"; +import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import { ChatDescriber } from "./util/chatDescriber"; export class Core { // implements IMessenger @@ -79,6 +82,9 @@ export class Core { private readonly ide: IDE, private readonly onWrite: (text: string) => Promise = async () => {}, ) { + // Ensure .continue directory is created + setupInitialDotContinueDirectory(); + this.indexingState = { status: "loading", desc: "loading", progress: 0 }; const ideSettingsPromise = messenger.request("getIdeSettings", undefined); @@ -395,6 +401,7 @@ export class Core { }); break; } + // @ts-ignore yield { content: next.value.content }; next = await gen.next(); } @@ -483,7 +490,7 @@ export class Core { on("tts/kill", async () => { void TTS.kill(); }); - + on("chatDescriber/describe", async (msg) => { const currentModel = await this.getSelectedModel(); return await ChatDescriber.describe(currentModel, {}, msg.data); @@ -701,8 +708,13 @@ export class Core { return { url }; }); - on("didChangeActiveTextEditor", ({ data: { filepath } }) => { - recentlyEditedFilesCache.set(filepath, filepath); + on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { + const ignoreInstance = ignore().add(defaultIgnoreFile); + let rootDirectory = await this.ide.getWorkspaceDirs(); + const relativeFilePath = path.relative(rootDirectory[0], filepath); + if (!ignoreInstance.ignores(relativeFilePath)) { + recentlyEditedFilesCache.set(filepath, filepath); + } }); } diff --git a/core/diff/util.ts b/core/diff/util.ts index 6d218bcbf..9dda0ff02 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -110,6 +110,11 @@ export async function* streamLines( yield line; allLines.push(line); } + + // if (buffer === "" && chunk.endsWith("\n")) { + // yield ""; + // allLines.push(""); + // } } if (buffer.length > 0) { yield buffer; diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index e9cbdf921..bb938b050 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -2,7 +2,7 @@ import { distance } from "fastest-levenshtein"; import path from "path"; import Parser from "web-tree-sitter"; import { DiffLine } from "../.."; -import { LANGUAGES } from "../../autocomplete/languages"; +import { LANGUAGES } from "../../autocomplete/constants/AutocompleteLanguageInfo"; import { myersDiff } from "../../diff/myers"; import { getParserForFile } from "../../util/treeSitter"; import { findInAst } from "./findInAst"; diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index b4b6164cc..e6c3183f0 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -2,7 +2,7 @@ import { ILLM } from "../.."; import { filterLeadingNewline, stopAtLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { dedent } from "../../util"; diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 6dd9cef6d..f101c6981 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -2,7 +2,7 @@ import { filterLeadingAndTrailingNewLineInsertion, filterLeadingNewline, stopAtLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; import { DiffLine, ILLM } from "../../index.js"; diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index cad33b3a2..ca47f010d 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -5,15 +5,10 @@ import { filterLeadingAndTrailingNewLineInsertion, skipLines, stopAtLines, -} from "../autocomplete/streamTransforms/lineStream.js"; +} from "../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; -import { - ChatMessage, - DiffLine, - ILLM, - LLMFullCompletionOptions, -} from "../index.js"; +import { ChatMessage, DiffLine, ILLM, Prediction } from "../index.js"; import { gptEditPrompt } from "../llm/templates/edit.js"; import { Telemetry } from "../util/posthog.js"; @@ -60,7 +55,7 @@ export async function* streamDiffLines( language: string | undefined, onlyOneInsertion?: boolean, ): AsyncGenerator { - Telemetry.capture( + void Telemetry.capture( "inlineEdit", { model: llm.model, @@ -94,11 +89,17 @@ export async function* streamDiffLines( ); const inept = modelIsInept(llm.model); - const options: LLMFullCompletionOptions = {}; + const prediction: Prediction = { + type: "content", + content: highlighted, + }; + const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, { raw: true }) - : llm.streamChat(prompt); + ? llm.streamComplete(prompt, { raw: true, prediction }) + : llm.streamChat(prompt, { + prediction, + }); let lines = streamLines(completion); diff --git a/core/index.d.ts b/core/index.d.ts index e7c22db2f..ca46b3215 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -72,7 +72,7 @@ export interface ILLM extends LLMOptions { apiBase?: string; cacheBehavior?: CacheBehavior; - engine?: string; + deployment?: string; apiVersion?: string; apiType?: string; region?: string; @@ -351,7 +351,7 @@ export interface LLMOptions { accountId?: string; // Azure options - engine?: string; + deployment?: string; apiVersion?: string; apiType?: string; @@ -363,16 +363,13 @@ export interface LLMOptions { region?: string; // GCP Options - projectId?: string; capabilities?: ModelCapability; - // IBM watsonx options - watsonxUrl?: string; - watsonxCreds?: string; - watsonxProjectId?: string; - watsonxStopToken?: string; - watsonxApiVersion?: string; - watsonxFullUrl?: string; + // GCP and Watsonx Options + projectId?: string; + + // IBM watsonx Options + deploymentId?: string; } type RequireAtLeastOne = Pick< T, @@ -497,7 +494,11 @@ export interface IDE { stepIndex: number, ): Promise; getOpenFiles(): Promise; - getCurrentFile(): Promise; + getCurrentFile(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string, cwd?: string): Promise<[string, string]>; @@ -606,13 +607,13 @@ type TemplateType = | "codellama-70b" | "llava" | "gemma" + | "granite" | "llama3"; type ModelProvider = | "openai" | "free-trial" | "anthropic" - | "anthropic-vertexai" | "cohere" | "together" | "ollama" @@ -625,9 +626,7 @@ type ModelProvider = | "lmstudio" | "llamafile" | "gemini" - | "gemini-vertexai" | "mistral" - | "mistral-vertexai" | "bedrock" | "bedrockimport" | "sagemaker" @@ -648,8 +647,11 @@ type ModelProvider = | "nvidia" | "vllm" | "mock" - | "cerebras"; - + | "cerebras" + | "askSage" + | "vertexai" + | "nebius" + | "xAI"; export type ModelName = | "AUTODETECT" @@ -664,6 +666,8 @@ export type ModelName = | "gpt-4-turbo" | "gpt-4-turbo-preview" | "gpt-4-vision-preview" + | "o1-preview" + | "o1-mini" // Mistral | "codestral-latest" | "open-mistral-7b" @@ -691,6 +695,14 @@ export type ModelName = // Llama 3.1 | "llama3.1-8b" | "llama3.1-70b" + | "llama3.1-405b" + // Llama 3.2 + | "llama3.2-1b" + | "llama3.2-3b" + | "llama3.2-11b" + | "llama3.2-90b" + // xAI + | "grok-beta" // Other Open-source | "phi2" | "phind-codellama-34b" @@ -705,6 +717,7 @@ export type ModelName = | "gemma-7b-it" | "gemma2-9b-it" // Anthropic + | "claude-3-5-sonnet-latest" | "claude-3-5-sonnet-20240620" | "claude-3-opus-20240229" | "claude-3-sonnet-20240229" @@ -771,6 +784,14 @@ export interface CustomCommand { description: string; } +interface Prediction { + type: "content" + content: string | { + type: "text" + text: string + }[] +} + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -785,6 +806,7 @@ interface BaseCompletionOptions { keepAlive?: number; raw?: boolean; stream?: boolean; + prediction?: Prediction; } export interface ModelCapability { @@ -816,19 +838,23 @@ export type EmbeddingsProviderName = | "ollama" | "openai" | "cohere" + | "lmstudio" | "free-trial" | "gemini" | "continue-proxy" | "deepinfra" | "nvidia" | "voyage" - | "mistral"; + | "mistral" + | "nebius" + | "vertexai" + | "watsonx"; export interface EmbedOptions { apiBase?: string; apiKey?: string; model?: string; - engine?: string; + deployment?: string; apiType?: string; apiVersion?: string; requestOptions?: RequestOptions; @@ -839,6 +865,9 @@ export interface EmbedOptions { // AWS and GCP Options region?: string; + + // GCP and Watsonx Options + projectId?: string; } export interface EmbeddingsProviderDescription extends EmbedOptions { @@ -878,6 +907,7 @@ export interface TabAutocompleteOptions { debounceDelay: number; maxSuffixPercentage: number; prefixPercentage: number; + transform?: boolean; template?: string; multilineCompletions: "always" | "never" | "auto"; slidingWindowPrefixPercentage: number; @@ -892,6 +922,7 @@ export interface TabAutocompleteOptions { disableInFiles?: string[]; useImports?: boolean; useRootPathContext?: boolean; + showWhateverWeHaveAtXMs?: number; } export interface ContinueUIConfig { diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index a8b41cafe..70872aff9 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -14,7 +14,7 @@ import { getParserForFile, getQueryForFile, } from "../util/treeSitter"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; +import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, @@ -28,7 +28,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; artifactId = "codeSnippets"; - constructor(private readonly ide: IDE) {} + constructor(private readonly ide: IDE) { } private static async _createTables(db: DatabaseConnection) { await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets ( @@ -383,7 +383,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const db = await SqliteDb.get(); await CodeSnippetsCodebaseIndex._createTables(db); - const likePatterns = workspaceDirs.map((dir) => `${dir}%`); + const likePatterns = workspaceDirs.map((dir) => truncateSqliteLikePattern(`${dir}%`)); const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); const query = ` diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 27face898..82e4e822f 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -1,6 +1,7 @@ import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; import { getBasename } from "../util/index"; import { RETRIEVAL_PARAMS } from "../util/parameters"; + import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { @@ -10,10 +11,20 @@ import { type CodebaseIndex, } from "./types"; +export interface RetrieveConfig { + tags: BranchAndDir[]; + text: string; + n: number; + directory?: string; + filterPaths?: string[]; + bm25Threshold?: number; +} + export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; static artifactId = "sqliteFts"; artifactId: string = FullTextSearchCodebaseIndex.artifactId; + pathWeightMultiplier = 10.0; private async _createTables(db: DatabaseConnection) { await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( @@ -71,17 +82,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { desc: `Indexing ${getBasename(item.path)}`, status: "indexing", }; - markComplete([item], IndexResultType.Compute); + await markComplete([item], IndexResultType.Compute); } // Add tag for (const item of results.addTag) { - markComplete([item], IndexResultType.AddTag); + await markComplete([item], IndexResultType.AddTag); } // Remove tag for (const item of results.removeTag) { - markComplete([item], IndexResultType.RemoveTag); + await markComplete([item], IndexResultType.RemoveTag); } // Delete @@ -93,63 +104,81 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { await db.run("DELETE FROM fts WHERE path = ?", [item.path]); - markComplete([item], IndexResultType.Delete); + await markComplete([item], IndexResultType.Delete); } } - async retrieve( - tags: BranchAndDir[], - text: string, - n: number, - directory: string | undefined, - filterPaths: string[] | undefined, - bm25Threshold: number = RETRIEVAL_PARAMS.bm25Threshold, - ): Promise { + async retrieve(config: RetrieveConfig): Promise { const db = await SqliteDb.get(); - // Notice that the "chunks" artifactId is used because of linking between tables - const tagStrings = tags.map((tag) => { - return tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }); - }); + const query = this.buildRetrieveQuery(config); + const parameters = this.getRetrieveQueryParameters(config); - const query = `SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank - FROM fts - JOIN fts_metadata ON fts.rowid = fts_metadata.id - JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId - WHERE fts MATCH '${text.replace( - /\?/g, - "", - )}' AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")}) - ${ - filterPaths - ? `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})` - : "" - } - ORDER BY rank - LIMIT ?`; + let results = await db.all(query, parameters); - let results = await db.all(query, [ - ...tagStrings, - ...(filterPaths || []), - Math.ceil(n), - ]); - - results = results.filter((result) => result.rank <= bm25Threshold); + results = results.filter( + (result) => + result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold), + ); const chunks = await db.all( `SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`, results.map((result) => result.chunkId), ); - return chunks.map((chunk) => { - return { - filepath: chunk.path, - index: chunk.index, - startLine: chunk.startLine, - endLine: chunk.endLine, - content: chunk.content, - digest: chunk.cacheKey, - }; - }); + return chunks.map((chunk) => ({ + filepath: chunk.path, + index: chunk.index, + startLine: chunk.startLine, + endLine: chunk.endLine, + content: chunk.content, + digest: chunk.cacheKey, + })); + } + + private buildTagFilter(tags: BranchAndDir[]): string { + const tagStrings = this.convertTags(tags); + + return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`; + } + + private buildPathFilter(filterPaths: string[] | undefined): string { + if (!filterPaths || filterPaths.length === 0) { + return ""; + } + return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`; + } + + private buildRetrieveQuery(config: RetrieveConfig): string { + return ` + SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank + FROM fts + JOIN fts_metadata ON fts.rowid = fts_metadata.id + JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId + WHERE fts MATCH ? + ${this.buildTagFilter(config.tags)} + ${this.buildPathFilter(config.filterPaths)} + ORDER BY bm25(fts, ${this.pathWeightMultiplier}) + LIMIT ? + `; + } + + private getRetrieveQueryParameters(config: RetrieveConfig) { + const { text, tags, filterPaths, n } = config; + const tagStrings = this.convertTags(tags); + + return [ + text.replace(/\?/g, ""), + ...tagStrings, + ...(filterPaths || []), + Math.ceil(n), + ]; + } + + private convertTags(tags: BranchAndDir[]): string[] { + // Notice that the "chunks" artifactId is used because of linking between tables + return tags.map((tag) => + tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }), + ); } } diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index cdf91f359..e2d316d67 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -23,9 +23,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex { private readonly pathSep: string, private readonly continueServerClient: IContinueServerClient, private readonly maxChunkSize: number, - ) { - this.readFile = readFile; - } + ) {} async *update( tag: IndexTag, diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 19300cd0b..d0851f95b 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -1,18 +1,11 @@ -import { Octokit } from "@octokit/rest"; -import * as cheerio from "cheerio"; -import * as fs from "fs"; -import fetch from "node-fetch"; import { URL } from "node:url"; -import { Handler, HTTPResponse, Page } from "puppeteer"; -import { - editConfigJson, - getChromiumPath, - getContinueUtilsPath, -} from "../../util/paths"; // @ts-ignore // @prettier-ignore -import PCR from "puppeteer-chromium-resolver"; import { ContinueConfig, IDE } from "../.."; +import CheerioCrawler from "./crawlers/CheerioCrawler"; +import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler"; +import { DefaultCrawler } from "./crawlers/DefaultCrawler"; +import GitHubCrawler from "./crawlers/GitHubCrawler"; export type PageData = { url: string; @@ -42,10 +35,23 @@ class DocsCrawler { async *crawl( startUrl: URL, maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL, - ): AsyncGenerator { + ): AsyncGenerator { if (startUrl.host === this.GITHUB_HOST) { yield* new GitHubCrawler(startUrl).crawl(); - } else if (this.shouldUseChromium()) { + return; + } + + try { + const pageData = await new DefaultCrawler(startUrl).crawl(); + if (pageData.length > 0) { + yield* pageData; + return; + } + } catch (e) { + console.error("Default crawler failed, trying backup: ", e); + } + + if (this.shouldUseChromium()) { yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); } else { let didCrawlSinglePage = false; @@ -83,471 +89,6 @@ class DocsCrawler { } } -class GitHubCrawler { - private readonly markdownRegex = new RegExp(/\.(md|mdx)$/); - private octokit = new Octokit({ auth: undefined }); - - constructor(private readonly startUrl: URL) {} - - async *crawl(): AsyncGenerator { - console.debug( - `[${ - (this.constructor as any).name - }] Crawling GitHub repo: ${this.startUrl.toString()}`, - ); - const urlStr = this.startUrl.toString(); - const [_, owner, repo] = this.startUrl.pathname.split("/"); - const branch = await this.getGithubRepoDefaultBranch(owner, repo); - const paths = await this.getGitHubRepoPaths(owner, repo, branch); - - for await (const path of paths) { - const content = await this.getGithubRepoFileContent(path, owner, repo); - yield { path, url: urlStr, content: content ?? "" }; - } - } - - private async getGithubRepoDefaultBranch( - owner: string, - repo: string, - ): Promise { - const repoInfo = await this.octokit.repos.get({ owner, repo }); - return repoInfo.data.default_branch; - } - - private async getGitHubRepoPaths( - owner: string, - repo: string, - branch: string, - ) { - const tree = await this.octokit.request( - "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", - { - owner, - repo, - tree_sha: branch, - headers: { "X-GitHub-Api-Version": "2022-11-28" }, - recursive: "true", - }, - ); - - return tree.data.tree - .filter( - (file: any) => - file.type === "blob" && this.markdownRegex.test(file.path ?? ""), - ) - .map((file: any) => file.path); - } - - private async getGithubRepoFileContent( - path: string, - owner: string, - repo: string, - ) { - try { - const response = await this.octokit.repos.getContent({ - owner, - repo, - path, - headers: { Accept: "application/vnd.github.raw+json" }, - }); - return response.data as unknown as string; - } catch (error) { - console.debug("Error fetching file contents:", error); - return null; - } - } -} - -class CheerioCrawler { - private readonly IGNORE_PATHS_ENDING_IN = [ - "favicon.ico", - "robots.txt", - ".rst.txt", - "genindex", - "py-modindex", - "search.html", - "search", - "genindex.html", - "changelog", - "changelog.html", - ]; - - constructor( - private readonly startUrl: URL, - private readonly maxRequestsPerCrawl: number, - ) {} - - async *crawl(): AsyncGenerator { - yield* this.crawlPage(this.startUrl); - } - - private async *crawlPage( - url: URL, - maxDepth: number = 3, - ): AsyncGenerator { - console.log( - `[${ - (this.constructor as any).name - }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`, - ); - - const { baseUrl, basePath } = this.splitUrl(url); - - let paths: { path: string; depth: number }[] = [ - { path: basePath, depth: 0 }, - ]; - - let index = 0; - - while (index < paths.length) { - const batch = paths.slice(index, index + 50); - - try { - const promises = batch.map(({ path, depth }) => - this.getLinksFromUrl(baseUrl, path).then((links) => ({ - links, - path, - depth, - })), - ); - - const results = await Promise.all(promises); - for (const { - links: { html, links: linksArray }, - path, - depth, - } of results) { - if (html !== "" && depth <= maxDepth) { - yield { url: url.toString(), path, content: html }; - } - - if (depth < maxDepth) { - for (let link of linksArray) { - if (!paths.some((p) => p.path === link)) { - paths.push({ path: link, depth: depth + 1 }); - } - } - } - } - } catch (e) { - console.debug("Error while crawling page: ", e); - } - - index += batch.length; - } - - console.log("Crawl completed"); - } - - private async getLinksFromUrl(url: string, path: string) { - const baseUrl = new URL(url); - const location = new URL(path, url); - let response; - - try { - response = await fetch(location.toString()); - } catch (error: unknown) { - if ( - error instanceof Error && - error.message.includes("maximum redirect") - ) { - console.error( - `[${ - (this.constructor as any).name - }] Maximum redirect reached for: ${location.toString()}`, - ); - return { html: "", links: [] }; - } - console.error(error); - return { html: "", links: [] }; - } - if (!response.ok) { - return { html: "", links: [] }; - } - const html = await response.text(); - let links: string[] = []; - - if (url.includes("github.com")) { - return { html, links }; - } - - const $ = cheerio.load(html); - - $("a").each((_: any, element: any) => { - const href = $(element).attr("href"); - if (!href) { - return; - } - - const parsedUrl = new URL(href, location); - if (parsedUrl.hostname === baseUrl.hostname) { - links.push(parsedUrl.pathname); - } - }); - - links = [...new Set(links)].filter((link) => { - return ( - !link.includes("#") && - !this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending)) - ); - }); - return { html, links }; - } - - private splitUrl(url: URL) { - const baseUrl = new URL('/', url).href; - const basePath = url.pathname; - return { baseUrl, basePath }; - } -} - -class ChromiumCrawler { - private readonly LINK_GROUP_SIZE = 2; - private curCrawlCount = 0; - - constructor( - private readonly startUrl: URL, - private readonly maxRequestsPerCrawl: number, - ) {} - - static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { - editConfigJson((config) => ({ - ...config, - experimental: { - ...config.experimental, - useChromiumForDocsCrawling, - }, - })); - } - - async *crawl(): AsyncGenerator { - console.debug( - `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`, - ); - - const stats = await PCR(ChromiumInstaller.PCR_CONFIG); - const browser = await stats.puppeteer.launch({ - args: [ - "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", - ], - executablePath: stats.executablePath, - }); - const page = await browser.newPage(); - - try { - yield* this.crawlSitePages(page, this.startUrl); - } catch (e) { - console.debug("Error getting links: ", e); - console.debug( - "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", - ); - - ChromiumCrawler.setUseChromiumForDocsCrawling(false); - } finally { - await browser.close(); - } - } - - /** - * We need to handle redirects manually, otherwise there are race conditions. - * - * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573 - */ - private async gotoPageAndHandleRedirects(page: Page, url: string) { - const MAX_PAGE_WAIT_MS = 5000; - - await page.goto(url, { - timeout: 0, - waitUntil: "networkidle2", - }); - - let responseEventOccurred = false; - const responseHandler: Handler = (event) => - (responseEventOccurred = true); - - const responseWatcher = new Promise(function (resolve, reject) { - setTimeout(() => { - if (!responseEventOccurred) { - resolve(); - } else { - setTimeout(() => resolve(), MAX_PAGE_WAIT_MS); - } - }, 500); - }); - - page.on("response", responseHandler); - - await Promise.race([responseWatcher, page.waitForNavigation()]); - } - - private async *crawlSitePages( - page: Page, - curUrl: URL, - visitedLinks: Set = new Set(), - ): AsyncGenerator { - const urlStr = curUrl.toString(); - - if (visitedLinks.has(urlStr)) { - return; - } - - await this.gotoPageAndHandleRedirects(page, urlStr); - - const htmlContent = await page.content(); - const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); - this.curCrawlCount++; - - visitedLinks.add(urlStr); - - yield { - path: curUrl.pathname, - url: urlStr, - content: htmlContent, - }; - - for (const linkGroup of linkGroups) { - let enqueuedLinkCount = this.curCrawlCount; - - for (const link of linkGroup) { - enqueuedLinkCount++; - console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); - if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { - yield* this.crawlSitePages(page, new URL(link), visitedLinks); - } - } - } - } - - private stripHashFromUrl(urlStr: string) { - try { - let url = new URL(urlStr); - url.hash = ""; - return url; - } catch (err) { - return null; - } - } - - private isValidHostAndPath(newUrl: URL, curUrl: URL) { - return ( - newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host - ); - } - - private async getLinksFromPage(page: Page, curUrl: URL) { - const links = await page.$$eval("a", (links) => links.map((a) => a.href)); - - const cleanedLinks = links - .map(this.stripHashFromUrl) - .filter( - (newUrl) => - newUrl !== null && - this.isValidHostAndPath(newUrl, curUrl) && - newUrl !== curUrl, - ) - .map((newUrl) => (newUrl as URL).href); - - const dedupedLinks = Array.from(new Set(cleanedLinks)); - - return dedupedLinks; - } - - private async getLinkGroupsFromPage(page: Page, curUrl: URL) { - const links = await this.getLinksFromPage(page, curUrl); - - const groups = links.reduce((acc, link, i) => { - const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); - - if (!acc[groupIndex]) { - acc.push([]); - } - - acc[groupIndex].push(link); - - return acc; - }, [] as string[][]); - - return groups; - } -} - -class ChromiumInstaller { - static PCR_CONFIG = { downloadPath: getContinueUtilsPath() }; - - constructor( - private readonly ide: IDE, - private readonly config: ContinueConfig, - ) { - if (this.shouldInstallOnStartup()) { - console.log("Installing Chromium"); - void this.install(); - } - } - - isInstalled() { - return fs.existsSync(getChromiumPath()); - } - - shouldInstallOnStartup() { - return ( - !this.isInstalled() && - this.config.experimental?.useChromiumForDocsCrawling - ); - } - - shouldProposeUseChromiumOnCrawlFailure() { - const { experimental } = this.config; - - return ( - experimental?.useChromiumForDocsCrawling === undefined || - experimental.useChromiumForDocsCrawling - ); - } - - async proposeAndAttemptInstall(site: string) { - const userAcceptedInstall = await this.proposeInstall(site); - - if (userAcceptedInstall) { - const didInstall = await this.install(); - return didInstall; - } - } - - async install() { - try { - await PCR(ChromiumInstaller.PCR_CONFIG); - - ChromiumCrawler.setUseChromiumForDocsCrawling(true); - - return true; - } catch (error) { - console.debug("Error installing Chromium : ", error); - console.debug( - "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", - ); - - ChromiumCrawler.setUseChromiumForDocsCrawling(false); - - await this.ide.showToast("error", "Failed to install Chromium"); - - return false; - } - } - - private async proposeInstall(site: string) { - const msg = - `Unable to crawl documentation site: ${site}\n` + - "We recommend installing Chromium. " + - "Download progress can be viewed in the developer console."; - - const actionMsg = "Install Chromium"; - - const res = await this.ide.showToast("warning", msg, actionMsg); - - return res === actionMsg; - } -} - export default DocsCrawler; export { CheerioCrawler, diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index d6c3b684c..0224dc3a0 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -404,12 +404,15 @@ export default class DocsService { async getFavicon(startUrl: string) { const db = await this.getOrCreateSqliteDb(); - const { favicon } = await db.get( + const result = await db.get( `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, startUrl, ); - return favicon; + if (!result) { + return; + } + return result.favicon; } private async init(configHandler: ConfigHandler) { diff --git a/core/indexing/docs/crawlers/CheerioCrawler.ts b/core/indexing/docs/crawlers/CheerioCrawler.ts new file mode 100644 index 000000000..df3eaf1bd --- /dev/null +++ b/core/indexing/docs/crawlers/CheerioCrawler.ts @@ -0,0 +1,146 @@ +import * as cheerio from "cheerio"; +import { URL } from "node:url"; +import { PageData } from "../DocsCrawler"; + +export default class CheerioCrawler { + private readonly IGNORE_PATHS_ENDING_IN = [ + "favicon.ico", + "robots.txt", + ".rst.txt", + "genindex", + "py-modindex", + "search.html", + "search", + "genindex.html", + "changelog", + "changelog.html", + ]; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number, + ) {} + + async *crawl(): AsyncGenerator { + yield* this.crawlPage(this.startUrl); + } + + private async *crawlPage( + url: URL, + maxDepth: number = 3, + ): AsyncGenerator { + console.log( + `[${ + (this.constructor as any).name + }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`, + ); + + const { baseUrl, basePath } = this.splitUrl(url); + + let paths: { path: string; depth: number }[] = [ + { path: basePath, depth: 0 }, + ]; + + let index = 0; + + while (index < paths.length) { + const batch = paths.slice(index, index + 50); + + try { + const promises = batch.map(({ path, depth }) => + this.getLinksFromUrl(baseUrl, path).then((links) => ({ + links, + path, + depth, + })), + ); + + const results = await Promise.all(promises); + for (const { + links: { html, links: linksArray }, + path, + depth, + } of results) { + if (html !== "" && depth <= maxDepth) { + yield { url: url.toString(), path, content: html }; + } + + if (depth < maxDepth) { + for (let link of linksArray) { + if (!paths.some((p) => p.path === link)) { + paths.push({ path: link, depth: depth + 1 }); + } + } + } + } + } catch (e) { + console.debug("Error while crawling page: ", e); + } + + index += batch.length; + } + + console.log("Crawl completed"); + } + + private async getLinksFromUrl(url: string, path: string) { + const baseUrl = new URL(url); + const location = new URL(path, url); + let response; + + try { + response = await fetch(location.toString()); + } catch (error: unknown) { + if ( + error instanceof Error && + error.message.includes("maximum redirect") + ) { + console.error( + `[${ + (this.constructor as any).name + }] Maximum redirect reached for: ${location.toString()}`, + ); + return { html: "", links: [] }; + } + console.error(error); + return { html: "", links: [] }; + } + if (!response.ok) { + return { html: "", links: [] }; + } + const html = await response.text(); + let links: string[] = []; + + if (url.includes("github.com")) { + return { html, links }; + } + + const $ = cheerio.load(html); + + $("a").each((_: any, element: any) => { + const href = $(element).attr("href"); + if (!href) { + return; + } + + const parsedUrl = new URL(href, location); + if (parsedUrl.hostname === baseUrl.hostname) { + links.push(parsedUrl.pathname); + } + }); + + links = [...new Set(links)].filter((link) => { + return ( + !link.includes("#") && + !this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending)) + ); + }); + return { html, links }; + } + + private splitUrl(url: URL) { + const baseUrl = new URL("/", url).href; + const basePath = url.pathname; + return { baseUrl, basePath }; + } +} diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts new file mode 100644 index 000000000..1b4dbab01 --- /dev/null +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -0,0 +1,260 @@ +import * as fs from "fs"; +import { URL } from "node:url"; +import { Handler, HTTPResponse, Page } from "puppeteer"; +import { + editConfigJson, + getChromiumPath, + getContinueUtilsPath, +} from "../../../util/paths"; +// @ts-ignore +// @prettier-ignore +import PCR from "puppeteer-chromium-resolver"; +import { ContinueConfig, IDE } from "../../.."; +import { PageData } from "../DocsCrawler"; + +export class ChromiumCrawler { + private readonly LINK_GROUP_SIZE = 2; + private curCrawlCount = 0; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number, + ) {} + + static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { + editConfigJson((config) => ({ + ...config, + experimental: { + ...config.experimental, + useChromiumForDocsCrawling, + }, + })); + } + + async *crawl(): AsyncGenerator { + console.debug( + `[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`, + ); + + const stats = await PCR(ChromiumInstaller.PCR_CONFIG); + const browser = await stats.puppeteer.launch({ + args: [ + "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", + ], + executablePath: stats.executablePath, + }); + const page = await browser.newPage(); + + try { + yield* this.crawlSitePages(page, this.startUrl); + } catch (e) { + console.debug("Error getting links: ", e); + console.debug( + "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", + ); + + ChromiumCrawler.setUseChromiumForDocsCrawling(false); + } finally { + await browser.close(); + } + } + + /** + * We need to handle redirects manually, otherwise there are race conditions. + * + * https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573 + */ + private async gotoPageAndHandleRedirects(page: Page, url: string) { + const MAX_PAGE_WAIT_MS = 5000; + + await page.goto(url, { + timeout: 0, + waitUntil: "networkidle2", + }); + + let responseEventOccurred = false; + const responseHandler: Handler = (event) => + (responseEventOccurred = true); + + const responseWatcher = new Promise(function (resolve, reject) { + setTimeout(() => { + if (!responseEventOccurred) { + resolve(); + } else { + setTimeout(() => resolve(), MAX_PAGE_WAIT_MS); + } + }, 500); + }); + + page.on("response", responseHandler); + + await Promise.race([responseWatcher, page.waitForNavigation()]); + } + + private async *crawlSitePages( + page: Page, + curUrl: URL, + visitedLinks: Set = new Set(), + ): AsyncGenerator { + const urlStr = curUrl.toString(); + + if (visitedLinks.has(urlStr)) { + return; + } + + await this.gotoPageAndHandleRedirects(page, urlStr); + + const htmlContent = await page.content(); + const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); + this.curCrawlCount++; + + visitedLinks.add(urlStr); + + yield { + path: curUrl.pathname, + url: urlStr, + content: htmlContent, + }; + + for (const linkGroup of linkGroups) { + let enqueuedLinkCount = this.curCrawlCount; + + for (const link of linkGroup) { + enqueuedLinkCount++; + console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); + if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { + yield* this.crawlSitePages(page, new URL(link), visitedLinks); + } + } + } + } + + private stripHashFromUrl(urlStr: string) { + try { + let url = new URL(urlStr); + url.hash = ""; + return url; + } catch (err) { + return null; + } + } + + private isValidHostAndPath(newUrl: URL, curUrl: URL) { + return ( + newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host + ); + } + + private async getLinksFromPage(page: Page, curUrl: URL) { + const links = await page.$$eval("a", (links) => links.map((a) => a.href)); + + const cleanedLinks = links + .map(this.stripHashFromUrl) + .filter( + (newUrl) => + newUrl !== null && + this.isValidHostAndPath(newUrl, curUrl) && + newUrl !== curUrl, + ) + .map((newUrl) => (newUrl as URL).href); + + const dedupedLinks = Array.from(new Set(cleanedLinks)); + + return dedupedLinks; + } + + private async getLinkGroupsFromPage(page: Page, curUrl: URL) { + const links = await this.getLinksFromPage(page, curUrl); + + const groups = links.reduce((acc, link, i) => { + const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); + + if (!acc[groupIndex]) { + acc.push([]); + } + + acc[groupIndex].push(link); + + return acc; + }, [] as string[][]); + + return groups; + } +} + +export class ChromiumInstaller { + static PCR_CONFIG = { downloadPath: getContinueUtilsPath() }; + + constructor( + private readonly ide: IDE, + private readonly config: ContinueConfig, + ) { + if (this.shouldInstallOnStartup()) { + console.log("Installing Chromium"); + void this.install(); + } + } + + isInstalled() { + return fs.existsSync(getChromiumPath()); + } + + shouldInstallOnStartup() { + return ( + !this.isInstalled() && + this.config.experimental?.useChromiumForDocsCrawling + ); + } + + shouldProposeUseChromiumOnCrawlFailure() { + const { experimental } = this.config; + + return ( + experimental?.useChromiumForDocsCrawling === undefined || + experimental.useChromiumForDocsCrawling + ); + } + + async proposeAndAttemptInstall(site: string) { + const userAcceptedInstall = await this.proposeInstall(site); + + if (userAcceptedInstall) { + const didInstall = await this.install(); + return didInstall; + } + } + + async install() { + try { + await PCR(ChromiumInstaller.PCR_CONFIG); + + ChromiumCrawler.setUseChromiumForDocsCrawling(true); + + return true; + } catch (error) { + console.debug("Error installing Chromium : ", error); + console.debug( + "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", + ); + + ChromiumCrawler.setUseChromiumForDocsCrawling(false); + + await this.ide.showToast("error", "Failed to install Chromium"); + + return false; + } + } + + private async proposeInstall(site: string) { + const msg = + `Unable to crawl documentation site: ${site}\n` + + "We recommend installing Chromium. " + + "Download progress can be viewed in the developer console."; + + const actionMsg = "Install Chromium"; + + const res = await this.ide.showToast("warning", msg, actionMsg); + + return res === actionMsg; + } +} diff --git a/core/indexing/docs/crawlers/DefaultCrawler.ts b/core/indexing/docs/crawlers/DefaultCrawler.ts new file mode 100644 index 000000000..64a65c8fd --- /dev/null +++ b/core/indexing/docs/crawlers/DefaultCrawler.ts @@ -0,0 +1,25 @@ +import { URL } from "node:url"; +import { getHeaders } from "../../../continueServer/stubs/headers"; +import { TRIAL_PROXY_URL } from "../../../control-plane/client"; +import { PageData } from "../DocsCrawler"; + +export class DefaultCrawler { + constructor(private readonly startUrl: URL) {} + + async crawl(): Promise { + const resp = await fetch(new URL("crawl", TRIAL_PROXY_URL).toString(), { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(await getHeaders()), + }, + body: JSON.stringify({ startUrl: this.startUrl.toString() }), + }); + if (!resp.ok) { + const text = await resp.text(); + throw new Error(`Failed to crawl site: ${text}`); + } + const json = (await resp.json()) as PageData[]; + return json; + } +} diff --git a/core/indexing/docs/crawlers/GitHubCrawler.ts b/core/indexing/docs/crawlers/GitHubCrawler.ts new file mode 100644 index 000000000..41362cf72 --- /dev/null +++ b/core/indexing/docs/crawlers/GitHubCrawler.ts @@ -0,0 +1,80 @@ +import { Octokit } from "@octokit/rest"; +import { URL } from "node:url"; +import { PageData } from "../DocsCrawler"; + +class GitHubCrawler { + private readonly markdownRegex = new RegExp(/\.(md|mdx)$/); + private octokit = new Octokit({ auth: undefined }); + + constructor(private readonly startUrl: URL) {} + + async *crawl(): AsyncGenerator { + console.debug( + `[${ + (this.constructor as any).name + }] Crawling GitHub repo: ${this.startUrl.toString()}`, + ); + const urlStr = this.startUrl.toString(); + const [_, owner, repo] = this.startUrl.pathname.split("/"); + const branch = await this.getGithubRepoDefaultBranch(owner, repo); + const paths = await this.getGitHubRepoPaths(owner, repo, branch); + + for await (const path of paths) { + const content = await this.getGithubRepoFileContent(path, owner, repo); + yield { path, url: urlStr, content: content ?? "" }; + } + } + + private async getGithubRepoDefaultBranch( + owner: string, + repo: string, + ): Promise { + const repoInfo = await this.octokit.repos.get({ owner, repo }); + return repoInfo.data.default_branch; + } + + private async getGitHubRepoPaths( + owner: string, + repo: string, + branch: string, + ) { + const tree = await this.octokit.request( + "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", + { + owner, + repo, + tree_sha: branch, + headers: { "X-GitHub-Api-Version": "2022-11-28" }, + recursive: "true", + }, + ); + + return tree.data.tree + .filter( + (file: any) => + file.type === "blob" && this.markdownRegex.test(file.path ?? ""), + ) + .map((file: any) => file.path); + } + + private async getGithubRepoFileContent( + path: string, + owner: string, + repo: string, + ) { + try { + const response = await this.octokit.repos.getContent({ + owner, + repo, + path, + headers: { Accept: "application/vnd.github.raw+json" }, + }); + return response.data as unknown as string; + } catch (error) { + console.debug("Error fetching file contents:", error); + return null; + } + } +} + +export default GitHubCrawler; diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 9da86ef85..48b777b21 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -299,6 +299,32 @@ const preIndexedDocs: Record< rootUrl: "https://docs.godotengine.org/en/latest/", faviconUrl: "https://godotengine.org/favicon.ico", }, + "https://docs.amplify.aws/react/start/": { + title: "AWS Amplify (Gen 2)", + startUrl: "https://docs.amplify.aws/react/start/", + rootUrl: "https://docs.amplify.aws/react/", + faviconUrl: "https://docs.amplify.aws/favicon.ico", + }, + "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": { + title: "AWS SDK for JavaScript v3", + startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", + rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/", + faviconUrl: "https://docs.aws.amazon.com/favicon.ico", + }, + "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": { + title: "AWS CDK v2", + startUrl: + "https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html", + rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/", + faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png", + }, + "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": { + title: "AWS CLI commands", + startUrl: + "https://awscli.amazonaws.com/v2/documentation/api/latest/index.html", + rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/", + faviconUrl: "https://docs.aws.amazon.com/favicon.ico", + }, }; export default preIndexedDocs; diff --git a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts index bf3bcac88..a5cfce6c4 100644 --- a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts +++ b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts @@ -6,11 +6,14 @@ import { fromIni } from "@aws-sdk/credential-providers"; import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js"; import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; +interface ModelConfig { + formatPayload: (text: string) => any; + extractEmbeddings: (responseBody: any) => number[][]; +} + class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "bedrock"; - - static defaultOptions: Partial | undefined = { + static defaultOptions: Partial = { model: "amazon.titan-embed-text-v2:0", region: "us-east-1" }; @@ -18,6 +21,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { constructor(options: EmbedOptions, fetch: FetchFunction) { super(options, fetch); + this.options.model = this.options.model || BedrockEmbeddingsProvider.defaultOptions.model!; if (!options.apiBase) { options.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; } @@ -29,7 +33,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { } } - async embed(chunks: string[]) { + async embed(chunks: string[]): Promise { const credentials = await this._getCredentials(); const client = new BedrockRuntimeClient({ region: this.options.region, @@ -43,41 +47,64 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { return ( await Promise.all( chunks.map(async (chunk) => { - const input = this._generateInvokeModelCommandInput(chunk, this.options); + const input = this._generateInvokeModelCommandInput(chunk); const command = new InvokeModelCommand(input); const response = await client.send(command); - if (response.body) { const responseBody = JSON.parse(new TextDecoder().decode(response.body)); - return [responseBody.embedding]; + return this._extractEmbeddings(responseBody); } + return []; }), ) ).flat(); } - private _generateInvokeModelCommandInput( - prompt: string, - options: EmbedOptions, - ): any { - const payload = { - "inputText": prompt, - "dimensions": 512, - "normalize": true - }; + private _generateInvokeModelCommandInput(text: string): any { + const modelConfig = this._getModelConfig(); + const payload = modelConfig.formatPayload(text); return { body: JSON.stringify(payload), modelId: this.options.model, - accept: "application/json", - contentType: "application/json" + accept: "*/*", + contentType: "application/json", }; } + private _extractEmbeddings(responseBody: any): number[][] { + const modelConfig = this._getModelConfig(); + return modelConfig.extractEmbeddings(responseBody); + } + + private _getModelConfig() { + const modelConfigs: { [key: string]: ModelConfig } = { + 'cohere': { + formatPayload: (text: string) => ({ + texts: [text], + input_type: "search_document", + truncate: "END", + }), + extractEmbeddings: (responseBody: any) => responseBody.embeddings || [], + }, + 'amazon.titan-embed': { + formatPayload: (text: string) => ({ + inputText: text, + }), + extractEmbeddings: (responseBody: any) => responseBody.embedding ? [responseBody.embedding] : [], + }, + }; + + const modelPrefix = Object.keys(modelConfigs).find(prefix => this.options.model!.startsWith(prefix)); + if (!modelPrefix) { + throw new Error(`Unsupported model: ${this.options.model}`); + } + return modelConfigs[modelPrefix]; + } + private async _getCredentials() { try { - return await - fromIni({ + return await fromIni({ profile: this.profile, ignoreCache: true })(); @@ -88,7 +115,6 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { return await fromIni()(); } } - } export default BedrockEmbeddingsProvider; diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts new file mode 100644 index 000000000..f5ec128d3 --- /dev/null +++ b/core/indexing/embeddings/LMStudio.ts @@ -0,0 +1,13 @@ +import { EmbeddingsProviderName, EmbedOptions } from "../.."; +import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; + +class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "lmstudio"; + + static defaultOptions: Partial | undefined = { + apiBase: "http://localhost:1234/v1", + model: "nomic-ai/nomic-embed-text-v1.5-GGUF", + }; +} + +export default LMStudioEmbeddingsProvider; \ No newline at end of file diff --git a/core/indexing/embeddings/NebiusEmbeddingsProvider.ts b/core/indexing/embeddings/NebiusEmbeddingsProvider.ts new file mode 100644 index 000000000..4bf20e868 --- /dev/null +++ b/core/indexing/embeddings/NebiusEmbeddingsProvider.ts @@ -0,0 +1,13 @@ +import { EmbeddingsProviderName, EmbedOptions } from "../.."; +import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; + +class NebiusEmbeddingsProvider extends OpenAIEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "nebius"; + + static defaultOptions: Partial | undefined = { + apiBase: "https://api.studio.nebius.ai/v1/", + model: "BAAI/bge-en-icl", + }; +} + +export default NebiusEmbeddingsProvider; diff --git a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts index 290dad1fe..43aa84020 100644 --- a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts @@ -8,12 +8,12 @@ import BaseEmbeddingsProvider, { IBaseEmbeddingsProvider, } from "./BaseEmbeddingsProvider.js"; -async function embedOne( - chunk: string, +async function embedOneBatch( + chunks: string[], options: EmbedOptions, customFetch: FetchFunction, ) { - const embedding = await withExponentialBackoff(async () => { + const embedding = await withExponentialBackoff(async () => { let apiBase = options.apiBase!; if (!apiBase.endsWith("/")) { @@ -24,7 +24,7 @@ async function embedOne( method: "POST", body: JSON.stringify({ model: options.model, - input: chunk, + input: chunks, }), headers: { "Content-Type": "application/json", @@ -37,7 +37,7 @@ async function embedOne( } const data = await resp.json(); - const embedding = data.embeddings[0]; + const embedding: number[][] = data.embeddings; if (!embedding || embedding.length === 0) { throw new Error("Ollama generated empty embedding"); @@ -53,12 +53,15 @@ class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider { static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"] = { apiBase: "http://localhost:11434/", model: "nomic-embed-text", + maxBatchSize: 64, }; async embed(chunks: string[]) { - const results: any = []; - for (const chunk of chunks) { - results.push(await embedOne(chunk, this.options, this.fetch)); + const batchedChunks = this.getBatchedChunks(chunks); + var results: number[][] = []; + + for (const batch of batchedChunks) { + results.push(...await embedOneBatch(batch, this.options, this.fetch)); } return results; } diff --git a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts index 0f755ae3a..95308bbd9 100644 --- a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts @@ -12,6 +12,7 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { static defaultOptions: Partial | undefined = { apiBase: "https://api.openai.com/v1/", model: "text-embedding-3-small", + apiVersion: "2024-02-15-preview", }; private _getEndpoint() { @@ -27,7 +28,7 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { if (this.options.apiType === "azure") { return new URL( - `openai/deployments/${this.options.engine}/embeddings?api-version=${this.options.apiVersion}`, + `openai/deployments/${this.options.deployment}/embeddings?api-version=${this.options.apiVersion}`, this.options.apiBase, ); } diff --git a/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts b/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts index 9b860f1ae..a8a3fb0a5 100644 --- a/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts +++ b/core/indexing/embeddings/SageMakerEmbeddingsProvider.ts @@ -1,114 +1,114 @@ import { - InvokeEndpointCommand, - SageMakerRuntimeClient, - } from "@aws-sdk/client-sagemaker-runtime"; - import { fromIni } from "@aws-sdk/credential-providers"; - - import { - EmbeddingsProviderName, - EmbedOptions, - FetchFunction, - } from "../../index.js"; - import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; - - - class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider { - static providerName: EmbeddingsProviderName = "sagemaker"; - - static defaultOptions: Partial | undefined = { - region: "us-west-2", - maxBatchSize: 1, - }; - profile?: string | undefined; - - constructor(options: EmbedOptions, fetch: FetchFunction) { - super(options, fetch); - if (!options.apiBase) { - options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`; - } - - if (options.profile) { - this.profile = options.profile; - } else { - this.profile = "sagemaker"; - } + InvokeEndpointCommand, + SageMakerRuntimeClient, +} from "@aws-sdk/client-sagemaker-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; + +import { + EmbeddingsProviderName, + EmbedOptions, + FetchFunction, +} from "../../index.js"; + +import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; + + +class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "sagemaker"; + + static defaultOptions: Partial | undefined = { + region: "us-west-2", + maxBatchSize: 1, + }; + profile?: string | undefined; + + constructor(options: EmbedOptions, fetch: FetchFunction) { + super(options, fetch); + if (!options.apiBase) { + options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`; } - - async embed(chunks: string[]) { - const credentials = await this._getCredentials(); - const client = new SageMakerRuntimeClient({ - region: this.options.region, - credentials: { - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - sessionToken: credentials.sessionToken || "", - }, - }); - - const batchedChunks = this.getBatchedChunks(chunks); - return ( - await Promise.all( - batchedChunks.map(async (batch) => { - const input = this._generateInvokeModelCommandInput( - batch, - this.options, - ); - const command = new InvokeEndpointCommand(input); - const response = await client.send(command); - - if (response.Body) { - const responseBody = JSON.parse( - new TextDecoder().decode(response.Body), - ); - // If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body - if (responseBody.embedding) { - return responseBody.embedding; - } else if (responseBody.embeddings) { - return responseBody.embeddings; - } else { - return responseBody; - } - } - }), - ) - ).flat(); - } - private _generateInvokeModelCommandInput( - prompts: string | string[], - options: EmbedOptions, - ): any { - const payload = { - inputs: prompts, - normalize: true, - // ...(options.requestOptions?.extraBodyProperties || {}), - }; - - if (options.requestOptions?.extraBodyProperties) { - Object.assign(payload, options.requestOptions.extraBodyProperties); - } - - return { - EndpointName: this.options.model, - Body: JSON.stringify(payload), - ContentType: "application/json", - CustomAttributes: "accept_eula=false", - }; - } - - private async _getCredentials() { - try { - return await fromIni({ - profile: this.profile, - ignoreCache: true, - })(); - } catch (e) { - console.warn( - `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, - ); - return await fromIni()(); - } + + if (options.profile) { + this.profile = options.profile; + } else { + this.profile = "sagemaker"; } } - - export default SageMakerEmbeddingsProvider; - \ No newline at end of file + + async embed(chunks: string[]) { + const credentials = await this._getCredentials(); + const client = new SageMakerRuntimeClient({ + region: this.options.region, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + + const batchedChunks = this.getBatchedChunks(chunks); + return ( + await Promise.all( + batchedChunks.map(async (batch) => { + const input = this._generateInvokeModelCommandInput( + batch, + this.options, + ); + const command = new InvokeEndpointCommand(input); + const response = await client.send(command); + + if (response.Body) { + const responseBody = JSON.parse( + new TextDecoder().decode(response.Body), + ); + // If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body + if (responseBody.embedding) { + return responseBody.embedding; + } else if (responseBody.embeddings) { + return responseBody.embeddings; + } else { + return responseBody; + } + } + }), + ) + ).flat(); + } + private _generateInvokeModelCommandInput( + prompts: string | string[], + options: EmbedOptions, + ): any { + const payload = { + inputs: prompts, + normalize: true, + // ...(options.requestOptions?.extraBodyProperties || {}), + }; + + if (options.requestOptions?.extraBodyProperties) { + Object.assign(payload, options.requestOptions.extraBodyProperties); + } + + return { + EndpointName: this.options.model, + Body: JSON.stringify(payload), + ContentType: "application/json", + CustomAttributes: "accept_eula=false", + }; + } + + private async _getCredentials() { + try { + return await fromIni({ + profile: this.profile, + ignoreCache: true, + })(); + } catch (e) { + console.warn( + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} + +export default SageMakerEmbeddingsProvider; diff --git a/core/indexing/embeddings/VertexEmbeddingsProvider.ts b/core/indexing/embeddings/VertexEmbeddingsProvider.ts new file mode 100644 index 000000000..7188254a1 --- /dev/null +++ b/core/indexing/embeddings/VertexEmbeddingsProvider.ts @@ -0,0 +1,89 @@ +import { GoogleAuth } from "google-auth-library"; +import { Response } from "node-fetch"; +import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js"; +import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; +import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; + +/** + * [View the Vertex Text Embedding docs.](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings) + */ +class VertexEmbeddingsProvider extends BaseEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "vertexai"; + declare apiBase: string; + + + static defaultOptions: Partial | undefined = { + model: "text-embedding-004", + maxBatchSize: 5, + region: "us-central1" + }; + + private clientPromise = new GoogleAuth({ + scopes: "https://www.googleapis.com/auth/cloud-platform", + }).getClient(); + + private static getDefaultApiBaseFrom(options: EmbedOptions) { + const { region, projectId } = options; + if (!region || !projectId) { + throw new Error( + "region and projectId must be defined if apiBase is not provided", + ); + } + + return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}`; + } + + + + constructor(options: EmbedOptions, fetch: FetchFunction) { + super(options, fetch); + this.apiBase ??= VertexEmbeddingsProvider.getDefaultApiBaseFrom(options); + + } + + + + get urlPath(): string { + return `/publishers/google/models/${this.options.model}:predict`; + } + + async embed(chunks: string[]) { + const client = await this.clientPromise; + const { token } = await client.getAccessToken(); + if (!token) { + throw new Error( + "Could not get an access token. Set up your Google Application Default Credentials.", + ); + } + const batchedChunks = this.getBatchedChunks(chunks); + + return ( + await Promise.all( + batchedChunks.map(async (batch) => { + const fetchWithBackoff = () => + withExponentialBackoff(() => + this.fetch(new URL(this.apiBase + this.urlPath), { + method: "POST", + body: JSON.stringify({ + instances: batch.map((chunk) => ({ content: chunk })), + }), + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + }), + ); + const resp = await fetchWithBackoff(); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + return data.predictions.map((prediction: any) => prediction.embeddings.values); + }), + ) + ).flat(); + } +} +export default VertexEmbeddingsProvider; diff --git a/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts b/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts new file mode 100644 index 000000000..1c352697a --- /dev/null +++ b/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts @@ -0,0 +1,150 @@ +import { + EmbeddingsProviderName, + EmbedOptions, + FetchFunction, +} from "../../index.js"; +import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; +import BaseEmbeddingsProvider, { + IBaseEmbeddingsProvider, +} from "./BaseEmbeddingsProvider.js"; + +let accessToken = { + expiration: 0, + token: "", +}; + + +class WatsonxEmbeddingsProvider extends BaseEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "watsonx"; + static maxBatchSize = 1000; + static defaultOptions: Partial | undefined = { + model: "ibm/slate-125m-english-rtrvr-v2", + }; + + async getBearerToken(): Promise<{ token: string; expiration: number }> { + if ( + this.options.apiBase?.includes("cloud.ibm.com") + ) { + // watsonx SaaS + const wxToken = await ( + await fetch( + `https://iam.cloud.ibm.com/identity/token?apikey=${this.options.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, + { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json", + }, + }, + ) + ).json(); + return { + token: wxToken["access_token"], + expiration: wxToken["expiration"], + }; + } else { + // watsonx Software + if (!this.options.apiKey?.includes(":")) { + // Using ZenApiKey auth + return { + token: this.options.apiKey ?? "", + expiration: -1, + }; + } else { + // Using username/password auth + const userPass = this.options.apiKey?.split(":"); + const wxToken = await ( + await fetch(`${this.options.apiBase}/icp4d-api/v1/authorize`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify({ + username: userPass[0], + password: userPass[1], + }), + }) + ).json(); + const wxTokenExpiry = await ( + await fetch( + `${this.options.apiBase}/usermgmt/v1/user/tokenExpiry`, + { + method: "GET", + headers: { + Accept: "application/json", + Authorization: `Bearer ${wxToken["token"]}`, + }, + }, + ) + ).json(); + return { + token: wxToken["token"], + expiration: wxTokenExpiry["exp"], + }; + } + } + } + async getSingleBatchEmbedding(batch: string[]) { + var now = new Date().getTime() / 1000; + if ( + accessToken === undefined || + now > accessToken.expiration || + accessToken.token === undefined + ) { + accessToken = await this.getBearerToken(); + } else { + console.log( + `Reusing token (expires in ${(accessToken.expiration - now) / 60 + } mins)`, + ); + } + return await withExponentialBackoff(async () => { + const payload: any = { + inputs: batch, + parameters: { + truncate_input_tokens: 500, + return_options: { input_text: false }, + }, + model_id: this.options.model, + project_id: this.options.projectId, + }; + const headers = { + "Content-Type": "application/json", + Authorization: `${accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${accessToken.token}`, + }; + const resp = await this.fetch( + new URL( + `${this.options.apiBase}/ml/v1/text/embeddings?version=${this.options.apiVersion}`, + ), + { + method: "POST", + body: JSON.stringify(payload), + headers: headers, + }, + ); + + if (!resp.ok) { + throw new Error(`Failed to embed chunk: ${await resp.text()}`); + } + const data = await resp.json(); + const embeddings = data.results; + + if (!embeddings || embeddings.length === 0) { + throw new Error("Watsonx generated empty embedding"); + } + return embeddings.map((e: any) => e.embedding); + }); + } + + async embed(chunks: string[]) { + const batchedChunks = this.getBatchedChunks(chunks); + const results = await Promise.all( + batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)), + ); + return results.flat(); + } +} + +export default WatsonxEmbeddingsProvider; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index 0eb2ae11f..b0508d3fd 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -14,6 +14,10 @@ import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js"; import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js"; import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; +import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js"; +import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js"; +import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js"; +import LMStudioEmbeddingsProvider from "./LMStudio.js"; type EmbeddingsProviderConstructor = new ( ...args: any[] @@ -37,4 +41,8 @@ export const allEmbeddingsProviders: Record< nvidia: NvidiaEmbeddingsProvider, voyage: VoyageEmbeddingsProvider, mistral: MistralEmbeddingsProvider, + nebius: NebiusEmbeddingsProvider, + vertexai: VertexEmbeddingsProvider, + watsonx: WatsonxEmbeddingsProvider, + lmstudio: LMStudioEmbeddingsProvider }; diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 0b2714f1d..06b8cac51 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -1,4 +1,7 @@ import ignore from "ignore"; +import path from "path"; +import os from "os"; +import fs from "fs"; export const DEFAULT_IGNORE_FILETYPES = [ "*.DS_Store", @@ -114,3 +117,18 @@ export function gitIgArrayFromFile(file: string) { .map((l) => l.trim()) // Remove whitespace .filter((l) => !/^#|^$/.test(l)); // Remove empty lines } + +export const GLOBAL_CONTINUEIGNORE_PATH = path.join(os.homedir(), ".continue", ".continueignore"); + +export const getGlobalContinueIgArray = () => { + try { + const contents = fs.readFileSync(GLOBAL_CONTINUEIGNORE_PATH, "utf8"); + return gitIgArrayFromFile(contents); + } catch (error) { + // If the file doesn't exist, that's okay + if (error instanceof Error && ("code" in error) && error.code === "ENOENT") { + return []; + } + throw error; + } +}; \ No newline at end of file diff --git a/core/indexing/refreshIndex.test.ts b/core/indexing/refreshIndex.test.ts new file mode 100644 index 000000000..7eeb2c5d8 --- /dev/null +++ b/core/indexing/refreshIndex.test.ts @@ -0,0 +1,34 @@ +import { truncateToLastNBytes } from "./refreshIndex"; + +describe("truncateToLastNBytes", () => { + it("should return full string if maxBytes greater than string byte length", () => { + const input = "Hello World"; + const result = truncateToLastNBytes(input, 100); + expect(result).toBe("Hello World"); + }); + + it("should truncate ASCII string correctly", () => { + const input = "Hello World"; + const result = truncateToLastNBytes(input, 5); + expect(result).toBe("World"); + }); + + it("should handle empty string", () => { + const input = ""; + const result = truncateToLastNBytes(input, 5); + expect(result).toBe(""); + }); + + it("should handle UTF-8 characters correctly", () => { + const input = "👋 Hello"; + // 👋 is 4 bytes, space is 1 byte + const result = truncateToLastNBytes(input, 5); + expect(result).toBe("Hello"); + }); + + it("should handle maxBytes of 0", () => { + const input = "Hello World"; + const result = truncateToLastNBytes(input, 0); + expect(result).toBe(""); + }); +}); diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 51cbdb646..ba2dbd820 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -416,11 +416,9 @@ export async function getComputeDeleteAddRemove( export class GlobalCacheCodeBaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; - private db: DatabaseConnection; - constructor(db: DatabaseConnection) { - this.db = db; - } + constructor(private db: DatabaseConnection) {} + artifactId = "globalCache"; static async create(): Promise { @@ -471,3 +469,24 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex { ); } } + +const SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000; + +export function truncateToLastNBytes(input: string, maxBytes: number): string { + let bytes = 0; + let startIndex = 0; + + for (let i = input.length - 1; i >= 0; i--) { + bytes += new TextEncoder().encode(input[i]).length; + if (bytes > maxBytes) { + startIndex = i + 1; + break; + } + } + + return input.substring(startIndex, input.length); +} + +export function truncateSqliteLikePattern(input: string) { + return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH); +} diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index eeeb064d0..44f785ab4 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -6,6 +6,7 @@ import { DEFAULT_IGNORE_FILETYPES, defaultIgnoreDir, defaultIgnoreFile, + getGlobalContinueIgArray, gitIgArrayFromFile, } from "./ignore.js"; @@ -38,15 +39,13 @@ type IgnoreContext = { }; class DFSWalker { - private readonly path: string; - private readonly ide: IDE; - private readonly options: WalkerOptions; private readonly ignoreFileNames: Set; - constructor(path: string, ide: IDE, options: WalkerOptions) { - this.path = path; - this.ide = ide; - this.options = options; + constructor( + private readonly path: string, + private readonly ide: IDE, + private readonly options: WalkerOptions, + ) { this.ignoreFileNames = new Set(options.ignoreFiles); } @@ -85,6 +84,7 @@ class DFSWalker { } private newRootWalkContext(): WalkContext { + const globalIgnoreFile = getGlobalContinueIgArray(); return { walkableEntry: { relPath: "", @@ -94,7 +94,7 @@ class DFSWalker { }, ignoreContexts: [ { - ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), + ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile).add(globalIgnoreFile), dirname: "", }, ], @@ -128,10 +128,7 @@ class DFSWalker { ignore: ignore().add(patterns), dirname: curDir.walkableEntry.relPath, }; - return [ - ...curDir.ignoreContexts, - newIgnoreContext - ]; + return [...curDir.ignoreContexts, newIgnoreContext]; } private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { @@ -147,7 +144,10 @@ class DFSWalker { return this.ignoreFileNames.has(p); } - private shouldInclude(walkableEntry: WalkableEntry, ignoreContexts: IgnoreContext[]) { + private shouldInclude( + walkableEntry: WalkableEntry, + ignoreContexts: IgnoreContext[], + ) { if (this.entryIsSymlink(walkableEntry.entry)) { // If called from the root, a symlink either links to a real file in this repository, // and therefore will be walked OR it linksto something outside of the repository and diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 369421406..64e0634a5 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -5,6 +5,7 @@ import { codeLlama70bTemplateMessages, deepseekTemplateMessages, gemmaTemplateMessage, + graniteTemplateMessages, llama2TemplateMessages, llama3TemplateMessages, llavaTemplateMessages, @@ -41,28 +42,27 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [ "together", "msty", "anthropic", - "anthropic-vertexai", "bedrock", "sagemaker", "continue-proxy", "mistral", - "mistral-vertexai", "sambanova", + "vertexai", + "watsonx" ]; const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [ "openai", "ollama", "gemini", - "gemini-vertexai", "free-trial", "msty", "anthropic", - "anthropic-vertexai", "bedrock", "sagemaker", "continue-proxy", "openrouter", + "vertexai" ]; const MODEL_SUPPORTS_IMAGES: string[] = [ @@ -79,6 +79,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "opus", "haiku", "pixtral", + "llama3.2", ]; function modelSupportsImages( @@ -107,20 +108,19 @@ function modelSupportsImages( } const PARALLEL_PROVIDERS: ModelProvider[] = [ "anthropic", - "anthropic-vertexai", "bedrock", "sagemaker", "deepinfra", "gemini", - "gemini-vertexai", "huggingface-inference-api", "huggingface-tgi", "mistral", - "mistral-vertexai", "free-trial", "replicate", "together", "sambanova", + "nebius", + "vertexai" ]; function llmCanGenerateInParallel( @@ -146,7 +146,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("command") || lower.includes("chat-bison") || lower.includes("pplx") || - lower.includes("gemini") + lower.includes("gemini") || + lower.includes("grok") ) { return undefined; } @@ -220,6 +221,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { return "neural-chat"; } + if (lower.includes("granite")) { + return "granite"; + } + return "chatml"; } @@ -253,6 +258,7 @@ function autodetectTemplateFunction( llava: llavaTemplateMessages, "codellama-70b": codeLlama70bTemplateMessages, gemma: gemmaTemplateMessage, + granite: graniteTemplateMessages, llama3: llama3TemplateMessages, none: null, }; diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 35a287fd5..8d5d1cc35 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -1,5 +1,5 @@ -import { ChatMessage, LLMOptions, ModelProvider } from ".."; import { BaseLLM } from "."; +import { ChatMessage, LLMOptions, ModelProvider } from ".."; class DummyLLM extends BaseLLM { static providerName: ModelProvider = "openai"; @@ -48,7 +48,7 @@ describe("BaseLLM", () => { aiGatewaySlug: "testSlug", apiBase: "https://api.example.com", accountId: "testAccountId", - engine: "davinci", + deployment: "davinci", apiVersion: "v1", apiType: "public", region: "us", @@ -71,7 +71,7 @@ describe("BaseLLM", () => { expect(instance.aiGatewaySlug).toBe("testSlug"); expect(instance.apiBase).toBe("https://api.example.com/"); expect(instance.accountId).toBe("testAccountId"); - expect(instance.engine).toBe("davinci"); + expect(instance.deployment).toBe("davinci"); expect(instance.apiVersion).toBe("v1"); expect(instance.apiType).toBe("public"); expect(instance.region).toBe("us"); diff --git a/core/llm/index.ts b/core/llm/index.ts index 53c984b43..4d3f2fd6e 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -106,7 +106,7 @@ export abstract class BaseLLM implements ILLM { cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; - engine?: string; + deployment?: string; apiVersion?: string; apiType?: string; region?: string; @@ -114,13 +114,8 @@ export abstract class BaseLLM implements ILLM { accountId?: string; aiGatewaySlug?: string; - // For IBM watsonx only. - watsonxUrl?: string; - watsonxCreds?: string; - watsonxProjectId?: string; - watsonxStopToken?: string; - watsonxApiVersion?: string; - watsonxFullUrl?: string; + // For IBM watsonx + deploymentId?: string; private _llmOptions: LLMOptions; @@ -186,13 +181,8 @@ export abstract class BaseLLM implements ILLM { this.apiBase = options.apiBase; this.cacheBehavior = options.cacheBehavior; - // for watsonx only - this.watsonxUrl = options.watsonxUrl; - this.watsonxCreds = options.watsonxCreds; - this.watsonxProjectId = options.watsonxProjectId; - this.watsonxStopToken = options.watsonxStopToken; - this.watsonxApiVersion = options.watsonxApiVersion; - this.watsonxFullUrl = options.watsonxFullUrl; + // watsonx deploymentId + this.deploymentId = options.deploymentId; if (this.apiBase && !this.apiBase.endsWith("/")) { this.apiBase = `${this.apiBase}/`; @@ -200,7 +190,7 @@ export abstract class BaseLLM implements ILLM { this.accountId = options.accountId; this.capabilities = options.capabilities; - this.engine = options.engine; + this.deployment = options.deployment; this.apiVersion = options.apiVersion; this.apiType = options.apiType; this.region = options.region; @@ -511,15 +501,20 @@ export abstract class BaseLLM implements ILLM { } let completion = ""; - for await (const chunk of this._streamComplete(prompt, completionOptions)) { - completion += chunk; - yield chunk; - } + try { + for await (const chunk of this._streamComplete( + prompt, + completionOptions, + )) { + completion += chunk; + yield chunk; + } + } finally { + this._logTokensGenerated(completionOptions.model, prompt, completion); - this._logTokensGenerated(completionOptions.model, prompt, completion); - - if (log && this.writeLog) { - await this.writeLog(`Completion:\n\n${completion}\n\n`); + if (log && this.writeLog) { + await this.writeLog(`Completion:\n\n${completion}\n\n`); + } } return { diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index f2182d851..eaedde8de 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -11,16 +11,17 @@ import { streamSse } from "../stream.js"; class Anthropic extends BaseLLM { static providerName: ModelProvider = "anthropic"; static defaultOptions: Partial = { - model: "claude-3-5-sonnet-20240620", + model: "claude-3-5-sonnet-latest", contextLength: 200_000, completionOptions: { - model: "claude-3-5-sonnet-20240620", + model: "claude-3-5-sonnet-latest", maxTokens: 4096, }, apiBase: "https://api.anthropic.com/v1/", }; - private _convertArgs(options: CompletionOptions) { + public convertArgs(options: CompletionOptions) { + // should be public for use within VertexAI const finalOptions = { top_k: options.topK, top_p: options.topP, @@ -34,53 +35,61 @@ class Anthropic extends BaseLLM { return finalOptions; } - private _convertMessages(msgs: ChatMessage[]): any[] { - const filteredmessages = msgs.filter((m) => m.role !== "system") - const lastTwoUserMsgIndices = filteredmessages + public convertMessages(msgs: ChatMessage[]): any[] { + // should be public for use within VertexAI + const filteredmessages = msgs.filter((m) => m.role !== "system"); + const lastTwoUserMsgIndices = filteredmessages .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1).slice(-2); + .filter((index) => index !== -1) + .slice(-2); const messages = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching - const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching + const addCaching = + this.cacheBehavior?.cacheConversation && + lastTwoUserMsgIndices.includes(filteredMsgIdx); - if (typeof message.content === "string") { - var chatMessage = { - ...message, - content: [{ - type: "text", - text: message.content, - ...(addCaching? { cache_control: { type: "ephemeral" } } : {}) - }] - }; - return chatMessage; - } - - return { + if (typeof message.content === "string") { + var chatMessage = { ...message, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {}) - }; - return newpart; - } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), + content: [ + { + type: "text", + text: message.content, + ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), + }, + ], }; - }); + return chatMessage; + } + + return { + ...message, + content: message.content.map((part, contentIdx) => { + if (part.type === "text") { + const newpart = { + ...part, + // If multiple text parts, only add cache_control to the last one + ...(addCaching && contentIdx == message.content.length - 1 + ? { cache_control: { type: "ephemeral" } } + : {}), + }; + return newpart; + } + return { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + }), + }; + }); return messages; } @@ -98,7 +107,8 @@ class Anthropic extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const shouldCacheSystemMessage = + !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; const systemMessage: string = stripImages( messages.filter((m) => m.role === "system")[0]?.content, ); @@ -115,8 +125,8 @@ class Anthropic extends BaseLLM { : {}), }, body: JSON.stringify({ - ...this._convertArgs(options), - messages: this._convertMessages(messages), + ...this.convertArgs(options), + messages: this.convertMessages(messages), system: shouldCacheSystemMessage ? [ { diff --git a/core/llm/llms/AnthropicVertexAI.ts b/core/llm/llms/AnthropicVertexAI.ts deleted file mode 100644 index c910e8b85..000000000 --- a/core/llm/llms/AnthropicVertexAI.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider, -} from "../../index.js"; -import { stripImages } from "../images.js"; -import { streamSse } from "../stream.js"; -import VertexAI from "./VertexAI.js"; - -class AnthropicVertexAI extends VertexAI { - static providerName: ModelProvider = "anthropic-vertexai"; - static defaultOptions: Partial = { - region: "us-east5", - model: "claude-3-5-sonnet", - }; - - private _convertArgs(options: CompletionOptions) { - const finalOptions = { - anthropic_version: "vertex-2023-10-16", - top_k: options.topK, - top_p: options.topP, - temperature: options.temperature, - max_tokens: options.maxTokens ?? 2048, - stop_sequences: options.stop?.filter((x) => x.trim() !== ""), - stream: options.stream ?? true, - }; - - return finalOptions; - } - - private _convertMessages(msgs: ChatMessage[]): any[] { - const filteredmessages = msgs.filter((m) => m.role !== "system") - const lastTwoUserMsgIndices = filteredmessages - .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1).slice(-2); - - const messages = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching - const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); - - if (typeof message.content === "string") { - var chatMessage = { - ...message, - content: [{ - type: "text", - text: message.content, - ...(addCaching? { cache_control: { type: "ephemeral" } } : {}) - }] - }; - return chatMessage; - } - - return { - ...message, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {}) - }; - return newpart; - } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), - }; - }); - return messages; - } - - protected async *_streamComplete( - prompt: string, - options: CompletionOptions, - ): AsyncGenerator { - const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { - yield stripImages(update.content); - } - } - - protected async *_streamChat( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( - messages.filter((m) => m.role === "system")[0]?.content, - ); - const apiURL = new URL( - `publishers/anthropic/models/${options.model}:streamRawPredict`, - this.apiBase - ); - - const response = await this.fetch(apiURL, { - method: "POST", - headers: { - ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation - ? { "anthropic-beta": "prompt-caching-2024-07-31" } - : {}), - }, - body: JSON.stringify({ - ...this._convertArgs(options), - messages: this._convertMessages(messages), - system: shouldCacheSystemMessage - ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] - : systemMessage, - }), - }); - - if (options.stream === false) { - const data = await response.json(); - yield { role: "assistant", content: data.content[0].text }; - return; - } - - for await (const value of streamSse(response)) { - if (value.type == "message_start") console.log(value); - if (value.delta?.text) { - yield { role: "assistant", content: value.delta.text }; - } - } - } -} - -export default AnthropicVertexAI; diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts new file mode 100644 index 000000000..85fb19184 --- /dev/null +++ b/core/llm/llms/Asksage.ts @@ -0,0 +1,168 @@ +import { + ChatMessage, + CompletionOptions, + LLMOptions, + ModelProvider, +} from "../../index.js"; +import { BaseLLM } from "../index.js"; + +class Asksage extends BaseLLM { + static providerName: ModelProvider = "askSage"; + static defaultOptions: Partial = { + apiBase: "https://api.asksage.ai/server/", + model: "gpt-4o", + }; + + private static modelConversion: { [key: string]: string } = { + "gpt-4o": "gpt-4o", + "gpt-4o-mini": "gpt-4o-mini", + "gpt4-gov": "gpt4-gov", + "gpt-4o-gov": "gpt-4o-gov", + "gpt-3.5-turbo": "gpt35-16k", + "mistral-large-latest": "mistral-large", + "llama3-70b": "llma3", + "gemini-1.5-pro-latest": "google-gemini-pro", + "claude-3-5-sonnet-20240620": "claude-35-sonnet", + "claude-3-opus-20240229": "claude-3-opus", + "claude-3-sonnet-20240229": "claude-3-sonnet", + }; + + constructor(options: LLMOptions) { + super(options); + this.apiVersion = options.apiVersion ?? "v1.2.4"; + } + + protected _convertModelName(model: string): string { + return Asksage.modelConversion[model] ?? model; + } + + protected _convertMessage(message: ChatMessage) { + return { + user: message.role === "assistant" ? "gpt" : "me", + message: + typeof message.content === "string" + ? message.content + : message.content.map((part) => part.text).join(""), + }; + } + + protected _convertArgs(options: any, messages: ChatMessage[]) { + let formattedMessage: any; + if (messages.length === 1) { + formattedMessage = messages[0].content; + } else { + formattedMessage = messages.map(this._convertMessage); + } + + const args: any = { + message: formattedMessage, + persona: options.persona ?? "default", + dataset: options.dataset ?? "none", + limit_references: options.limitReferences ?? 0, + temperature: options.temperature ?? 0.0, + live: options.live ?? 0, + model: this._convertModelName(options.model), + system_prompt: options.systemPrompt ?? "You are an expert software developer. You give helpful and concise responses.", + tools: options.tools, + tool_choice: options.toolChoice, + }; + + Object.keys(args).forEach( + (key) => args[key] === undefined && delete args[key] + ); + + return args; + } + + protected _getHeaders() { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers["x-access-tokens"] = this.apiKey; + } + + return headers; + } + + protected _getEndpoint(endpoint: string) { + if (!this.apiBase) { + throw new Error( + "No API base URL provided. Please set the 'apiBase' option." + ); + } + + return new URL(endpoint, this.apiBase); + } + + protected async _complete( + prompt: string, + options: CompletionOptions + ): Promise { + if (typeof prompt !== "string" || prompt.trim() === "") { + throw new Error("Prompt must be a non-empty string."); + } + + const messages: ChatMessage[] = [{ role: "user", content: prompt }]; + + const args = this._convertArgs(options, messages); + + const response = await this.fetch(this._getEndpoint("query"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify(args), + }); + + if (!response.ok) { + throw new Error( + `API request failed with status ${response.status}: ${response.statusText}` + ); + } + + const data = await response.json(); + return data.message; + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions + ): AsyncGenerator { + const completion = await this._complete(prompt, options); + yield completion; + } + + protected async *_streamChat( + messages: ChatMessage[], + options: CompletionOptions + ): AsyncGenerator { + const args = this._convertArgs(options, messages); + + const response = await this.fetch(this._getEndpoint("query"), { + method: "POST", + headers: this._getHeaders(), + body: JSON.stringify(args), + }); + + if (!response.ok) { + throw new Error( + `API request failed with status ${response.status}: ${response.statusText}` + ); + } + + const data = await response.json(); + + const assistantMessage: ChatMessage = { + role: "assistant", + content: data.message, + }; + + yield assistantMessage; + } + + async listModels(): Promise { + return Object.keys(Asksage.modelConversion); + } +} + +export default Asksage; \ No newline at end of file diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index be7d1c18c..a8f119445 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -11,7 +11,7 @@ class Azure extends OpenAI { constructor(options: LLMOptions) { super(options); - this.engine = options.model; + this.deployment = options.deployment ?? options.model; } } diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 485b87015..c143fa412 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -111,7 +111,15 @@ class Bedrock extends BaseLLM { maxTokens: options.maxTokens, temperature: options.temperature, topP: options.topP, - stopSequences: options.stop?.filter((stop) => stop.trim() !== ""), + // TODO: The current approach selects the first 4 items from the list to comply with Bedrock's requirement + // of having at most 4 stop sequences, as per the AWS documentation: + // https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_InferenceConfiguration.html + // However, it might be better to implement a strategy that dynamically selects the most appropriate stop sequences + // based on the context. + // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. + // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), + // providing meaningful error messages to improve the user experience. + stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), }, }; } diff --git a/core/llm/llms/DeepInfra.ts b/core/llm/llms/DeepInfra.ts index 6b33a4bdc..592d28009 100644 --- a/core/llm/llms/DeepInfra.ts +++ b/core/llm/llms/DeepInfra.ts @@ -6,6 +6,7 @@ class DeepInfra extends OpenAI { static defaultOptions: Partial = { apiBase: "https://api.deepinfra.com/v1/openai/", }; + maxStopWords: number | undefined = 16; } export default DeepInfra; diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index e3dcdfef7..46d46046c 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -164,7 +164,7 @@ class FreeTrial extends BaseLLM { async listModels(): Promise { return [ "codestral-latest", - "claude-3-5-sonnet-20240620", + "claude-3-5-sonnet-latest", "llama3.1-405b", "llama3.1-70b", "gpt-4o", diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 4bfed0420..2e33968d5 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -15,10 +15,11 @@ class Gemini extends BaseLLM { static defaultOptions: Partial = { model: "gemini-pro", apiBase: "https://generativelanguage.googleapis.com/v1beta/", + maxStopWords: 5, }; // Function to convert completion options to Gemini format - private _convertArgs(options: CompletionOptions) { + public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI const finalOptions: any = {}; // Initialize an empty object // Map known options @@ -35,7 +36,9 @@ class Gemini extends BaseLLM { finalOptions.maxOutputTokens = options.maxTokens; } if (options.stop) { - finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== ""); + finalOptions.stopSequences = options.stop + .filter((x) => x.trim() !== "") + .slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords); } return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' @@ -53,7 +56,7 @@ class Gemini extends BaseLLM { } } - private removeSystemMessage(messages: ChatMessage[]) { + public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI const msgs = [...messages]; if (msgs[0]?.role === "system") { @@ -100,7 +103,7 @@ class Gemini extends BaseLLM { } } - private _continuePartToGeminiPart(part: MessagePart) { + continuePartToGeminiPart(part: MessagePart) { return part.type === "text" ? { text: part.text, @@ -139,13 +142,13 @@ class Gemini extends BaseLLM { parts: typeof msg.content === "string" ? [{ text: msg.content }] - : msg.content.map(this._continuePartToGeminiPart), + : msg.content.map(this.continuePartToGeminiPart), }; }) .filter((c) => c !== null); const body = { - ...this._convertArgs(options), + ...this.convertArgs(options), contents, // if this.systemMessage is defined, reformat it for Gemini API ...(this.systemMessage && diff --git a/core/llm/llms/GeminiVertexAI.ts b/core/llm/llms/GeminiVertexAI.ts deleted file mode 100644 index 2dc5e8cc1..000000000 --- a/core/llm/llms/GeminiVertexAI.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - MessagePart, - ModelProvider, -} from "../../index.js"; -import { stripImages } from "../images.js"; -import { streamResponse } from "../stream.js"; -import VertexAI from "./VertexAI.js"; - -class GeminiVertexAI extends VertexAI { - static providerName: ModelProvider = "gemini-vertexai"; - - static defaultOptions: Partial = { - model: "gemini-pro", - region: "us-central1", - }; - - // Function to convert completion options to Gemini format - private _convertArgs(options: CompletionOptions) { - const finalOptions: any = {}; // Initialize an empty object - - // Map known options - if (options.topK) { - finalOptions.topK = options.topK; - } - if (options.topP) { - finalOptions.topP = options.topP; - } - if (options.temperature !== undefined && options.temperature !== null) { - finalOptions.temperature = options.temperature; - } - if (options.maxTokens) { - finalOptions.maxOutputTokens = options.maxTokens; - } - if (options.stop) { - finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== ""); - } - - return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' - } - - protected async *_streamComplete( - prompt: string, - options: CompletionOptions, - ): AsyncGenerator { - for await (const message of this._streamChat( - [{ content: prompt, role: "user" }], - options, - )) { - yield stripImages(message.content); - } - } - - private removeSystemMessage(messages: ChatMessage[]) { - const msgs = [...messages]; - - if (msgs[0]?.role === "system") { - const sysMsg = msgs.shift()?.content; - // @ts-ignore - if (msgs[0]?.role === "user") { - msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; - } - } - - return msgs; - } - - protected async *_streamChat( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const isV1API = this.apiBase.includes("/v1/"); - - // Conditionally apply removeSystemMessage - const convertedMsgs = isV1API - ? this.removeSystemMessage(messages) - : messages; - - if (options.model.includes("gemini")) { - yield* this.streamChatGemini(convertedMsgs, options); - } else { - yield* this.streamChatBison(convertedMsgs, options); - } - } - - private _continuePartToGeminiPart(part: MessagePart) { - return part.type === "text" - ? { - text: part.text, - } - : { - inlineData: { - mimeType: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - } - - private async *streamChatGemini( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const apiURL = new URL( - `publishers/google/models/${options.model}:streamGenerateContent`, - this.apiBase, - ); - // This feels hacky to repeat code from above function but was the quickest - // way to ensure system message re-formatting isn't done if user has specified v1 - const isV1API = this.apiBase.includes("/v1/"); - - const contents = messages - .map((msg) => { - if (msg.role === "system" && !isV1API) { - return null; // Don't include system message in contents - } - return { - role: msg.role === "assistant" ? "model" : "user", - parts: - typeof msg.content === "string" - ? [{ text: msg.content }] - : msg.content.map(this._continuePartToGeminiPart), - }; - }) - .filter((c) => c !== null); - - const body = { - ...this._convertArgs(options), - contents, - // if this.systemMessage is defined, reformat it for Gemini API - ...(this.systemMessage && - !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, - }), - }; - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - }); - - let buffer = ""; - for await (const chunk of streamResponse(response)) { - buffer += chunk; - if (buffer.startsWith("[")) { - buffer = buffer.slice(1); - } - if (buffer.endsWith("]")) { - buffer = buffer.slice(0, -1); - } - if (buffer.startsWith(",")) { - buffer = buffer.slice(1); - } - - const parts = buffer.split("\n,"); - - let foundIncomplete = false; - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - let data; - try { - data = JSON.parse(part); - } catch (e) { - foundIncomplete = true; - continue; // yo! - } - if (data.error) { - throw new Error(data.error.message); - } - // Check for existence of each level before accessing the final 'text' property - if (data?.candidates?.[0]?.content?.parts?.[0]?.text) { - // Incrementally stream the content to make it smoother - const content = data.candidates[0].content.parts[0].text; - const words = content.split(/(\s+)/); - const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1); - while (words.length > 0) { - const wordsToYield = Math.min(3, words.length); - yield { - role: "assistant", - content: words.splice(0, wordsToYield).join(""), - }; - await delay(delaySeconds); - } - } else { - // Handle the case where the expected data structure is not found - console.warn("Unexpected response format:", data); - } - } - if (foundIncomplete) { - buffer = parts[parts.length - 1]; - } else { - buffer = ""; - } - } - } - - private async *streamChatBison( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const instances = messages.map((message) => ({ prompt: message.content })); - - const apiURL = new URL( - `publishers/google/models/${options.model}:predict`, - this.apiBase, - ); - const body = { - instances, - parameters: { - temperature: options.temperature, - maxOutputTokens: options.maxTokens, - topP: options.topP, - topK: options.topK, - stopSequences: options.stop, - presencePenalty: options.presencePenalty, - frequencyPenalty: options.frequencyPenalty, - }, - }; - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - }); - const data = await response.json(); - yield { role: "assistant", content: data.predictions[0].content }; - } -} - -async function delay(seconds: number) { - return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); -} - -export default GeminiVertexAI; diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts index bc05263c9..b69e2c020 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -18,6 +18,10 @@ class Groq extends OpenAI { "llama3.1-8b": "llama-3.1-8b-instant", "llama3.1-70b": "llama-3.1-70b-versatile", "llama3.1-405b": "llama-3.1-405b-reasoning", + "llama3.2-1b": "llama-3.2-1b-preview", + "llama3.2-3b": "llama-3.2-3b-preview", + "llama3.2-11b": "llama-3.2-11b-vision-preview", + "llama3.2-90b": "llama-3.2-90b-vision-preview", }; protected _convertModelName(model: string): string { return Groq.modelConversion[model] ?? model; diff --git a/core/llm/llms/MistralVertexAI.ts b/core/llm/llms/MistralVertexAI.ts deleted file mode 100644 index af0fc6272..000000000 --- a/core/llm/llms/MistralVertexAI.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { - ChatMessage, - CompletionOptions, - LLMOptions, - ModelProvider -} from "../../index.js"; -import { stripImages } from "../images.js"; -import { streamSse } from "../stream.js"; -import { gptEditPrompt } from "../templates/edit.js"; -import VertexAI from "./VertexAI.js"; - -class MistralVertexAI extends VertexAI { - static providerName: ModelProvider = "mistral-vertexai"; - static defaultOptions: Partial = { - region: "us-central1", - model: "codestral-latest", - promptTemplates: { - edit: gptEditPrompt, - }, - }; - - protected async *_streamComplete( - prompt: string, - options: CompletionOptions, - ): AsyncGenerator { - for await (const chunk of this._streamChat( - [{ role: "user", content: prompt }], - options, - )) { - yield stripImages(chunk.content); - } - } - - protected async *_streamChat( - messages: ChatMessage[], - options: CompletionOptions, - ): AsyncGenerator { - const apiBase = this.apiBase!; - const apiURL = new URL( - `publishers/mistralai/models/${options.model}:streamRawPredict`, - apiBase, - ); - - const lastMessage = messages[messages.length - 1]; - if (lastMessage?.role === "assistant") { - (lastMessage as any).prefix = true; - } - - const body = { - model: options.model, - temperature: options.temperature, - top_p: options.topP, - max_tokens: options.maxTokens, - stream: options.stream ?? true, - stop: options.stop, - messages, - }; - - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - }); - - for await (const chunk of streamSse(response)) { - yield chunk.choices[0].delta; - } - } - - protected async *_streamFim( - prefix: string, - suffix: string, - options: CompletionOptions, - ): AsyncGenerator { - const apiBase = this.apiBase!; - const apiURL = new URL( - `publishers/mistralai/models/${options.model}:streamRawPredict`, - apiBase, - ); - - const body = { - model: options.model, - max_tokens: options.maxTokens, - temperature: options.temperature, - top_p: options.topP, - stream: options.stream ?? true, - stop: options.stop, - prompt: prefix, - suffix, - }; - - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - }); - - for await (const chunk of streamSse(response)) { - yield chunk.choices[0].delta.content; - } - } - - supportsFim(): boolean { - return true; - } -} - -export default MistralVertexAI; diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index d5e2ef59c..e6097a60d 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -2,24 +2,26 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; import { BaseLLM } from "../index.js"; class Mock extends BaseLLM { - static Completion = "Test Completion"; + public completion: string = "Test Completion"; static providerName: ModelProvider = "mock"; protected async *_streamComplete( prompt: string, options: CompletionOptions, ): AsyncGenerator { - yield Mock.Completion; + yield this.completion; } protected async *_streamChat( messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - yield { - role: "assistant", - content: Mock.Completion, - }; + for (const char of this.completion) { + yield { + role: "assistant", + content: char, + }; + } } } diff --git a/core/llm/llms/Nebius.ts b/core/llm/llms/Nebius.ts new file mode 100644 index 000000000..4e2b56721 --- /dev/null +++ b/core/llm/llms/Nebius.ts @@ -0,0 +1,12 @@ +import { LLMOptions, ModelProvider } from "../.."; +import OpenAI from "./OpenAI"; + +class Nebius extends OpenAI { + static providerName: ModelProvider = "nvidia"; + static defaultOptions: Partial = { + apiBase: "https://api.studio.nebius.ai/v1/", + useLegacyCompletionsEndpoint: false, + }; +} + +export default Nebius; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 75e973219..91d7976b7 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -8,6 +8,59 @@ import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; +interface OllamaChatMessage extends ChatMessage { + images?: string[]; +} + +// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter +interface ModelFileParams { + mirostat?: number; + mirostat_eta?: number; + mirostat_tau?: number; + num_ctx?: number; + repeat_last_n?: number; + repeat_penalty?: number; + temperature?: number; + seed?: number; + stop?: string | string[]; + tfs_z?: number; + num_predict?: number; + top_k?: number; + top_p?: number; + min_p?: number; + // deprecated? + num_thread?: number; + num_gqa?: number; + num_gpu?: number; +} + +// See https://github.com/ollama/ollama/blob/main/docs/api.md +interface BaseOptions { + model: string; // the model name + options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature + format?: "json"; // the format to return a response in. Currently, the only accepted value is json + stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects + keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m) +} + +interface GenerateOptions extends BaseOptions { + prompt: string; // the prompt to generate a response for + suffix?: string; // the text after the model response + images?: string[]; // a list of base64-encoded images (for multimodal models such as llava) + system?: string; // system message to (overrides what is defined in the Modelfile) + template?: string; // the prompt template to use (overrides what is defined in the Modelfile) + context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory + raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API +} + +interface ChatOptions extends BaseOptions { + messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory + // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false + // And correspondingly, tool calls in OllamaChatMessage +} + + + class Ollama extends BaseLLM { static providerName: ModelProvider = "ollama"; static defaultOptions: Partial = { @@ -63,7 +116,7 @@ class Ollama extends BaseLLM { this.completionOptions.stop.push(JSON.parse(value)); } catch (e) { console.warn( - 'Error parsing stop parameter value "{value}: ${e}', + `Error parsing stop parameter value "{value}: ${e}`, ); } break; @@ -101,6 +154,10 @@ class Ollama extends BaseLLM { "llama3.1-8b": "llama3.1:8b", "llama3.1-70b": "llama3.1:70b", "llama3.1-405b": "llama3.1:405b", + "llama3.2-1b": "llama3.2:1b", + "llama3.2-3b": "llama3.2:3b", + "llama3.2-11b": "llama3.2:11b", + "llama3.2-90b": "llama3.2:90b", "phi-2": "phi:2.7b", "phind-codellama-34b": "phind-codellama:34b-v2", "wizardcoder-7b": "wizardcoder:7b-python", @@ -124,49 +181,72 @@ class Ollama extends BaseLLM { ); } - private _convertMessage(message: ChatMessage) { + private _getModelFileParams(options: CompletionOptions): ModelFileParams { + return { + temperature: options.temperature, + top_p: options.topP, + top_k: options.topK, + num_predict: options.maxTokens, + stop: options.stop, + num_ctx: this.contextLength, + mirostat: options.mirostat, + num_thread: options.numThreads, + min_p: options.minP, + }; + } + + private _convertMessage( + message: ChatMessage + ) { if (typeof message.content === "string") { return message; } + const images: string[] = []; + message.content.forEach((part) => { + if (part.type === "imageUrl" && part.imageUrl) { + const image = part.imageUrl?.url.split(",").at(-1); + if (image) { + images.push(image); + } + } + }); return { role: message.role, content: stripImages(message.content), - images: message.content - .filter((part) => part.type === "imageUrl") - .map((part) => part.imageUrl?.url.split(",").at(-1)), + images }; } - private _convertArgs( + private _getChatOptions( options: CompletionOptions, - prompt: string | ChatMessage[], - suffix?: string, - ) { - const finalOptions: any = { + messages: ChatMessage[] + ): ChatOptions { + return { model: this._getModel(), - raw: true, + messages: messages.map(this._convertMessage), + options: this._getModelFileParams(options), keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes - suffix, - options: { - temperature: options.temperature, - top_p: options.topP, - top_k: options.topK, - num_predict: options.maxTokens, - stop: options.stop, - num_ctx: this.contextLength, - mirostat: options.mirostat, - num_thread: options.numThreads, - }, + stream: options.stream, + // format: options.format, // Not currently in base completion options }; + } - if (typeof prompt === "string") { - finalOptions.prompt = prompt; - } else { - finalOptions.messages = prompt.map(this._convertMessage); - } - - return finalOptions; + private _getGenerateOptions( + options: CompletionOptions, + prompt: string, + suffix?: string + ): GenerateOptions { + return { + model: this._getModel(), + prompt, + suffix, + raw: options.raw, + options: this._getModelFileParams(options), + keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes + stream: options.stream, + // Not supported yet: context, images, system, template, format + }; } private getEndpoint(endpoint: string): URL { @@ -188,7 +268,7 @@ class Ollama extends BaseLLM { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, - body: JSON.stringify(this._convertArgs(options, prompt)), + body: JSON.stringify(this._getGenerateOptions(options, prompt)), }); let buffer = ""; @@ -227,7 +307,7 @@ class Ollama extends BaseLLM { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, - body: JSON.stringify(this._convertArgs(options, messages)), + body: JSON.stringify(this._getChatOptions(options, messages)), }); let buffer = ""; @@ -274,7 +354,7 @@ class Ollama extends BaseLLM { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, - body: JSON.stringify(this._convertArgs(options, prefix, suffix)), + body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), }); let buffer = ""; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 9366a7954..168e0afff 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -37,13 +37,13 @@ const CHAT_ONLY_MODELS = [ "gpt-4-0125-preview", "gpt-4-1106-preview", "gpt-4o-mini", + "o1-preview", + "o1-mini", ]; class OpenAI extends BaseLLM { public useLegacyCompletionsEndpoint: boolean | undefined = undefined; - maxStopWords: number | undefined = undefined; - constructor(options: LLMOptions) { super(options); this.useLegacyCompletionsEndpoint = options.useLegacyCompletionsEndpoint; @@ -95,7 +95,14 @@ class OpenAI extends BaseLLM { ); } - protected _convertArgs(options: any, messages: ChatMessage[]) { + private supportsPrediction(model: string): boolean { + return [ + "gpt-4o-mini", + "gpt-4o" + ].includes(model); + } + + protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { const url = new URL(this.apiBase!); const finalOptions: any = { messages: messages.map(this._convertMessage), @@ -113,9 +120,9 @@ class OpenAI extends BaseLLM { : 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" + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, }; @@ -135,6 +142,18 @@ class OpenAI extends BaseLLM { ); } + if (options.prediction && this.supportsPrediction(options.model)) { + if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + finalOptions.presence_penalty = undefined; + } + if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + finalOptions.frequency_penalty = undefined; + } + finalOptions.max_completion_tokens = undefined; + + finalOptions.prediction = options.prediction; + } + return finalOptions; } @@ -166,7 +185,7 @@ class OpenAI extends BaseLLM { ) { if (this.apiType === "azure") { return new URL( - `openai/deployments/${this.engine}/${endpoint}?api-version=${this.apiVersion}`, + `openai/deployments/${this.deployment}/${endpoint}?api-version=${this.apiVersion}`, this.apiBase, ); } diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index 03b9a5b22..d5e9039de 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -59,10 +59,10 @@ class SageMaker extends BaseLLM { const data = JSON.parse(line.replace(/^data:/, '')); let text = undefined; if ("choices" in data) { - if ("delta" in data.choices[0]){ + if ("delta" in data.choices[0]) { text = data.choices[0].delta.content; } - else{ + else { text = data.choices[0].text; } } @@ -110,10 +110,10 @@ class SageMaker extends BaseLLM { const data = JSON.parse(line.replace(/^data:/, '')); let text = undefined; if ("choices" in data) { - if ("delta" in data.choices[0]){ + if ("delta" in data.choices[0]) { text = data.choices[0].delta.content; } - else{ + else { text = data.choices[0].text; } } diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts index 2b409dcde..39a216681 100644 --- a/core/llm/llms/SambaNova.ts +++ b/core/llm/llms/SambaNova.ts @@ -12,6 +12,8 @@ class SambaNova extends OpenAI { "llama3.1-8b": "Meta-Llama-3.1-8B-Instruct", "llama3.1-70b": "Meta-Llama-3.1-70B-Instruct", "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct", + "llama3.1-1b": "Meta-Llama-3.2-1B-Instruct", + "llama3.1-3b": "Meta-Llama-3.2-3B-Instruct", }; protected _convertModelName(model: string) { diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index eaa144277..862226394 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -22,6 +22,9 @@ class Together extends OpenAI { "llama3.1-8b": "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", "llama3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", "llama3.1-405b": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo", + "llama3.2-3b": "meta-llama/Llama-3.2-3B-Instruct-Turbo", + "llama3.2-11b": "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo", + "llama3.2-90b": "meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo", "llama2-7b": "togethercomputer/llama-2-7b-chat", "llama2-13b": "togethercomputer/llama-2-13b-chat", "llama2-70b": "togethercomputer/llama-2-70b-chat", diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 772b30ea7..e3435b6ae 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,9 +1,24 @@ import { GoogleAuth } from "google-auth-library"; -import { LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; +import { stripImages } from "../images.js"; +import { streamSse } from "../stream.js"; +import { + ChatMessage, + CompletionOptions, + LLMOptions, + MessagePart, + ModelProvider, +} from "../../index.js"; +import { streamResponse } from "../stream.js"; +import Anthropic from "./Anthropic.js"; +import Gemini from "./Gemini.js"; -abstract class VertexAI extends BaseLLM { +class VertexAI extends BaseLLM { + static providerName: ModelProvider = "vertexai"; declare apiBase: string; + declare vertexProvider: string; + declare anthropicInstance: Anthropic; + declare geminiInstance: Gemini; private clientPromise = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform", @@ -22,6 +37,17 @@ abstract class VertexAI extends BaseLLM { constructor(_options: LLMOptions) { super(_options); this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); + this.vertexProvider = + _options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral") + ? "mistral" + : _options.model.includes("claude") + ? "anthropic" + : _options.model.includes("gemini") + ? "gemini" : + "unknown"; + this.anthropicInstance = new Anthropic(_options); + this.geminiInstance = new Gemini(_options) + } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -41,6 +67,373 @@ abstract class VertexAI extends BaseLLM { }, }); } + + // Anthropic functions + private _anthropicConvertArgs(options: CompletionOptions) { + const convertedArgs = this.anthropicInstance.convertArgs(options); + + // Remove the `model` property and add `anthropic_version` + const { model, ...finalOptions } = convertedArgs; + return { + ...finalOptions, + anthropic_version: "vertex-2023-10-16", + }; + } + + + protected async *StreamChatAnthropic( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const systemMessage: string = stripImages( + messages.filter((m) => m.role === "system")[0]?.content, + ); + const apiURL = new URL( + `publishers/anthropic/models/${options.model}:streamRawPredict`, + this.apiBase + ); + + const response = await this.fetch(apiURL, { + method: "POST", + headers: { + ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation + ? { "anthropic-beta": "prompt-caching-2024-07-31" } + : {}), + }, + body: JSON.stringify({ + ...this._anthropicConvertArgs(options), + messages: this.anthropicInstance.convertMessages(messages), + system: shouldCacheSystemMessage + ? [ + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] + : systemMessage, + }), + }); + + if (options.stream === false) { + const data = await response.json(); + yield { role: "assistant", content: data.content[0].text }; + return; + } + + for await (const value of streamSse(response)) { + if (value.type == "message_start") console.log(value); + if (value.delta?.text) { + yield { role: "assistant", content: value.delta.text }; + } + } + } + + + //Gemini + + private async *streamChatGemini( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const apiURL = new URL( + `publishers/google/models/${options.model}:streamGenerateContent`, + this.apiBase, + ); + // This feels hacky to repeat code from above function but was the quickest + // way to ensure system message re-formatting isn't done if user has specified v1 + const isV1API = this.apiBase.includes("/v1/"); + + const contents = messages + .map((msg) => { + if (msg.role === "system" && !isV1API) { + return null; // Don't include system message in contents + } + return { + role: msg.role === "assistant" ? "model" : "user", + parts: + typeof msg.content === "string" + ? [{ text: msg.content }] + : msg.content.map(this.geminiInstance.continuePartToGeminiPart), + }; + }) + .filter((c) => c !== null); + + const body = { + ...this.geminiInstance.convertArgs(options), + contents, + // if this.systemMessage is defined, reformat it for Gemini API + ...(this.systemMessage && + !isV1API && { + systemInstruction: { parts: [{ text: this.systemMessage }] }, + }), + }; + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + }); + + let buffer = ""; + for await (const chunk of streamResponse(response)) { + buffer += chunk; + if (buffer.startsWith("[")) { + buffer = buffer.slice(1); + } + if (buffer.endsWith("]")) { + buffer = buffer.slice(0, -1); + } + if (buffer.startsWith(",")) { + buffer = buffer.slice(1); + } + + const parts = buffer.split("\n,"); + + let foundIncomplete = false; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + let data; + try { + data = JSON.parse(part); + } catch (e) { + foundIncomplete = true; + continue; // yo! + } + if (data.error) { + throw new Error(data.error.message); + } + // Check for existence of each level before accessing the final 'text' property + if (data?.candidates?.[0]?.content?.parts?.[0]?.text) { + // Incrementally stream the content to make it smoother + const content = data.candidates[0].content.parts[0].text; + const words = content.split(/(\s+)/); + const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1); + while (words.length > 0) { + const wordsToYield = Math.min(3, words.length); + yield { + role: "assistant", + content: words.splice(0, wordsToYield).join(""), + }; + await delay(delaySeconds); + } + } else { + // Handle the case where the expected data structure is not found + if (data?.candidates?.[0]?.finishReason !== "STOP") { + console.warn("Unexpected response format:", data); + } + } + } + if (foundIncomplete) { + buffer = parts[parts.length - 1]; + } else { + buffer = ""; + } + } + } + + private async *streamChatBison( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const instances = messages.map((message) => ({ prompt: message.content })); + + const apiURL = new URL( + `publishers/google/models/${options.model}:predict`, + this.apiBase, + ); + const body = { + instances, + parameters: { + temperature: options.temperature, + maxOutputTokens: options.maxTokens, + topP: options.topP, + topK: options.topK, + stopSequences: options.stop, + presencePenalty: options.presencePenalty, + frequencyPenalty: options.frequencyPenalty, + }, + }; + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + }); + const data = await response.json(); + yield { role: "assistant", content: data.predictions[0].content }; + } + + //Mistral + + + protected async *StreamChatMistral( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const apiBase = this.apiBase!; + const apiURL = new URL( + `publishers/mistralai/models/${options.model}:streamRawPredict`, + apiBase, + ); + + const lastMessage = messages[messages.length - 1]; + if (lastMessage?.role === "assistant") { + (lastMessage as any).prefix = true; + } + + const body = { + model: options.model, + temperature: options.temperature, + top_p: options.topP, + max_tokens: options.maxTokens, + stream: options.stream ?? true, + stop: options.stop, + messages, + }; + + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + }); + + for await (const chunk of streamSse(response)) { + if (chunk.choices?.[0]) { + // At the end vertexai will return a empty chunk. + yield chunk.choices[0].delta; + } + } + } + + protected async *StreamFimMistral( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + const apiBase = this.apiBase!; + const apiURL = new URL( + `publishers/mistralai/models/${options.model}:streamRawPredict`, + apiBase, + ); + + const body = { + model: options.model, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + stream: options.stream ?? true, + stop: options.stop, + prompt: prefix, + suffix, + }; + + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + }); + + for await (const chunk of streamSse(response)) { + yield chunk.choices[0].delta.content; + } + } + + + + //gecko + protected async *streamFimGecko( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + instances: [ + { + prefix: prefix, + suffix: suffix + } + ], + parameters: { + temperature: options.temperature, + maxOutputTokens: Math.min(options.maxTokens ?? 64, 64), + stopSequences: options.stop?.splice(0, 5), + frequencyPenalty: options.frequencyPenalty, + presencePenalty: options.frequencyPenalty, + } + + }), + }); + // Streaming is not supported by code-gecko + // TODO: convert to non-streaming fim method when one exist in continue. + yield (await resp.json()).predictions[0].content; + } + + //Manager functions + + protected async *_streamChat( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + const isV1API = this.apiBase.includes("/v1/"); + + // Conditionally apply removeSystemMessage + const convertedMsgs = isV1API + ? this.geminiInstance.removeSystemMessage(messages) + : messages; + if (this.vertexProvider == "gemini") { + yield* this.streamChatGemini(convertedMsgs, options); + } else if (this.vertexProvider == "mistral") { + yield* this.StreamChatMistral(messages, options); + } else if (this.vertexProvider == "anthropic") { + yield* this.StreamChatAnthropic(messages, options) + } else { + if (options.model.includes("bison")) { + yield* this.streamChatBison(convertedMsgs, options); + } + } + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions, + ): AsyncGenerator { + for await (const message of this._streamChat( + [{ content: prompt, role: "user" }], + options, + )) { + yield stripImages(message.content); + } + } + + protected async *_streamFim( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + + + + if (this.model === "code-gecko") { + yield* this.streamFimGecko(prefix, suffix, options); + } else if (this.model.includes("codestral")) { + yield* this.StreamFimMistral(prefix, suffix, options); + } else { + throw new Error(`Unsupported model: ${this.model}`); + } + + + } + + supportsFim(): boolean { + return ["code-gecko", "codestral-latest"].includes(this.model); + } + + } +async function delay(seconds: number) { + return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); +} + + + export default VertexAI; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index d9b61a3f1..94a7b66fa 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -7,27 +7,26 @@ import { import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; -const watsonxConfig = { - accessToken: { - expiration: 0, - token: "", - }, -}; + +let watsonxToken = { + expiration: 0, + token: "" +} + class WatsonX extends BaseLLM { - maxStopWords: number | undefined = undefined; constructor(options: LLMOptions) { super(options); } + async getBearerToken(): Promise<{ token: string; expiration: number }> { if ( - this.watsonxFullUrl?.includes("cloud.ibm.com") || - this.watsonxUrl?.includes("cloud.ibm.com") + this.apiBase?.includes("cloud.ibm.com") ) { // watsonx SaaS const wxToken = await ( await fetch( - `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxCreds}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, + `https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, { method: "POST", headers: { @@ -43,17 +42,17 @@ class WatsonX extends BaseLLM { }; } else { // watsonx Software - if (!this.watsonxCreds?.includes(":")) { + if (!this.apiKey?.includes(":")) { // Using ZenApiKey auth return { - token: this.watsonxCreds ?? "", + token: this.apiKey ?? "", expiration: -1, }; } else { // Using username/password auth - const userPass = this.watsonxCreds?.split(":"); + const userPass = this.apiKey?.split(":"); const wxToken = await ( - await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, { + await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, { method: "POST", headers: { "Content-Type": "application/json", @@ -66,7 +65,7 @@ class WatsonX extends BaseLLM { }) ).json(); const wxTokenExpiry = await ( - await fetch(`${this.watsonxUrl}/usermgmt/v1/user/tokenExpiry`, { + await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, { method: "GET", headers: { Accept: "application/json", @@ -84,8 +83,9 @@ class WatsonX extends BaseLLM { getWatsonxEndpoint(): string { return ( - this.watsonxFullUrl ?? - `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}` + this.deploymentId ? + `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`: + `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}` ); } @@ -133,8 +133,8 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxConfig.accessToken.token}`, + Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, }; } @@ -171,24 +171,22 @@ class WatsonX extends BaseLLM { ): AsyncGenerator { var now = new Date().getTime() / 1000; if ( - watsonxConfig.accessToken === undefined || - now > watsonxConfig.accessToken.expiration || - watsonxConfig.accessToken.token === undefined + watsonxToken === undefined || + now > watsonxToken.expiration || + watsonxToken.token === undefined ) { - watsonxConfig.accessToken = await this.getBearerToken(); + watsonxToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60 + `Reusing token (expires in ${(watsonxToken.expiration - now) / 60 } mins)`, ); } - if (watsonxConfig.accessToken.token === undefined) { + if (watsonxToken.token === undefined) { throw new Error("Something went wrong. Check your credentials, please."); } - - const stopToken = - this.watsonxStopToken ?? - (options.model?.includes("granite") ? "<|im_end|>" : undefined); + const stopSequences = + options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []); const url = this.getWatsonxEndpoint(); const headers = this._getHeaders(); @@ -196,24 +194,25 @@ class WatsonX extends BaseLLM { decoding_method: "greedy", max_new_tokens: options.maxTokens ?? 1024, min_new_tokens: 1, - stop_sequences: stopToken ? [stopToken] : [], + stop_sequences: stopSequences, include_stop_sequence: false, - repetition_penalty: 1, + truncate_input_tokens: this.contextLength - (options.maxTokens ?? 1024), + repetition_penalty: options.frequencyPenalty || 1, }; if (!!options.temperature) { parameters.decoding_method = "sample"; parameters.temperature = options.temperature; parameters.top_p = options.topP || 1.0; - parameters.top_k = options.topK; + parameters.top_k = options.topK || 100; } const payload: any = { input: messages[messages.length - 1].content, parameters: parameters, }; - if (!this.watsonxFullUrl) { + if (!this.deploymentId) { payload.model_id = options.model; - payload.project_id = this.watsonxProjectId; + payload.project_id = this.projectId; } var response = await this.fetch(url, { @@ -246,7 +245,8 @@ class WatsonX extends BaseLLM { generatedChunk += result.generated_text || ""; }); } catch (e) { - console.error(`Error parsing JSON string: ${dataStr}`, e); + // parsing error is expected with streaming response + // console.error(`Error parsing JSON string: ${dataStr}`, e); } } }); diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index b504aa900..64882b09b 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -8,7 +8,6 @@ import { import { renderTemplatedString } from "../../promptFiles/renderTemplatedString"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; -import AnthropicVertexAI from "./AnthropicVertexAI"; import Azure from "./Azure"; import Bedrock from "./Bedrock"; import BedrockImport from "./BedrockImport"; @@ -21,7 +20,6 @@ import Fireworks from "./Fireworks"; import Flowise from "./Flowise"; import FreeTrial from "./FreeTrial"; import Gemini from "./Gemini"; -import GeminiVertexAI from "./GeminiVertexAI"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; import HuggingFaceTGI from "./HuggingFaceTGI"; @@ -30,9 +28,9 @@ import LMStudio from "./LMStudio"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; import Mistral from "./Mistral"; -import MistralVertexAI from "./MistralVertexAI"; import Mock from "./Mock"; import Msty from "./Msty"; +import Nebius from "./Nebius"; import Nvidia from "./Nvidia"; import Ollama from "./Ollama"; import OpenAI from "./OpenAI"; @@ -45,14 +43,15 @@ import Together from "./Together"; import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; import ContinueProxy from "./stubs/ContinueProxy"; +import VertexAI from "./VertexAI"; +import Asksage from "./Asksage"; +import xAI from "./xAI"; const LLMs = [ Anthropic, - AnthropicVertexAI, Cohere, FreeTrial, Gemini, - GeminiVertexAI, Llamafile, Ollama, Replicate, @@ -65,7 +64,6 @@ const LLMs = [ OpenAI, LMStudio, Mistral, - MistralVertexAI, Bedrock, BedrockImport, SageMaker, @@ -85,6 +83,10 @@ const LLMs = [ SambaNova, Mock, Cerebras, + Asksage, + Nebius, + VertexAI, + xAI ]; export async function llmFromDescription( diff --git a/core/llm/llms/xAI.ts b/core/llm/llms/xAI.ts new file mode 100644 index 000000000..aa33ee70d --- /dev/null +++ b/core/llm/llms/xAI.ts @@ -0,0 +1,20 @@ +import { LLMOptions, ModelProvider } from "../../index.js"; + +import OpenAI from "./OpenAI.js"; + +class xAI extends OpenAI { + static providerName: ModelProvider = "xAI"; + static defaultOptions: Partial = { + apiBase: "https://api.x.ai/v1/", + }; + + private static MODEL_IDS: { [name: string]: string } = { + "grok-beta": "grok-beta", // Future names might not line up + }; + + protected _convertModelName(model: string) { + return xAI.MODEL_IDS[model] || this.model; + } +} + +export default xAI; diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index 17fae23cb..9d26620f4 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -274,12 +274,22 @@ const gemmaTemplateMessage = templateFactory( "\n", ); +const graniteTemplateMessages = templateFactory( + (msg) => (!!msg ? `\n\nSystem:\n ${msg.content}\n\n` : ""), + "Question:\n", + "Answer:\n", + "\n\n", + "", + "", +); + export { anthropicTemplateMessages, chatmlTemplateMessages, codeLlama70bTemplateMessages, deepseekTemplateMessages, gemmaTemplateMessage, + graniteTemplateMessages, llama2TemplateMessages, llama3TemplateMessages, llavaTemplateMessages, diff --git a/core/package-lock.json b/core/package-lock.json index 58eec1b51..f218b1904 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -17,7 +17,6 @@ "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", - "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -65,6 +64,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" @@ -89,7 +89,6 @@ "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", @@ -4969,7 +4968,8 @@ "node_modules/@types/json5": { "version": "0.0.29", "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", - "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==" + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "peer": true }, "node_modules/@types/long": { "version": "4.0.2", @@ -5224,6 +5224,7 @@ "version": "7.10.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.10.0.tgz", "integrity": "sha512-2EjZMA0LUW5V5tGQiaa2Gys+nKdfrn2xiTIBLR4fxmPmVSvgPcKNW+AE/ln9k0A4zDUti0J/GZXMDupQoI+e1w==", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "7.10.0", "@typescript-eslint/types": "7.10.0", @@ -5645,6 +5646,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.1.tgz", "integrity": "sha512-ahC5W1xgou+KTXix4sAO8Ki12Q+jf4i0+tmk3sC+zgcynshkHxzpXdImBehiUYKKKDwvfFiJl1tZt6ewscS1Mg==", + "peer": true, "dependencies": { "call-bind": "^1.0.5", "is-array-buffer": "^3.0.4" @@ -5660,6 +5662,7 @@ "version": "3.1.8", "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.8.tgz", "integrity": "sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -5692,6 +5695,7 @@ "version": "1.2.5", "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz", "integrity": "sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -5711,6 +5715,7 @@ "version": "1.3.2", "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz", "integrity": "sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.2.0", @@ -5728,6 +5733,7 @@ "version": "1.3.2", "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.2.tgz", "integrity": "sha512-Ewyx0c9PmpcsByhSW4r+9zDU7sGjFc86qf/kKtuSCRdhfbk0SNLLkaT5qvcHnRGgc5NP/ly/y+qkXkqONX54CQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.2.0", @@ -5745,6 +5751,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.3.tgz", "integrity": "sha512-bMxMKAjg13EBSVscxTaYA4mRc5t1UAXa2kXiGTNfZ079HIWXEkKmkgFrh/nJqamaLSrXO5H4WFFkPEaLJWbs3A==", + "peer": true, "dependencies": { "array-buffer-byte-length": "^1.0.1", "call-bind": "^1.0.5", @@ -5806,6 +5813,7 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "peer": true, "dependencies": { "possible-typed-array-names": "^1.0.0" }, @@ -6901,6 +6909,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz", "integrity": "sha512-0lht7OugA5x3iJLOWFhWK/5ehONdprk0ISXqVFn/NFrDu+cuc8iADFrGQz5BnRK7LLU3JmkbXSxaqX+/mXYtUA==", + "peer": true, "dependencies": { "call-bind": "^1.0.6", "es-errors": "^1.3.0", @@ -6917,6 +6926,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.1.tgz", "integrity": "sha512-4J7wRJD3ABAzr8wP+OcIcqq2dlUKp4DVflx++hs5h5ZKydWMI6/D/fAot+yh6g2tHh8fLFTvNOaVN357NvSrOQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "es-errors": "^1.3.0", @@ -6933,6 +6943,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.0.tgz", "integrity": "sha512-t/Ygsytq+R995EJ5PZlD4Cu56sWa8InXySaViRzw9apusqsOO2bQP+SbYzAhR0pFKoB+43lYy8rWban9JSuXnA==", + "peer": true, "dependencies": { "call-bind": "^1.0.6", "es-errors": "^1.3.0", @@ -7396,6 +7407,7 @@ "version": "1.23.3", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz", "integrity": "sha512-e+HfNH61Bj1X9/jLc5v1owaLYuHdeHHSQlkhCBiTK8rBvKaULl/beGMxwrMXjpYrv4pz22BlY570vVePA2ho4A==", + "peer": true, "dependencies": { "array-buffer-byte-length": "^1.0.1", "arraybuffer.prototype.slice": "^1.0.3", @@ -7485,6 +7497,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz", "integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==", + "peer": true, "dependencies": { "get-intrinsic": "^1.2.4", "has-tostringtag": "^1.0.2", @@ -7498,6 +7511,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz", "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==", + "peer": true, "dependencies": { "hasown": "^2.0.0" } @@ -7506,6 +7520,7 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "peer": true, "dependencies": { "is-callable": "^1.1.4", "is-date-object": "^1.0.1", @@ -7690,6 +7705,7 @@ "version": "0.3.9", "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "peer": true, "dependencies": { "debug": "^3.2.7", "is-core-module": "^2.13.0", @@ -7700,6 +7716,7 @@ "version": "3.2.7", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "peer": true, "dependencies": { "ms": "^2.1.1" } @@ -7708,6 +7725,7 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.8.1.tgz", "integrity": "sha512-rXDXR3h7cs7dy9RNpUlQf80nX31XWJEyGq1tRMo+6GsO5VmTe4UTwtmonAD4ZkAsrfMVDA2wlGJ3790Ys+D49Q==", + "peer": true, "dependencies": { "debug": "^3.2.7" }, @@ -7724,6 +7742,7 @@ "version": "3.2.7", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "peer": true, "dependencies": { "ms": "^2.1.1" } @@ -7732,6 +7751,7 @@ "version": "2.29.1", "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.29.1.tgz", "integrity": "sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==", + "peer": true, "dependencies": { "array-includes": "^3.1.7", "array.prototype.findlastindex": "^1.2.3", @@ -7762,6 +7782,7 @@ "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -7771,6 +7792,7 @@ "version": "3.2.7", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "peer": true, "dependencies": { "ms": "^2.1.1" } @@ -7779,6 +7801,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "peer": true, "dependencies": { "esutils": "^2.0.2" }, @@ -7790,6 +7813,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -7801,6 +7825,7 @@ "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "peer": true, "bin": { "semver": "bin/semver.js" } @@ -8258,6 +8283,7 @@ "version": "0.3.3", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "peer": true, "dependencies": { "is-callable": "^1.1.3" } @@ -8413,6 +8439,7 @@ "version": "1.1.6", "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz", "integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.2.0", @@ -8430,6 +8457,7 @@ "version": "1.2.3", "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -8593,6 +8621,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.2.tgz", "integrity": "sha512-g0QYk1dZBxGwk+Ngc+ltRH2IBp2f7zBkBMBJZCDerh6EhlhSR6+9irMCuT/09zD6qkarHUSn529sK/yL4S27mg==", + "peer": true, "dependencies": { "call-bind": "^1.0.5", "es-errors": "^1.3.0", @@ -8708,6 +8737,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "peer": true, "dependencies": { "define-properties": "^1.2.1", "gopd": "^1.0.1" @@ -8904,6 +8934,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -8961,6 +8992,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "peer": true, "dependencies": { "has-symbols": "^1.0.3" }, @@ -9209,6 +9241,7 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz", "integrity": "sha512-NGnrKwXzSms2qUUih/ILZ5JBqNTSa1+ZmP6flaIp6KmSElgE9qdndzS3cqjrDovwFdmwsGsLdeFgB6suw+1e9g==", + "peer": true, "dependencies": { "es-errors": "^1.3.0", "hasown": "^2.0.0", @@ -9234,6 +9267,7 @@ "version": "3.0.4", "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", "integrity": "sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "get-intrinsic": "^1.2.1" @@ -9254,6 +9288,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "peer": true, "dependencies": { "has-bigints": "^1.0.1" }, @@ -9265,6 +9300,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "has-tostringtag": "^1.0.0" @@ -9280,6 +9316,7 @@ "version": "1.2.7", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "peer": true, "engines": { "node": ">= 0.4" }, @@ -9302,6 +9339,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.1.tgz", "integrity": "sha512-AHkaJrsUVW6wq6JS8y3JnM/GJF/9cf+k20+iDzlSaJrinEo5+7vRiteOSwBhHRiAyQATN1AmY4hwzxJKPmYf+w==", + "peer": true, "dependencies": { "is-typed-array": "^1.1.13" }, @@ -9316,6 +9354,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "peer": true, "dependencies": { "has-tostringtag": "^1.0.0" }, @@ -9377,6 +9416,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "peer": true, "engines": { "node": ">= 0.4" }, @@ -9396,6 +9436,7 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "peer": true, "dependencies": { "has-tostringtag": "^1.0.0" }, @@ -9428,6 +9469,7 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "has-tostringtag": "^1.0.0" @@ -9443,6 +9485,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.3.tgz", "integrity": "sha512-nA2hv5XIhLR3uVzDDfCIknerhx8XUKnstuOERPNNIinXG7v9u+ohXF67vxm4TPTEPU6lm61ZkwP3c9PCB97rhg==", + "peer": true, "dependencies": { "call-bind": "^1.0.7" }, @@ -9468,6 +9511,7 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "peer": true, "dependencies": { "has-tostringtag": "^1.0.0" }, @@ -9482,6 +9526,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "peer": true, "dependencies": { "has-symbols": "^1.0.2" }, @@ -9496,6 +9541,7 @@ "version": "1.1.13", "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz", "integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==", + "peer": true, "dependencies": { "which-typed-array": "^1.1.14" }, @@ -9515,6 +9561,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.2" }, @@ -9525,7 +9572,8 @@ "node_modules/isarray": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", - "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==" + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "peer": true }, "node_modules/isexe": { "version": "2.0.0", @@ -11569,6 +11617,7 @@ "version": "1.13.1", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -11615,6 +11664,7 @@ "version": "2.0.8", "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -11632,6 +11682,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -11645,6 +11696,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.0.tgz", "integrity": "sha512-yBYjY9QX2hnRmZHAjG/f13MzmBzxzYgQhFrke06TTyKY5zSTEqkOeukBzIdVA3j3ulu8Qa3MbVFShV7T2RmGtQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -12294,6 +12346,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "peer": true, "engines": { "node": ">= 0.4" } @@ -12869,6 +12922,7 @@ "version": "1.5.2", "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.2.tgz", "integrity": "sha512-NcDiDkTLuPR+++OCKB0nWafEmhg/Da8aUPLPMQbK+bxKKCm1/S5he+AqYa4PlMCVBalb4/yxIRub6qkEx5yJbw==", + "peer": true, "dependencies": { "call-bind": "^1.0.6", "define-properties": "^1.2.1", @@ -13142,6 +13196,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", "integrity": "sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "get-intrinsic": "^1.2.4", @@ -13178,6 +13233,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.3.tgz", "integrity": "sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==", + "peer": true, "dependencies": { "call-bind": "^1.0.6", "es-errors": "^1.3.0", @@ -13248,6 +13304,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "peer": true, "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", @@ -13303,6 +13360,7 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "es-errors": "^1.3.0", @@ -13724,6 +13782,7 @@ "version": "1.2.9", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", "integrity": "sha512-klHuCNxiMZ8MlsOihJhJEBJAiMVqU3Z2nEXWfWnIqjN0gEFS9J9+IxKozWWtQGcgoa1WUZzLjKPTr4ZHNFTFxw==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -13741,6 +13800,7 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.8.tgz", "integrity": "sha512-p73uL5VCHCO2BZZ6krwwQE3kCzM7NKmis8S//xEC6fQonchbum4eP6kR4DLEjQFO3Wnj3Fuo8NM0kOSjVdHjZQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -13754,6 +13814,7 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1", @@ -14184,6 +14245,7 @@ "version": "3.15.0", "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", + "peer": true, "dependencies": { "@types/json5": "^0.0.29", "json5": "^1.0.2", @@ -14195,6 +14257,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "peer": true, "dependencies": { "minimist": "^1.2.0" }, @@ -14206,6 +14269,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "peer": true, "engines": { "node": ">=4" } @@ -14266,6 +14330,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz", "integrity": "sha512-gEymJYKZtKXzzBzM4jqa9w6Q1Jjm7x2d+sh19AdsD4wqnMPDYyvwpsIc2Q/835kHuo3BEQ7CjelGhfTsoBb2MQ==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "es-errors": "^1.3.0", @@ -14279,6 +14344,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.1.tgz", "integrity": "sha512-3iMJ9q0ao7WE9tWcaYKIptkNBuOIcZCCT0d4MRvuuH88fEoEH62IuQe0OtraD3ebQEoTRk8XCBoknUNc1Y67pw==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "for-each": "^0.3.3", @@ -14297,6 +14363,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.2.tgz", "integrity": "sha512-Ous0vodHa56FviZucS2E63zkgtgrACj7omjwd/8lTEMEPFFyjfixMZ1ZXenpgCFBBt4EC1J2XsyVS2gkG0eTFA==", + "peer": true, "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.7", @@ -14316,6 +14383,7 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.6.tgz", "integrity": "sha512-/OxDN6OtAk5KBpGb28T+HZc2M+ADtvRxXrKKbUwtsLgdoxgX13hyy7ek6bFRl5+aBs2yZzB0c4CnQfAtVypW/g==", + "peer": true, "dependencies": { "call-bind": "^1.0.7", "for-each": "^0.3.3", @@ -14374,6 +14442,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", + "peer": true, "dependencies": { "call-bind": "^1.0.2", "has-bigints": "^1.0.2", @@ -14720,6 +14789,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "peer": true, "dependencies": { "is-bigint": "^1.0.1", "is-boolean-object": "^1.1.0", @@ -14735,6 +14805,7 @@ "version": "1.1.15", "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz", "integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==", + "peer": true, "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.7", @@ -14780,6 +14851,69 @@ "node": ">=4" } }, + "node_modules/wink-distance": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz", + "integrity": "sha512-pyEhUB/OKFYcgOC4J6E+c+gwVA/8qg2s5n49mIcUsJZM5iDSa17uOxRQXR4rvfp+gbj55K/I08FwjFBwb6fq3g==", + "dependencies": { + "wink-helpers": "^2.0.0", + "wink-jaro-distance": "^2.0.0" + } + }, + "node_modules/wink-eng-lite-web-model": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/wink-eng-lite-web-model/-/wink-eng-lite-web-model-1.8.0.tgz", + "integrity": "sha512-PlSaw2tzQ2SrKYEaH6AbxIUCFnQ9H7FeReVluV9O9VpgfYYa+urttUoAgzDrVujeMkJtACAIY8eFIkQgbEMpPg==", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/wink-helpers": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wink-helpers/-/wink-helpers-2.0.0.tgz", + "integrity": "sha512-I/ZzXrHcNRXuoeFJmp2vMVqDI6UCK02Tds1WP4kSGAmx520gjL1BObVzF7d2ps24tyHIly9ngdB2jwhlFUjPvg==" + }, + "node_modules/wink-jaro-distance": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wink-jaro-distance/-/wink-jaro-distance-2.0.0.tgz", + "integrity": "sha512-9bcUaXCi9N8iYpGWbFkf83OsBkg17r4hEyxusEzl+nnReLRPqxhB9YNeRn3g54SYnVRNXP029lY3HDsbdxTAuA==" + }, + "node_modules/wink-nlp": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/wink-nlp/-/wink-nlp-1.14.3.tgz", + "integrity": "sha512-lvY5iCs3T8I34F8WKS70+2P0U9dWLn3vdPf/Z+m2VK14N7OmqnPzmHfh3moHdusajoQ37Em39z0IZB9K4x/96A==" + }, + "node_modules/wink-nlp-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/wink-nlp-utils/-/wink-nlp-utils-2.1.0.tgz", + "integrity": "sha512-b7PcRhEBNxQmsmht70jLOkwYUyie3da4/cgEXL+CumYO5b/nwV+W7fuMXToh5BtGq1RABznmc2TGTp1Qf/JUXg==", + "dependencies": { + "wink-distance": "^2.0.1", + "wink-eng-lite-web-model": "^1.4.3", + "wink-helpers": "^2.0.0", + "wink-nlp": "^1.12.0", + "wink-porter2-stemmer": "^2.0.1", + "wink-tokenizer": "^5.2.3" + } + }, + "node_modules/wink-porter2-stemmer": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/wink-porter2-stemmer/-/wink-porter2-stemmer-2.0.1.tgz", + "integrity": "sha512-0g+RkkqhRXFmSpJQStVXW5N/WsshWpJXsoDRW7DwVkGI2uDT6IBCoq3xdH5p6IHLaC6ygk7RWUsUx4alKxoagQ==" + }, + "node_modules/wink-tokenizer": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/wink-tokenizer/-/wink-tokenizer-5.3.0.tgz", + "integrity": "sha512-O/yAw0g3FmSgeeQuYAJJfP7fVPB4A6ay0018qASh79aWmIOyPYy4j4r9EQT8xBjicja6lCLvgRVAybmEBaATQA==", + "dependencies": { + "emoji-regex": "^9.0.0" + } + }, + "node_modules/wink-tokenizer/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/core/package.json b/core/package.json index bdda48184..952a9503d 100644 --- a/core/package.json +++ b/core/package.json @@ -32,7 +32,6 @@ "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", @@ -49,7 +48,6 @@ "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", - "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", @@ -97,6 +95,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" diff --git a/core/promptFiles/handlebarUtils.ts b/core/promptFiles/handlebarUtils.ts index ada9fa6b7..947b76fbf 100644 --- a/core/promptFiles/handlebarUtils.ts +++ b/core/promptFiles/handlebarUtils.ts @@ -71,7 +71,7 @@ export function registerHelpers( export async function prepareTemplateAndData( template: string, readFile: (filepath: string) => Promise, - inputData: any, + inputData: Record, ctxProviderNames: string[], ): Promise<[string, any]> { const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames); @@ -95,7 +95,7 @@ export async function prepareTemplateAndData( return [newTemplate, data]; } -export function compileAndRenderTemplate(template: string, data: any): string { +export function compileAndRenderTemplate(template: string, data: Record): string { const templateFn = Handlebars.compile(template); return templateFn(data); } diff --git a/core/promptFiles/renderTemplatedString.ts b/core/promptFiles/renderTemplatedString.ts index d31cce0b9..bcc645ace 100644 --- a/core/promptFiles/renderTemplatedString.ts +++ b/core/promptFiles/renderTemplatedString.ts @@ -8,7 +8,7 @@ import { export async function renderTemplatedString( template: string, readFile: (filepath: string) => Promise, - inputData: any, + inputData: Record, availableHelpers?: Array<[string, Handlebars.HelperDelegate]>, ): Promise { const helperPromises = availableHelpers diff --git a/core/promptFiles/slashCommandFromPromptFile.ts b/core/promptFiles/slashCommandFromPromptFile.ts index e81f13615..af865078e 100644 --- a/core/promptFiles/slashCommandFromPromptFile.ts +++ b/core/promptFiles/slashCommandFromPromptFile.ts @@ -1,4 +1,4 @@ -import { SlashCommand } from ".."; +import { ContinueSDK, SlashCommand } from ".."; import { stripImages } from "../llm/images"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; @@ -37,18 +37,18 @@ export function extractUserInput(input: string, commandName: string): string { 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 getDefaultVariables(context: ContinueSDK, userInput: string): Promise> { + const currentFile = await context.ide.getCurrentFile(); + const vars: Record = { input: userInput }; + if (currentFile) { + vars.currentFile = currentFile.path; + } + return vars; } export async function renderPrompt( prompt: string, - context: any, + context: ContinueSDK, userInput: string, ) { const helpers = getContextProviderHelpers(context); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e2d512950..abe6c8fe1 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -15,7 +15,7 @@ import type { SessionInfo, SiteIndexingConfig, } from "../"; -import type { AutocompleteInput } from "../autocomplete/completionProvider"; +import { AutocompleteInput } from "../autocomplete/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index eda6bebfb..d6b6a90d3 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -48,7 +48,11 @@ export type ToIdeFromWebviewOrCoreProtocol = { ]; getProblems: [{ filepath: string }, Problem[]]; getOpenFiles: [undefined, string[]]; - getCurrentFile: [undefined, string | undefined]; + getCurrentFile: [undefined, undefined | { + isUntitled: boolean; + path: string; + contents: string; + }]; getPinnedFiles: [undefined, string[]]; showLines: [{ filepath: string; startLine: number; endLine: number }, void]; readRangeInFile: [{ filepath: string; range: Range }, string]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 3b357b679..6fb101c03 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -1,8 +1,9 @@ -import type { RangeInFileWithContents } from "../commands/util.js"; -import type { ContextSubmenuItem } from "../index.js"; import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; +import type { RangeInFileWithContents } from "../commands/util.js"; +import type { ContextSubmenuItem, MessageContent } from "../index.js"; + export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { onLoad: [ undefined, @@ -15,7 +16,17 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { }, ]; openUrl: [string, void]; - applyToCurrentFile: [{ text: string; streamId: string }, void]; + // We pass the `curSelectedModel` because we currently cannot access the + // default model title in the GUI from JB + applyToFile: [ + { + text: string; + streamId: string; + curSelectedModelTitle: string; + filepath: string; + }, + void, + ]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; openConfigJson: [undefined, void]; @@ -30,8 +41,23 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { setGitHubAuthToken: [{ token: string }, void]; acceptDiff: [{ filepath: string }, void]; rejectDiff: [{ filepath: string }, void]; + "edit/sendPrompt": [ + { prompt: MessageContent; range: RangeInFileWithContents }, + void, + ]; + "edit/acceptReject": [ + { accept: boolean; onlyFirst: boolean; filepath: string }, + void, + ]; + "edit/escape": [undefined, void]; }; +export interface EditModeArgs { + highlightedCode: RangeInFileWithContents; +} + +export type EditStatus = "not-started" | "streaming" | "accepting" | "done"; + export interface ApplyState { streamId: string; status: "streaming" | "done" | "closed"; @@ -39,7 +65,6 @@ export interface ApplyState { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; - setTTSActive: [boolean, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap updateSubmenuItems: [ { provider: string; submenuItems: ContextSubmenuItem[] }, @@ -66,6 +91,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { * @deprecated Use navigateTo with a path instead. */ viewHistory: [undefined, void]; + focusContinueSessionId: [{ sessionId: string | undefined }, void]; newSession: [undefined, void]; setTheme: [{ theme: any }, void]; setColors: [{ [key: string]: string }, void]; @@ -76,4 +102,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { openOnboardingCard: [undefined, void]; applyCodeFromChat: [undefined, void]; updateApplyState: [ApplyState, void]; + startEditMode: [EditModeArgs, void]; + setEditStatus: [{ status: EditStatus }, void]; + exitEditMode: [undefined, void]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index f570b9e87..1c0f5e962 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -60,4 +60,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", + "getWebviewHistoryLength" ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index eccb1e97e..ef2daacf0 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -16,4 +16,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { void, ]; setTTSActive: [boolean, void]; + getWebviewHistoryLength: [undefined, number]; }; diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 9e5641332..f48e848a9 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,6 +1,6 @@ import fs from "node:fs"; -import { getGlobalContextFilePath } from "./paths"; import { EmbeddingsProvider } from "../"; +import { getGlobalContextFilePath } from "./paths"; export type GlobalContextType = { indexingPaused: boolean; @@ -37,7 +37,15 @@ export class GlobalContext { ); } else { const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); - const parsed = JSON.parse(data); + + let parsed; + try { + parsed = JSON.parse(data); + } catch (e: any) { + console.warn(`Error updating global context: ${e}`); + return; + } + parsed[key] = value; fs.writeFileSync( getGlobalContextFilePath(), @@ -54,7 +62,12 @@ export class GlobalContext { } const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); - const parsed = JSON.parse(data); - return parsed[key]; + try { + const parsed = JSON.parse(data); + return parsed[key]; + } catch (e: any) { + console.warn(`Error parsing global context: ${e}`); + return undefined; + } } } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 6e8bd6c0d..459e0adee 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -19,7 +19,7 @@ import { GetGhTokenArgs } from "../protocol/ide.js"; import { getContinueGlobalPath } from "./paths.js"; class FileSystemIde implements IDE { - constructor(private readonly workspaceDir: string) {} + constructor(private readonly workspaceDir: string) { } showToast( type: ToastType, message: string, @@ -38,7 +38,7 @@ class FileSystemIde implements IDE { throw new Error("Method not implemented."); } onDidChangeActiveTextEditor(callback: (filepath: string) => void): void { - throw new Error("Method not implemented."); + return; } async getIdeSettings(): Promise { @@ -205,6 +205,10 @@ class FileSystemIde implements IDE { }); } + getCurrentFile(): Promise { + return Promise.resolve(undefined); + } + showDiff( filepath: string, newContents: string, @@ -221,10 +225,6 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } - getCurrentFile(): Promise { - return Promise.resolve(""); - } - getPinnedFiles(): Promise { return Promise.resolve([]); } diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts index 785a62c41..fb4be85d7 100644 --- a/core/util/generateRepoMap.ts +++ b/core/util/generateRepoMap.ts @@ -12,9 +12,6 @@ export interface RepoMapOptions { } class RepoMapGenerator { - private llm: ILLM; - private ide: IDE; - private options: RepoMapOptions; private maxRepoMapTokens: number; private repoMapPath: string = getRepoMapFilePath(); @@ -32,10 +29,11 @@ class RepoMapGenerator { "this map contains the name of the file, and the signature for any " + "classes, methods, or functions in the file.\n\n"; - constructor(llm: ILLM, ide: IDE, options: RepoMapOptions) { - this.llm = llm; - this.ide = ide; - this.options = options; + constructor( + private llm: ILLM, + private ide: IDE, + private options: RepoMapOptions, + ) { this.maxRepoMapTokens = llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; } diff --git a/core/util/history.ts b/core/util/history.ts index 5f4a85e5d..08bc26994 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -3,6 +3,18 @@ import { PersistedSessionInfo, SessionInfo } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; import { getSessionFilePath, getSessionsListPath } from "./paths.js"; +function safeParseArray( + value: string, + errorMessage: string = "Error parsing array", +): T[] | undefined { + try { + return JSON.parse(value) as T[]; + } catch (e: any) { + console.warn(`${errorMessage}: ${e}`); + return undefined; + } +} + class HistoryManager { list(options: ListHistoryOptions): SessionInfo[] { const filepath = getSessionsListPath(); @@ -10,7 +22,9 @@ class HistoryManager { return []; } const content = fs.readFileSync(filepath, "utf8"); - let sessions = JSON.parse(content).filter((session: any) => { + + let sessions = safeParseArray(content) ?? []; + sessions = sessions.filter((session: any) => { // Filter out old format return typeof session.session_id !== "string"; }); @@ -35,14 +49,11 @@ class HistoryManager { // Read and update the sessions list const sessionsListFile = getSessionsListPath(); const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8"); - let sessionsList: SessionInfo[]; - try { - sessionsList = JSON.parse(sessionsListRaw); - } catch (error) { - throw new Error( - `It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFile}). Please fix this before creating a new session.`, - ); - } + let sessionsList = + safeParseArray( + sessionsListRaw, + "Error parsing sessions.json", + ) ?? []; sessionsList = sessionsList.filter( (session) => session.sessionId !== sessionId, diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 0ed9f63d2..75c980809 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -27,7 +27,7 @@ export class MessageIde implements IDE { messageType: T, callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1], ) => void, - ) {} + ) { } pathSep(): Promise { return this.request("pathSep", undefined); @@ -177,7 +177,7 @@ export class MessageIde implements IDE { return this.request("getOpenFiles", undefined); } - getCurrentFile(): Promise { + getCurrentFile() { return this.request("getCurrentFile", undefined); } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 88c7d38a6..7a94abc03 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -12,7 +12,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, maxSnippetPercentage: 0.6, - recentlyEditedSimilarityThreshold: 0.3, + recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold. useCache: true, onlyMyCode: true, useOtherFiles: true, @@ -21,6 +21,8 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disableInFiles: undefined, useImports: true, useRootPathContext: true, + transform: true, + showWhateverWeHaveAtXMs: 300, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/core/util/paths.ts b/core/util/paths.ts index 3002892ca..b10b7fca6 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -3,9 +3,9 @@ import dotenv from "dotenv"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import { IdeType, SerializedContinueConfig } from "../"; import { defaultConfig, defaultConfigJetBrains } from "../config/default"; import Types from "../config/types"; -import { IdeType, SerializedContinueConfig } from "../"; dotenv.config(); @@ -348,3 +348,18 @@ export function getRepoMapFilePath(): string { export function getEsbuildBinaryPath(): string { return path.join(getContinueUtilsPath(), "esbuild"); } + +export function setupInitialDotContinueDirectory() { + const devDataTypes = [ + "chat", + "autocomplete", + "quickEdit", + "tokens_generated", + ]; + devDataTypes.forEach((p) => { + const devDataPath = getDevDataFilePath(p); + if (!fs.existsSync(devDataPath)) { + fs.writeFileSync(devDataPath, ""); + } + }); +} diff --git a/core/util/posthog.ts b/core/util/posthog.ts index c9d329f2b..58828dacd 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -13,22 +13,34 @@ export class Telemetry { event: string, properties: { [key: string]: any }, sendToTeam: boolean = false, + isExtensionActivationError: boolean = false, ) { - if (process.env.NODE_ENV === "test") { - return; - } try { - Telemetry.client?.capture({ + const augmentedProperties = { + ...properties, + os: Telemetry.os, + extensionVersion: Telemetry.ideInfo?.extensionVersion, + ideName: Telemetry.ideInfo?.name, + ideType: Telemetry.ideInfo?.ideType, + }; + const payload = { distinctId: Telemetry.uniqueId, event, - properties: { - ...properties, - os: Telemetry.os, - extensionVersion: Telemetry.ideInfo?.extensionVersion, - ideName: Telemetry.ideInfo?.name, - ideType: Telemetry.ideInfo?.ideType, - }, - }); + properties: augmentedProperties, + }; + + // In cases where an extremely early fatal error occurs, we may not have initialized yet + if (isExtensionActivationError && !Telemetry.client) { + const client = await Telemetry.getTelemetryClient(); + client?.capture(payload); + return; + } + + if (process.env.NODE_ENV === "test") { + return; + } + + Telemetry.client?.capture(payload); if (sendToTeam) { void TeamAnalytics.capture(event, properties); @@ -42,6 +54,17 @@ export class Telemetry { Telemetry.client?.shutdown(); } + static async getTelemetryClient() { + try { + const { PostHog } = await import("posthog-node"); + return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { + host: "https://app.posthog.com", + }); + } catch (e) { + console.error(`Failed to setup telemetry: ${e}`); + } + } + static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) { Telemetry.uniqueId = uniqueId; Telemetry.os = os.platform(); @@ -49,20 +72,8 @@ export class Telemetry { if (!allow || process.env.NODE_ENV === "test") { Telemetry.client = undefined; - } else { - try { - if (!Telemetry.client) { - const { PostHog } = await import("posthog-node"); - Telemetry.client = new PostHog( - "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", - { - host: "https://app.posthog.com", - }, - ); - } - } catch (e) { - console.error(`Failed to setup telemetry: ${e}`); - } + } else if (!Telemetry.client) { + Telemetry.client = await Telemetry.getTelemetryClient(); } } } diff --git a/core/util/ranges.ts b/core/util/ranges.ts index 345933f03..3fb5b609e 100644 --- a/core/util/ranges.ts +++ b/core/util/ranges.ts @@ -7,7 +7,7 @@ export function getRangeInString(content: string, range: Range): string { return ( lines[range.start.line]?.substring( range.start.character, - range.end.character + 1, + range.end.character, ) ?? "" ); } diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 08cfe64d1..bf6891f23 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -115,6 +115,7 @@ export async function getLanguageForFile( return undefined; } let language = nameToLanguage.get(languageName); + if (!language) { language = await loadLanguageForFileExt(extension); nameToLanguage.set(languageName, language); @@ -149,7 +150,9 @@ export async function getQueryForFile( const sourcePath = path.join( __dirname, "..", - "tree-sitter", + ...(process.env.NODE_ENV === "test" + ? ["extensions", "vscode", "tree-sitter"] + : ["tree-sitter"]), queryType, `${fullLangName}.scm`, ); diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md index 0170283d9..01cf2d064 100644 --- a/docs/docs/actions/how-to-customize.md +++ b/docs/docs/actions/how-to-customize.md @@ -7,7 +7,7 @@ sidebar_position: 5 ## Built-in slash commands -Continue has a large library of built-in slash commands, but when you first install we only display the most commonly used ones, like “/edit”, “/comment”, and “/share”. To add more actions, you can open [config.json](../customize/config.mdx) and add them to the `slashCommands` array. +Continue has a large library of built-in slash commands, but when you first install we only display the most commonly used ones, like “/edit”, “/comment”, and “/share”. To add more actions, you can open [config.json](../reference.md) and add them to the `slashCommands` array. ## Custom slash commands @@ -20,7 +20,7 @@ There are two ways to add custom slash commands: If you want to go a step further than writing custom commands with natural language, you can write a custom function that returns the response. This requires using `config.ts` instead of `config.json`. diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md index cffc0d65d..5be83b2e7 100644 --- a/docs/docs/actions/how-to-use-it.md +++ b/docs/docs/actions/how-to-use-it.md @@ -14,7 +14,7 @@ Actions are shortcuts for common use cases. For example, you might want to revie ### Slash commands -The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. +The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. ![slash-commands](/img/slash-commands.png) @@ -48,7 +48,7 @@ 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. +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. @@ -76,10 +76,10 @@ Right click actions let you highlight a desired region of code, right click, and #### Debug action -The debug action is a special built-in keyboard shortcut in the VS Code extension. Use `cmd/ctrl+shift+R` to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. +The debug action is a special built-in keyboard shortcut in the VS Code extension. Use cmd/ctrl + shift + R to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. #### Quick fixes -Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut `cmd/ctrl+.` will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use `cmd/ctrl+.` again and Continue will attempt to help solve the problem. +Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut cmd/ctrl + . will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use cmd/ctrl + . again and Continue will attempt to help solve the problem. ![ask-continue](/img/ask-continue.png) diff --git a/docs/docs/autocomplete/context-selection.md b/docs/docs/autocomplete/context-selection.md index e85e3d4bd..f237a3625 100644 --- a/docs/docs/autocomplete/context-selection.md +++ b/docs/docs/autocomplete/context-selection.md @@ -13,7 +13,7 @@ We will always include the code from your file prior to and after the cursor pos ### Definitions from the Language Server Protocol -Similar to how you can use `cmd/ctrl + click` in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. +Similar to how you can use cmd/ctrl + `click` in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. ### Imported files diff --git a/docs/docs/autocomplete/how-to-customize.md b/docs/docs/autocomplete/how-to-customize.md index df95b3201..dcf6ba234 100644 --- a/docs/docs/autocomplete/how-to-customize.md +++ b/docs/docs/autocomplete/how-to-customize.md @@ -5,7 +5,7 @@ keywords: [customize] sidebar_position: 5 --- -Continue offers a handful of parameters in [`config.json`](../customize/config.mdx) that can be tuned to find the perfect balance between suggestion quality and system performance for your specific needs and hardware capabilities: +Continue offers a handful of parameters in [`config.json`](../reference.md) that can be tuned to find the perfect balance between suggestion quality and system performance for your specific needs and hardware capabilities: ```json title="config.json" "tabAutocompleteOptions": { diff --git a/docs/docs/autocomplete/how-to-use-it.md b/docs/docs/autocomplete/how-to-use-it.md index 92a3db76e..5fd127ce5 100644 --- a/docs/docs/autocomplete/how-to-use-it.md +++ b/docs/docs/autocomplete/how-to-use-it.md @@ -14,12 +14,12 @@ Autocomplete provides inline code suggestions as you type. To enable it, simply ### Accepting a full suggestion -Accept a full suggestion by pressing `Tab` +Accept a full suggestion by pressing Tab ### Rejecting a full suggestion -Reject a full suggestion with `Esc` +Reject a full suggestion with Esc ### Partially accepting a suggestion -For more granular control, use `cmd/ctrl + →` to accept parts of the suggestion word-by-word. +For more granular control, use cmd/ctrl + → to accept parts of the suggestion word-by-word. diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index ebdb41185..072bc0128 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -11,11 +11,11 @@ Typing a question or instructions into the input box is the only required contex ## Highlighted code -The highlighted code you’ve selected by pressing `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) will be included in your prompt alongside the input you provide. This is the only section of code that will be provided to the model unless you highlight additional sections or use one of the other selection methods below. +The highlighted code you’ve selected by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) will be included in your prompt alongside the input you provide. This is the only section of code that will be provided to the model unless you highlight additional sections or use one of the other selection methods below. ## Active file -You can include the currently open file as context by pressing `cmd/ctrl + opt + enter` when you send your request. +You can include the currently open file as context by pressing cmd/ctrl + opt + enter when you send your request. ## Specific file diff --git a/docs/docs/chat/how-it-works.md b/docs/docs/chat/how-it-works.md index b5e8aaece..84c81582e 100644 --- a/docs/docs/chat/how-it-works.md +++ b/docs/docs/chat/how-it-works.md @@ -7,7 +7,7 @@ sidebar_position: 4 Using any selected code sections, all context that you have selected with @, and your input instructions, we prompt the model to provide a response in the sidebar. If you are asking a follow-up, then all earlier session context is also included. No other additional context is provided to the model. -The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. +The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.md#llm-prompt-logs). diff --git a/docs/docs/chat/how-to-use-it.md b/docs/docs/chat/how-to-use-it.md index 509702b4f..112649aeb 100644 --- a/docs/docs/chat/how-to-use-it.md +++ b/docs/docs/chat/how-to-use-it.md @@ -20,7 +20,7 @@ You send it a question, and it replies with an answer. You tell it to solve a pr ## Highlight a code section to include as context -You select a code section with your mouse, press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way. +You select a code section with your mouse, press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way. ## Reference context with the @ symbol @@ -32,8 +32,8 @@ When the LLM replies with edits to a file, you can click the “Apply” button. ## Start a fresh session for a new task -Once you complete a task and want to start a new one, press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM. +Once you complete a task and want to start a new one, press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM. ## Switch between different models -If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl + ’` +If you have configured multiple models, you can switch between models using the dropdown or by pressing cmd/ctrl + ’ diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index 023e875c1..bf968ad12 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; :::info -This page recommends models and providers for Chat. Read more about how to set up your `config.json` [here](../customize/config.mdx). +This page recommends models and providers for Chat. Read more about how to set up your `config.json` [here](../reference.md). ::: ## Best overall experience @@ -25,7 +25,7 @@ Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customiz { "title": "Claude 3.5 Sonnet", "provider": "anthropic", - "model": "claude-3-5-sonnet-20240620", + "model": "claude-3-5-sonnet-latest", "apiKey": "[ANTHROPIC_API_KEY]" } ] diff --git a/docs/docs/customize/config.mdx b/docs/docs/customize/config.mdx deleted file mode 100644 index cac96ceb6..000000000 --- a/docs/docs/customize/config.mdx +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: config.json Reference -keywords: [config.json, configuration, options] ---- - -import Schema from "@site/static/schemas/config.json"; -import JSONSchemaViewer from "@theme/JSONSchemaViewer"; - -# Configuration options - -The following shows the JSON Schema definition for `config.json`. - -You can also define a partial `config.json` object in a file called `.continuerc.json` at the root of your workspace. This will be applied on top of any configuration from `config.json`. - - - -[View the source](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json) diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 346ffb2d3..bb7e0f770 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -44,7 +44,7 @@ All of the configuration options available for chat models are available to use } ``` -If you aren't yet familiar with the available options, you can find the full reference [here](../config.mdx). +If you aren't yet familiar with the available options, you can find the full reference [here](./ways-to-configure.md). ## Configuration Options @@ -93,7 +93,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa ### I want better completions, should I use GPT-4? -Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/d2bc6359e8ebf647892ec953e418042dc7f8a685/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. +Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. ### I'm not seeing any completions @@ -103,8 +103,8 @@ Follow these steps to ensure that everything is set up correctly: 2. Make sure you have downloaded Ollama. 3. Run `ollama run starcoder2:3b` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). -6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl+, then search for this and check the box) +5. Check the output of the logs to find any potential errors: cmd/ctrl + shift + P -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains. +6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl + , then search for this and check the box) 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. ### Completions are slow @@ -122,8 +122,8 @@ Yes, in VS Code, if you don't want to be shown suggestions automatically you can 1. Set `"editor.inlineSuggest.enabled": false` in VS Code settings to disable automatic suggestions 2. Open "Keyboard Shortcuts" (cmd/ctrl+k, cmd/ctrl+s) and search for `editor.action.inlineSuggest.trigger` 3. Click the "+" icon to add a new keybinding -4. Press the key combination you want to use to trigger suggestions (e.g. `ctrl+space`) -5. Now whenever you want to see a suggestion, you can press your key binding (e.g. `ctrl+space`) to trigger suggestions manually +4. Press the key combination you want to use to trigger suggestions (e.g. cmd/ctrl + space) +5. Now whenever you want to see a suggestion, you can press your key binding (e.g. cmd/ctrl + space) to trigger suggestions manually ### Is there a shortcut to accept one line at a time? @@ -137,7 +137,7 @@ Click the "Continue" button in the status panel at the bottom right of the scree Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". -You can also use the default shortcut to disable autocomplete directly: press `ctrl/cmd + K`, `ctrl/cmd + A`. This will turn off autocomplete without navigating through settings. +You can also use the default shortcut to disable autocomplete directly using a chord: press and hold ctrl/cmd + K (continue holding ctrl/cmd) and press ctrl/cmd + A. This will turn off autocomplete without navigating through settings. #### JetBrains diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.md index 8b757a11f..4da920943 100644 --- a/docs/docs/customize/deep-dives/codebase.md +++ b/docs/docs/customize/deep-dives/codebase.md @@ -5,7 +5,11 @@ keywords: [talk, embeddings, reranker, codebase, experimental] # @Codebase -Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`. +Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally using `transformers.js` and stored locally in `~/.continue/index`. + +:::info[`transformers.js cannot be used in JetBrains`] +Currently, `transformers.js` cannot be used in JetBrains IDEs. However, you can select a differet embeddings model from [the list here](../model-types/embeddings.md). +::: Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@Codebase` or `@Folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files. @@ -34,7 +38,7 @@ Here are use cases where it is not useful: ## Configuration -There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`, and are the same for the codebase and folder context providers: +There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`, and are the same for the codebase, docs, and folder context providers: ```json title="config.json" { @@ -67,10 +71,12 @@ Whether to use re-ranking, which will allow initial selection of `nRetrieve` res Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`. +Continue also supports a **global** `.continueignore` file that will be respected for all workspaces, which can be created at `~/.continue/.continueignore`. + If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file. -If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window". +If you need to force a refresh of the index, reload the VS Code window with cmd/ctrl + shift + p + "Reload Window". ## Repository map -Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase. +Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase. diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md index bc8968528..58612106d 100644 --- a/docs/docs/customize/deep-dives/docs.md +++ b/docs/docs/customize/deep-dives/docs.md @@ -6,7 +6,7 @@ toc_max_heading_level: 5 # @Docs -The [`@Docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. +The [`@Docs` context provider](customize/context-providers.md#docs) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. ## Enabling the `@Docs` context provider @@ -69,6 +69,25 @@ The [configuration schema for docs](https://github.com/continuedev/continue/blob - `rootUrl`: The base URL of the documentation site, used to determine which pages to index. - `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI. +## Configuration + +As with [@Codebase context provider configuration](https://docs.continue.dev/customize/deep-dives/codebase#configuration), you can adjust the behavior of the docs context provider with the `nRetrieve`, `nFinal`, and `useReranking` + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "docs", + "params": { + "nRetrieve": 25, + "nFinal": 5, + "useReranking": true + } + } + ] +} +``` + ## Crawling dynamically generated sites with `useChromiumForDocsCrawling` By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript. diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 1c70d729c..928e01543 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -35,7 +35,7 @@ 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. +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. diff --git a/docs/docs/customize/deep-dives/ways-to-configure.md b/docs/docs/customize/deep-dives/ways-to-configure.md new file mode 100644 index 000000000..d67b92147 --- /dev/null +++ b/docs/docs/customize/deep-dives/ways-to-configure.md @@ -0,0 +1,68 @@ +--- +description: Ways to configure +keywords: [config, settings, customize] +--- + +# Ways to configure + +Continue can be deeply customized. User-level configuration is stored and can be edited in your home directory in [`config.json`](#configjson): + +- `~/.continue/config.json` (MacOS / Linux) +- `%USERPROFILE%\.continue\config.json` (Windows) + +To open `config.json`, you can click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or check the reference below. + +When you save `config.json`, Continue will automatically refresh to take into account your changes. `config.json` is automatically created the first time you use Continue. `config.json` is automatically generated if it doesn't exist. + +In the vast majority of cases, you will only need to edit `config.json`. However, Continue offers two additional ways to customize configuration: + +- [`.continuerc.json`](#continuercjson) - Workspace-level configuration. If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. This can be set to merge with _or_ override the user-level `config.json` +- [`config.ts`](#configts) - Advanced configuration (probably unnecessary) - a TypeScript file in your home directory that can be used to programmatically modify (_merged_) the `config.json` schema: + - `~/.continue/config.ts` (MacOS / Linux) + - `%USERPROFILE%\.continue\config.ts` (Windows) + +## `config.json` + +See the full reference for `config.json` [here](../../reference.md). + +## `.continuerc.json` + +The format of `.continuerc.json` is the same as `config.json`, plus one _additional_ property `mergeBehavior`, which can be set to either "merge" or "overwrite". If set to "merge" (the default), `.continuerc.json` will be applied on top of `config.json` (arrays and objects are merged). If set to "overwrite", then every top-level property of `.continuerc.json` will overwrite that property from `config.json`. + +Example + +```json title="config.json" +{ + "tabAutocompleteOptions": { + "disable": true + }, + "mergeBehavior": "overwrite" +} +``` + +## `config.ts` + +To programatically extend `config.json`, you can place a `config.ts` script in same directory as `config.json` and export a `modifyConfig` function, like: + +```ts title="config.ts" +export function modifyConfig(config: Config): Config { + config.slashCommands?.push({ + name: "commit", + description: "Write a commit message", + run: async function* (sdk) { + const diff = await sdk.ide.getDiff(); + for await (const message of sdk.llm.streamComplete( + `${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`, + { + maxTokens: 20, + }, + )) { + yield message; + } + }, + }); + return config; +} +``` + +This can be used for slash commands and custom context providers. diff --git a/docs/docs/customize/model-providers/more/anthropic-vertexai.md b/docs/docs/customize/model-providers/more/anthropic-vertexai.md deleted file mode 100644 index 3f00c17f6..000000000 --- a/docs/docs/customize/model-providers/more/anthropic-vertexai.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Anthropic Vertex AI -slug: ../anthropic-vertexai ---- - -:::info - -You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). - -::: - -## Chat model - -We recommend configuring **Claude 3.5 Sonnet** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Claude 3.5 Sonnet", - "provider": "anthropic-vertexai", - "model": "claude-3-5-sonnet-20240620", - "projectId": "[PROJECT_ID]", - "region": "us-east5" - } - ] -} -``` - -## Autocomplete model - -Anthropic Vertex AI currently does not offer any autocomplete models. - -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. - -## Embeddings model - -Anthropic Vertex AI currently does not offer any embeddings models. - -[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. - -## Reranking model - -Anthropic Vertex AI currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. - -## Prompt caching - -Anthropic Vertex AI supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching). - -To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following: - -```jsonc -{ - "models": [ - { - // Enable prompt caching - "cacheBehavior": { - "cacheSystemMessage": true, - "cacheConversation": true - }, - "title": "Anthropic", - "provider": "anthropic", - "model": "claude-3-5-sonnet-20240620", - "apiKey": "[API_KEY]" - } - ] -} -``` diff --git a/docs/docs/customize/model-providers/more/asksage.md b/docs/docs/customize/model-providers/more/asksage.md new file mode 100644 index 000000000..c5ba9218c --- /dev/null +++ b/docs/docs/customize/model-providers/more/asksage.md @@ -0,0 +1,61 @@ +# Ask Sage + +:::info + +To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs:[Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) + +::: + +## Configuration + +To use the Ask Sage models, the following configuration is required to the `config.json` file: + +```json +{ + "models": [ + { + "apiKey": "YOUR_API_KEY", + "apiBase": "https://api.asksage.ai/server/", // apiBase will be the same for all models, but will vary based on tenant. + "model": "gpt4-gov", + "title": "GPT-4 gov", + "provider": "askSage" + } + ] +} +``` + +The `apiBase` will be listed on the Ask Sage platform when you generate an `API key`. You will see context as shown below: + +> Server API for query/training etc.: +> - Documentation: https://app.swaggerhub.com/apis-docs/NICOLASCHAILLAN_1/server_ask-sage_api/1.0 +> - URL for this API is: https://api.asksage.ai/server/ + +## Usage + +Currently, the setup for the models provided by Ask Sage is to support the following two functionalities provided by Continue.Dev: + +- `Chat` to understand and iterate on code in the sidebar +- `Edit` to modify code without leaving your current file + +More models, functionalities and documentation will be added in the future for Ask Sage Integration. + +> We recommend to utilize the`OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities. + +## Current Models From Ask Sage Supported + +The current Models available provided by Ask Sage are: + +| Model | Added | +|--------------------|-------| +| Gov GPT-4.0 | Yes | +| Gov GPT-4o | Yes | +| GPT-4o | Yes | +| GPT-4o-mini | Yes | +| GPT-3.5-16K | Yes | +| Calude 3 Opus | Yes | +| Calude 3 Sonet | Yes | +| Calude 3.5 Sonnet | Yes | +| Gemini Pro | Yes | +| llama 3 | Yes | +| Mistral Large | Yes | + diff --git a/docs/docs/customize/model-providers/more/cerebras.md b/docs/docs/customize/model-providers/more/cerebras.md index 57d549830..d9cbd31dc 100644 --- a/docs/docs/customize/model-providers/more/cerebras.md +++ b/docs/docs/customize/model-providers/more/cerebras.md @@ -1,6 +1,6 @@ # Cerebras Inference -Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B and Llama3.1 70B models. +Cerebras Inference uses specialized silicon to provides fast inference. 1. Create an account in the portal [here](https://cloud.cerebras.ai/). 2. Create and copy the API key for use in Continue. diff --git a/docs/docs/customize/model-providers/more/cohere.md b/docs/docs/customize/model-providers/more/cohere.md index c2b3c631e..24f2a7f88 100644 --- a/docs/docs/customize/model-providers/more/cohere.md +++ b/docs/docs/customize/model-providers/more/cohere.md @@ -45,7 +45,7 @@ We recommend configuring **rerank-english-v3.0** as your reranking model. ```json title="config.json" { - "embeddingsProvider": { + "reranker": { "provider": "cohere", "params": { "model": "rerank-english-v3.0", diff --git a/docs/docs/customize/model-providers/more/gemini-vertexai.md b/docs/docs/customize/model-providers/more/gemini-vertexai.md deleted file mode 100644 index fb92e60ff..000000000 --- a/docs/docs/customize/model-providers/more/gemini-vertexai.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Gemini Vertex AI -slug: ../gemini-vertexai ---- - -:::info - -You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). - -::: - -## Chat model - -We recommend configuring **Gemini 1.5 Pro** as your chat model. - -```json title="config.json" -{ - "models": [ - { - "title": "Gemini 1.5 Pro (Vertex AI)", - "provider": "gemini-vertexai", - "model": "gemini-1.5-pro", - "projectId": "[PROJECT_ID]", - "region": "us-central1" - } - ] -} -``` - -## Autocomplete model - -Gemini Vertex AI currently does not offer any autocomplete models. - -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. - -## Embeddings model - -Gemini Vertex AI currently does not offer any embeddings models. - -[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. - -## Reranking model - -Gemini Vertex AI currently does not offer any reranking models. - -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/more/lmstudio.md b/docs/docs/customize/model-providers/more/lmstudio.md index 7448ebd01..a901f811a 100644 --- a/docs/docs/customize/model-providers/more/lmstudio.md +++ b/docs/docs/customize/model-providers/more/lmstudio.md @@ -14,6 +14,19 @@ } ``` +### Embeddings model + +LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models) + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } +} +``` + ## Setting up a remote instance To configure a remote instance of LM Studio, add the `"apiBase"` property to your model in config.json: diff --git a/docs/docs/customize/model-providers/more/nvidia.md b/docs/docs/customize/model-providers/more/nvidia.md new file mode 100644 index 000000000..049ff7754 --- /dev/null +++ b/docs/docs/customize/model-providers/more/nvidia.md @@ -0,0 +1,52 @@ +--- +title: NVIDIA +--- + +:::info + +[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key. + +::: + +## Chat model + +We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Nemotron-4-340B-Instruct", + "provider": "nvidia", + "model": "nvidia-nemotron-4-340b-instruct", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +NVIDIA currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "[API_KEY]" + } +} +``` + +## Reranking model + +NVIDIA currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/more/textgenwebui.md b/docs/docs/customize/model-providers/more/textgenwebui.md index 9abf2b9e8..723079735 100644 --- a/docs/docs/customize/model-providers/more/textgenwebui.md +++ b/docs/docs/customize/model-providers/more/textgenwebui.md @@ -8,7 +8,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. { "title": "Text Generation WebUI", "provider": "text-gen-webui", - "apiBase": "http://localhost:5000", + "apiBase": "http://localhost:5000/v1", "model": "MODEL_NAME" } ] diff --git a/docs/docs/customize/model-providers/more/watsonx.md b/docs/docs/customize/model-providers/more/watsonx.md index 5cc6b33fa..eeeb6073f 100644 --- a/docs/docs/customize/model-providers/more/watsonx.md +++ b/docs/docs/customize/model-providers/more/watsonx.md @@ -10,35 +10,35 @@ Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or To get started with watsonx SaaS, visit the [registration page](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx). If you do not have an existing IBM Cloud account, you can sign up for a free trial. -To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [setup an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue: +To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [set up an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue: -- Set **watsonx URL** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region. -- Set **watsonx Project ID** to your watsonx project ID. -- Set **watsonx API Key** to your watsonx API Key. +- Set **apiBase** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region. +- Set **projectId** to your watsonx project ID. +- Set **apiKey** to your watsonx API Key. ### watsonx.ai Software To authenticate to your watsonx.ai Software instance with Continue, you can use either `username/password` or `ZenApiKey` method: 1. _Option 1_ (Recommended): using `ZenApiKey` authentication: - - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. - - Set **watsonx Project ID** to your watsonx project ID. - - Set **watsonx API Key** to your watsonx Zen API Key. To generate it: - 1. Log in to the CPD web client. - 2. From the toolbar, click your avatar. - 3. Click **Profile and settings**. - 4. Click **API key** > **Generate new key**. - 5. Click **Generate**. - 6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it. - 7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo ":" | base64`, replacing `` with your CPD username and `` with the API Key you just created. + - Set **apiBase** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **projectId** to your watsonx project ID. + - Set **apiKey** to your watsonx Zen API Key. To generate it: + 1. Log in to the CPD web client. + 2. From the toolbar, click your avatar. + 3. Click **Profile and settings**. + 4. Click **API key** > **Generate new key**. + 5. Click **Generate**. + 6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it. + 7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo ":" | base64`, replacing `` with your CPD username and `` with the API Key you just created. 2. _Option 2_: using `username/password` authentication: - - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. - - Set **watsonx Project ID** to your watsonx project ID. - - Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format. + - Set **apiBase** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **projectId** to your watsonx project ID. + - Set **API Key** to your watsonx Username and Password using `username:password` as format. ## Configuration -Add the following configuration to your `config.json` file to use the watsonx provider. Fill in the `watsonxCreds` with the authentication details you obtained in the setup step. +Add the following configuration to your `config.json` file to use the watsonx provider. ```json title="~/.continue/config.json" { @@ -46,39 +46,101 @@ Add the following configuration to your `config.json` file to use the watsonx pr { "model": "model ID", "title": "watsonx - Model Name", - "watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", - "watsonxProjectId": "PROJECT_ID", - "watsonxCreds": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", - "watsonxApiVersion": "2023-05-29", - "provider": "watsonx" + "provider": "watsonx", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14" } ] } ``` -`watsonxAPIVersion` is optional and defaults to the latest version. +`apiVersion` is optional and defaults to the latest version. + + +If you are using a custom deployment endpoint, set `deploymentID` to the model's deployment ID. You can find it in the watsonx.ai Prompt Lab UI by selecting the corresponding model and opening the `` tab on the right, which will display the endpoint's URL containing the deployment ID. + +```json title="~/.continue/config.json" +{ + "models": [ + { + "model": "model ID", + "title": "watsonx - Model Name", + "provider": "watsonx", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14", + "deploymentId": "DEPLOYMENT_ID" + } + ] +} +``` ### Configuration Options -Add the full watsonx URL to `watsonxFullUrl` if you are using a custom endpoint. When `watsonxFullUrl` is set, `watsonxUrl` and `watsonxApiVersion` are ignored. +Make sure to specify a template name, such as `granite` or `llama3`, and to set the `contextLength` to the model's context window size. +You can also configure generation parameters, such as temperature, topP, topK, frequency penalty, and stop sequences: ```json title="~/.continue/config.json" { "models": [ { - "model": "model ID", - "title": "watsonx - Model Name", - "watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", - "watsonxProjectId": "PROJECT_ID", - "watsonxCreds": "API_KEY", - "watsonxApiVersion": "2023-05-29", + "model": "ibm/granite-20b-code-instruct", + "title": "Granite Code 20b", "provider": "watsonx", - "watsonxFullUrl": "https://us-south.ml.cloud.ibm.com/m1/v1/text/generation" + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14", + "template": "granite", + "contextLength": 8000, + "completionOptions": { + "temperature": 0.1, + "topP": 0.3, + "topK": 20, + "maxTokens": 2000, + "frequencyPenalty": 1.1, + "stop": [ + "Question:", + "\n\n\n" + ] + } } ] } ``` -## Usage +## Tab Auto Complete Model -![usage-gif](../assets/watsonx2.gif) +Granite models are recommended for tab auto complete. The configuration is similar to that of the chat models: +```json title="~/.continue/config.json" +{ + "tabAutocompleteModel": { + "model": "ibm/granite-8b-code-instruct", + "title": "Granite Code 8b", + "provider": "watsonx", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14", + "contextLength": 4000 + } +} +``` + +## Embeddings Model + +To view the list of available embeddings models, visit [this page](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models-embed.html?context=wx&pos=2#ibm-provided). +```json title="~/.continue/config.json +{ + "embeddingsProvider": { + "provider": "watsonx", + "model": "ibm/slate-30m-english-rtrvr-v2", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14" + } +} +``` diff --git a/docs/docs/customize/model-providers/top-level/anthropic.md b/docs/docs/customize/model-providers/top-level/anthropic.md index c4bb24a4c..9333a8e84 100644 --- a/docs/docs/customize/model-providers/top-level/anthropic.md +++ b/docs/docs/customize/model-providers/top-level/anthropic.md @@ -19,7 +19,7 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. { "title": "Claude 3.5 Sonnet", "provider": "anthropic", - "model": "claude-3-5-sonnet-20240620", + "model": "claude-3-5-sonnet-latest", "apiKey": "[API_KEY]" } ] @@ -61,7 +61,7 @@ To enable caching of the system message and the turn-by-turn conversation, updat }, "title": "Anthropic", "provider": "anthropic", - "model": "claude-3-5-sonnet-20240620", + "model": "claude-3-5-sonnet-latest", "apiKey": "[API_KEY]" } ] diff --git a/docs/docs/customize/model-providers/top-level/azure.md b/docs/docs/customize/model-providers/top-level/azure.md index 814a056ea..edd890d37 100644 --- a/docs/docs/customize/model-providers/top-level/azure.md +++ b/docs/docs/customize/model-providers/top-level/azure.md @@ -3,6 +3,14 @@ title: Azure OpenAI slug: ../azure --- +Azure OpenAI is a cloud-based service that provides access to OpenAI's models, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure OpenAI resource in the [Azure portal](https://portal.azure.com). + +:::info + +For details on model setup, see [General model configuration](#general-model-configuration). + +::: + ## Chat model We recommend configuring **GPT-4o** as your chat model. @@ -13,10 +21,8 @@ We recommend configuring **GPT-4o** as your chat model. "provider": "azure", "model": "gpt-4o", "apiBase": "", - "engine": "", - "apiVersion": "", - "apiType": "azure", - "apiKey": "" + "deployment": "", + "apiKey": "" // If you use subscription key, try using Azure gateway to rename it apiKey }] ``` @@ -36,11 +42,10 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. ```json title="config.json" "embeddingsProvider": { - "provider": "azure", + "provider": "openai", "model": "text-embedding-3-large", "apiBase": "", - "engine": "", - "apiVersion": "", + "deployment": "", "apiType": "azure", "apiKey": "" } @@ -64,20 +69,19 @@ You need to apply for access to the Azure OpenAI service. Response times are typ ## General model configuration -Azure OpenAI requires a handful of additional parameters to be configured, such as a model engine and API version. +Azure OpenAI requires a handful of additional parameters to be configured, such as a deployment name and API base URL. To find this information in _Azure AI Studio_, first select the model that you would like to connect. Then visit _Endpoint_ > _Target URI_. -For example, a Target URI of `` would map to the following: +For example, a Target URI of `https://just-an-example.openai.azure.com/openai/deployments/gpt-4o-july/chat/completions?api-version=2023-03-15-preview` would map to the following: ```json { "title": "GPT-4o Azure", "model": "gpt-4o", - "provider": "azure", + "provider": "openai", "apiBase": "https://just-an-example.openai.azure.com", - "apiType": "azure", - "engine": "gpt-4o", + "deployment": "gpt-4o-july", "apiVersion": "2023-03-15-preview", "apiKey": "" } diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index 14cc70211..8d46c5ad9 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -3,6 +3,8 @@ title: Amazon Bedrock slug: ../bedrock --- +Amazon Bedrock is a fully managed service on AWS that provides access to foundation models from various AI companies through a single API. + ## Chat model We recommend configuring **Claude 3.5 Sonnet** as your chat model. diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md index 7a6a0776a..ae97d30c3 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ b/docs/docs/customize/model-providers/top-level/ollama.md @@ -3,6 +3,8 @@ title: Ollama slug: ../ollama --- +Ollama is an open-source tool that allows to run large language models (LLMs) locally on their own computers. To use Ollama, you can install it [here](https://ollama.ai/download) and download the model you want to run with the `ollama run` command. + ## Chat model We recommend configuring **Llama3.1 8B** as your chat model. diff --git a/docs/docs/customize/model-providers/top-level/openai.md b/docs/docs/customize/model-providers/top-level/openai.md index d594f4f39..6b31b0b22 100644 --- a/docs/docs/customize/model-providers/top-level/openai.md +++ b/docs/docs/customize/model-providers/top-level/openai.md @@ -63,6 +63,7 @@ OpenAI compatible servers - [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) +- [BerriAI/litellm](https://github.com/BerriAI/litellm) OpenAI compatible APIs diff --git a/docs/docs/customize/model-providers/more/mistral-vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md similarity index 52% rename from docs/docs/customize/model-providers/more/mistral-vertexai.md rename to docs/docs/customize/model-providers/top-level/vertexai.md index c4590e41b..1778ce3c6 100644 --- a/docs/docs/customize/model-providers/more/mistral-vertexai.md +++ b/docs/docs/customize/model-providers/top-level/vertexai.md @@ -1,6 +1,6 @@ --- -title: Mistral Vertex AI -slug: ../mistral-vertexai +title: Vertex AI +slug: ../vertexai --- :::info @@ -11,46 +11,55 @@ You need to enable the [Vertex AI API](https://console.cloud.google.com/marketpl ## Chat model -We recommend configuring **Mistral Large** as your chat model. +We recommend configuring **Claude 3.5 Sonnet** as your chat model. ```json title="config.json" { "models": [ { - "title": "Mistral Large (Vertex AI)", - "provider": "mistral-vertexai", - "model": "mistral-large", + "title": "Claude 3.5 Sonnet", + "provider": "vertexai", + "model": "claude-3-5-sonnet-20240620", "projectId": "[PROJECT_ID]", - "region": "us-central1" + "region": "us-east5" } ] } ``` + ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. +We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. ```json title="config.json" { "tabAutocompleteModel": { "title": "Codestral (Vertex AI)", - "provider": "mistral-vertexai", + "provider": "vertexai", "model": "codestral", "projectId": "[PROJECT_ID]", "region": "us-central1" } } ``` - ## Embeddings model -Mistral Vertex AI currently does not offer any embeddings models. +We recommend configuring **text-embedding-004** as your embeddings model. -[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "vertexai", + "model": "text-embedding-004", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` ## Reranking model -Mistral Vertex AI currently does not offer any reranking models. +Vertex AI currently does not offer any reranking models. [Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-providers/top-level/xAI.md b/docs/docs/customize/model-providers/top-level/xAI.md new file mode 100644 index 000000000..fbdfa83ad --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/xAI.md @@ -0,0 +1,53 @@ +--- +title: xAI +slug: ../xai +--- + +:::info + +You can get an API key from the [xAI console](https://console.x.ai/) + +::: + +## Chat model + +We recommend configuring **grok-beta** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Grok Beta", + "provider": "xAI", + "model": "grok-beta", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +xAI currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +xAI currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. + +## Reranking model + +xAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. + +## Legacy Completions + +To force usage of `chat/completions` instead of `completions` endpoint you can set + +```json +"useLegacyCompletionsEndpoint": false +``` diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md index a7eaa5e63..64d39c893 100644 --- a/docs/docs/customize/model-types/autocomplete.md +++ b/docs/docs/customize/model-types/autocomplete.md @@ -11,6 +11,6 @@ In Continue, these models are used to display inline [Autocomplete](../../autoco ## Recommended Autocomplete models -If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Mistral Vertex AI](../model-providers/more/mistral-vertexai.md#autocomplete-model). +If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Vertex AI](../model-providers/top-level/vertexai.md#autocomplete-model). If you want to run a model locally, we recommend `Starcoder2-3B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md index c32468967..882c5da79 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -9,6 +9,14 @@ An "embeddings model" is trained to convert a piece of text into a vector, which In Continue, embeddings are generated during indexing and then used by [@Codebase](../deep-dives/codebase.md) to perform similarity search over your codebase. +:::info[Default model (VS Code only)] +`transformers.js` is used as a default embeddings model in VS Code. In JetBrains, there currently is no default. +::: + +:::info[Free Trial] +The free trial supports embeddings (provider: `free-trial`) +::: + ## Recommended embedding models If you have the ability to use any model, we recommend `voyage-code-2`, which is listed below along with the rest of the options for embeddings models. @@ -35,7 +43,7 @@ See [here](../model-providers/top-level/ollama.md#embeddings-model) for instruct ### Transformers.js (currently VS Code only) -[Transformers.js](https://huggingface.co/docs/transformers.js/index) is a JavaScript port of the popular [Transformers](https://huggingface.co/transformers/) library. It allows embeddings to be calculated entirely locally. The model used is `all-MiniLM-L6-v2`, which is shipped alongside the Continue extension and used as the default when you have not explicitly configured an embeddings provider. +[Transformers.js](https://huggingface.co/docs/transformers.js/index) is a JavaScript port of the popular [Transformers](https://huggingface.co/transformers/) library. It allows embeddings to be calculated entirely locally. The model used is `all-MiniLM-L6-v2`, which is shipped alongside the Continue extension. ```json title="config.json" { @@ -69,3 +77,27 @@ See [here](../model-providers/more/cohere.md#embeddings-model) for instructions ### Gemini See [here](../model-providers/top-level/gemini.md#embeddings-model) for instructions on how to use Gemini for embeddings. + +### Vertex + +See [here](../model-providers/top-level/vertexai.md#embeddings-model) for instructions on how to use Vertex for embeddings. + +### Mistral + +See [here](../model-providers/top-level/mistral.md#embeddings-model) for instructions on how to use Mistral for embeddings. + +### NVIDIA + +See [here](../model-providers/more/nvidia.md#embeddings-model) for instructions on how to use NVIDIA for embeddings. + +### Bedrock + +See [here](../model-providers/top-level/bedrock.md#embeddings-model) for instructions on how to use Bedrock for embeddings. + +### WatsonX + +See [here](../model-providers/more/watsonx.md#embeddings-model) for instructions on how to use WatsonX for embeddings. + +### LMStudio + +See [here](../model-providers/more/lmstudio.md#embeddings-model) for instructions on how to use LMStudio for embeddings. diff --git a/docs/docs/customize/model-types/reranking.md b/docs/docs/customize/model-types/reranking.md index 4aceade4a..a87918cb2 100644 --- a/docs/docs/customize/model-types/reranking.md +++ b/docs/docs/customize/model-types/reranking.md @@ -72,6 +72,7 @@ The `"modelTitle"` field must match one of the models in your "models" array in "name": "huggingface-tei", "params": { "apiBase": "http://localhost:8080", + "apiKey": "", "truncate": true, "truncation_direction": "Right" } diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index 04183a427..4f231d55c 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -8,16 +8,16 @@ Continue can be deeply customized. This is primarily accomplished by editing a l ## Getting started -To open `config.json`, click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can use IntelliSense to see the available options as you type, or you can check the [full reference](./config.mdx). +To open `config.json`, click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or you can check the [full reference](./deep-dives/ways-to-configure.md). When you save `config.json`, Continue will automatically refresh to take into account your changes. ## Per-workspace configuration -If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. It has the same [definition](./config.mdx) as `config.json`, and will automatically be applied on top of the local config.json. +If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. It has the same [definition](./deep-dives/ways-to-configure.md) as `config.json`, and will automatically be applied on top of the local config.json. ## Programmatic configuration `config.json` can handle the vast majority of necessary configuration, so we recommend using it whenever possible. However, if you need to programmatically configure Continue, you can use `config.ts`, which is located at `~/.continue/config.ts` (MacOS / Linux) or `%USERPROFILE%\.continue\config.ts` (Windows). -For examples of how to use `config.ts`, see [writing custom slash commands](./tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](./tutorials/build-your-own-context-provider.md). \ No newline at end of file +For examples of how to use `config.ts`, see [writing custom slash commands](./tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](./tutorials/build-your-own-context-provider.md). diff --git a/docs/docs/customize/tutorials/llama3.1.md b/docs/docs/customize/tutorials/llama3.1.md index 1ad6a1dc9..2cec71cda 100644 --- a/docs/docs/customize/tutorials/llama3.1.md +++ b/docs/docs/customize/tutorials/llama3.1.md @@ -4,7 +4,7 @@ description: How to use Llama 3.1 with Continue keywords: [llama, meta, togetherai, ollama, replicate] --- -Continue makes it easy to code with the latest open-source models, including the entire Llama 3.1 family of models. +Continue makes it easy to code with the latest open-source models, including the entire Llama 3.1 family of models. Llama 3.2 models are also supported but not recommended for chat, because they are specifically designed to be small or multi-modal. If you haven't already installed Continue, you can do that [here for VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [here for JetBrains](https://plugins.jetbrains.com/plugin/22707-continue). For more general information on customizing Continue, read [our customization docs](../overview.md). diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index ac6f2ed4b..850c34b60 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -20,18 +20,18 @@ Edit is best used for small, quick changes such as: ## Highlight code and activate -Highlight the block of code you would like to modify, and press `cmd/ctrl + i` to activate the edit input. +Highlight the block of code you would like to modify, and press cmd/ctrl + i to activate the edit input. ## Describe code changes -Describe the changes you would like the model to make to your highlighted code. For edits, a good prompt should be relatively short and concise. For longer, more complex tasks, we recommend using [Chat](chat/how-to-use-it.md). +Describe the changes you would like the model to make to your highlighted code. For edits, a good prompt should be relatively short and concise. For longer, more complex tasks, we recommend using [Chat](../chat/how-to-use-it.md). ## Accept or reject changes Proposed changes appear as inline diffs within your highlighted text. -You can navigate through each proposed change, accepting or rejecting them using `cmd/ctrl + opt + y` (to accept) or `cmd/ctrl + opt + n` (to reject). +You can navigate through each proposed change, accepting or rejecting them using cmd/ctrl + opt + y (to accept) or cmd/ctrl + opt + n (to reject). -You can also accept or reject all changes at once using `cmd/ctrl + shift + enter` (to accept) or `cmd/ctrl + shift + delete` (to reject). +You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). -If you want to request a new suggestion for the same highlighted code section, you can use `cmd/ctrl + i` to re-prompt the model. +If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. diff --git a/docs/docs/edit/model-setup.md b/docs/docs/edit/model-setup.md index ce5e18e18..ded10c2a4 100644 --- a/docs/docs/edit/model-setup.md +++ b/docs/docs/edit/model-setup.md @@ -7,4 +7,4 @@ keywords: [edit, cmd l, model] By default, Edit uses the [same model as Chat](chat/model-setup.mdx) since we recommend a similar, 400B+ parameter model or one of the frontier model for code edits. -You can configure a different model to be used for edits by updating your [`config.json`](../customize/config.mdx). +You can configure a different model to be used for edits by updating your [`config.json`](../reference.md). diff --git a/docs/docs/getting-started/install.md b/docs/docs/getting-started/install.md index da04e8468..e894596fb 100644 --- a/docs/docs/getting-started/install.md +++ b/docs/docs/getting-started/install.md @@ -7,9 +7,7 @@ keywords: [install, installation, getting started, vs code, jetbrains] ## VS Code 1. Click `Install` on the [Continue extension page in the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Continue.continue) - 2. This will open the Continue extension page in VS Code, where you will need to click `Install` again - 3. The Continue logo will appear on the left sidebar. For a better experience, move Continue to the right sidebar ![move-to-right-sidebar](/img/move-to-right-sidebar.gif) @@ -20,10 +18,8 @@ If you have any problems, see the [troubleshooting guide](troubleshooting.md) or ## JetBrains -1. Open your JetBrains IDE and open **Settings** using `cmd/ctrl + ,` - +1. Open your JetBrains IDE and open **Settings** using cmd/ctrl + , 2. Select **Plugins** on the sidebar and search for "Continue" in the marketplace - 3. Click `Install`, which will cause the Continue logo to show up on the right toolbar ![jetbrains-getting-started.png](/img/jetbrains-getting-started.png) diff --git a/docs/docs/reference.md b/docs/docs/reference.md new file mode 100644 index 000000000..391273943 --- /dev/null +++ b/docs/docs/reference.md @@ -0,0 +1,449 @@ +--- +title: Reference +description: Reference for the Continue _config.json_ configuration file +keywords: [config, config_schema.json, json] +--- + +Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). + +**All properties at all levels are optional unless explicitly marked required** + +### `models` + +Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md). +Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. + +**Properties:** + +- `title` (**required**): The title to assign to your model, shown in dropdowns, etc. +- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions. +- `model` (**required**): The name of the model, used for prompt template auto-detection. +- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere. +- `apiBase`: The base URL of the LLM API. +- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048). +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. +- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions. +- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt). +- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override. +- `systemMessage`: A system message that will precede responses from the LLM. +- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override. +- `apiType`: Specifies the type of API (`openai` or `azure`). +- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`). +- `engine`: Engine for Azure OpenAI requests. +- `capabilities`: Override auto-detected capabilities: + - `uploadImage`: Boolean indicating if the model supports image uploads. + +_(AWS Only)_ + +- `profile`: AWS security profile for authorization. +- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider). +- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`). + +Example: + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "AUTODETECT" + }, + { + "model": "gpt-4o", + "contextLength": 128000, + "title": "GPT-4o", + "provider": "openai", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +### `tabAutocompleteModel` + +Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model. + +Example + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "My Starcoder", + "provider": "ollama", + "model": "starcoder2:3b" + } +} +``` + +### `tabAutocompleteOptions` + +Specifies options for tab autocompletion behavior. + +**Properties:** + +- `disable`: If `true`, disables tab autocomplete (default: `false`). +- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. +- `useFileSuffix`: If `true`, includes file suffix in the prompt. +- `maxPromptTokens`: Maximum number of tokens for the prompt. +- `debounceDelay`: Delay (in ms) before triggering autocomplete. +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. +- `prefixPercentage`: Percentage of input for prefix. +- `template`: Template string for autocomplete, using Mustache templating. +- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). +- `useCache`: If `true`, caches completions. +- `onlyMyCode`: If `true`, only includes code within the repository. +- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). +- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. + +Example + +```json title="config.json" +{ + "tabAutocompleteOptions": { + "debounceDelay": 500, + "maxPromptTokens": 1500, + "disableInFiles": ["*.md"] + } +} +``` + +### `embeddingsProvider` + +Embeddings model settings - the model used for @Codebase and @docs. + +**Properties:** + +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `free-trial`, `gemini`, etc +- `model`: Model name for embeddings. +- `apiKey`: API key for the provider. +- `apiBase`: Base URL for API requests. +- `requestOptions`: Additional HTTP request settings specific to the embeddings provider. +- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. + +(AWS ONLY) + +- `region`: Specifies the region hosting the model. +- `profile`: AWS security profile. + +Example: + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-ada-002", + "apiKey": "", + "maxChunkSize": 256, + "maxBatchSize": 5 + } +} +``` + +### `completionOptions` + +Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_. + +**Properties:** + +- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`). +- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs. +- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. +- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. +- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. +- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. +- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). +- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. +- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). +- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. +- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). + +Example + +```json title="config.json" +{ + "completionOptions": { + "stream": false, + "temperature": 0.5 + } +} +``` + +### `requestOptions` + +Default HTTP request options that apply to all models and context providers, unless overridden at the model level. + +**Properties:** + +- `timeout`: Timeout for each request to the LLM (default: 7200 seconds). +- `verifySsl`: Whether to verify SSL certificates for requests. +- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths) +- `proxy`: Proxy URL to use for HTTP requests. +- `headers`: Custom headers for HTTP requests. +- `extraBodyProperties`: Additional properties to merge with the HTTP request body. +- `noProxy`: List of hostnames that should bypass the specified proxy. +- `clientCertificate`: Client certificate for HTTP requests. + + - `cert`: Path to the client certificate file. + - `key`: Path to the client certificate key file. + - `passphrase`: Optional passphrase for the client certificate key file. + +Example + +```json title="config.json" +{ + "requestOptions": { + "headers": { + "X-Auth-Token": "xxx" + } + } +} +``` + +### `reranker` + +Configuration for the reranker model used in response ranking. + +**Properties:** + +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `params`: + - `model`: Model name + - `apiKey`: Api key + +Example + +```json title="config.json" +{ + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" + } + } +} +``` + +### `docs` + +List of documentation sites to index. + +**Properties:** + +- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. +- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs +- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL +- `maxDepth`: Maximum depth for crawling. Default `3` +- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). + +Example + +```json title="config.json" +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] +``` + +### `analytics` + +Configuration for analytics tracking. + +**Properties:** + +- `provider`: Analytics provider (`"posthog"` or `"logstash"`). +- `url`: URL for analytics data. +- `clientKey`: Client key for analytics. + +### `slashCommands` + +Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined. + +**Properties:** + +- `name`: The command name. Options include "issue", "share", "cmd", "edit", "comment", "http", "commit", and "review". +- `description`: Brief description of the command. +- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. +- `params`: Additional parameters to configure command behavior (command-specific - see code for command) + +Example: + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message" + }, + { + "name": "comment", + "description": "Write comments for the selected code" + }, + { + "name": "share", + "description": "Export this session as markdown" + }, + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +### `customCommands` + +User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. + +**Properties:** + +- `name`: The name of the custom command. +- `prompt`: Text prompt for the command. +- `description`: Brief description explaining the command's function. + +Example: + +```json title="config.json" +{ + "customCommands": [ + { + "name": "test", + "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", + "description": "Write unit tests for highlighted code" + } + ] +} +``` + +### `contextProviders` + +List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`. + +**Properties:** + +- `name`: Name of the context provider, e.g. `docs` or `web` +- `params`: A context-provider-specific record of params to configure the context behavior + +Example + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "code", + "params": {} + }, + { + "name": "docs", + "params": {} + }, + { + "name": "diff", + "params": {} + }, + { + "name": "open", + "params": {} + } + ] +} +``` + +### `disableSessionTitles` + +Prevents generating summary titles for each chat session when set to `true`. + +### `ui` + +Customizable UI settings to control interface appearance and behavior. + +**Properties:** + +- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. +- `fontSize`: Specifies font size for UI elements. +- `displayRawMarkdown`: If `true`, shows raw markdown in responses. +- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. + +Example: + +```json title="config.json" +{ + "ui": { + "codeBlockToolbarPosition": "bottom", + "fontSize": 14, + "displayRawMarkdown": false + } +} +``` + +### `allowAnonymousTelemetry` + +When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. + +### `userToken` + +An optional token that identifies the user, primarily for authenticated services. + +### `systemMessage` + +Defines a system message that appears before every response from the language model, providing guidance or context. + +### `disableIndexing` + +Prevents indexing of the codebase, useful primarily for debugging purposes. + +### `experimental` + +Several experimental config parameters are available, as described below: + +`experimental`: + +- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= +- `modelRoles`: + - `inlineEdit`: Model title for inline edits. + - `applyCodeBlock`: Model title for applying code blocks. + - `repoMapFileSelection`: Model title for repo map selections. +- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`. +- `promptPath`: Change the path to custom prompt files from the default ".prompts" +- `quickActions`: Array of custom quick actions + - `title` (**required**): Display title for the quick action. + - `prompt` (**required**): Prompt for quick action. + - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. +- `contextMenuPrompts`: + - `comment`: Prompt for commenting code. + - `docstring`: Prompt for adding docstrings. + - `fix`: Prompt for fixing code. + - `optimize`: Prompt for optimizing code. + - `fixGrammar`: Prompt for fixing grammar or spelling. +- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.. + +Example + +```json title="config.json" +{ + "experimental": { + "modelRoles": { + "inlineEdit": "Edit Model" + }, + "promptPath": "custom/.prompts", + "quickActions": [ + { + "title": "Tags", + "prompt": "Return a list of any function and class names from the included code block", + "sendToChat": true + } + ], + "contextMenuPrompts": { + "fixGrammar": "Fix grammar in the above but allow for typos." + }, + "readResponseTTS": false, + "useChromiumForDocsCrawling": true + } +} +``` diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index a72a6e77a..8e7152d01 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -46,6 +46,6 @@ To opt out, change the value of `allowAnonymousTelemetry` to `false`. Alternativ ### 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). +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/docs/troubleshooting.md b/docs/docs/troubleshooting.md index d10d2c104..d4bbe69db 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -24,7 +24,7 @@ To solve many problems, the first step is reading the logs to find the relevant In order to view debug logs, which contain extra information, click the dropdown at the top that says "Default levels" and select "Verbose". ::: -1. `cmd+shift+p` (MacOS) / `ctrl+shift+p` (Windows) +1. cmd + shift + P for MacOS or ctrl + shift + P for Windows 2. Search for and then select "Developer: Toggle Developer Tools" 3. This will open the [Chrome DevTools window](https://developer.chrome.com/docs/devtools/) 4. Select the `Console` tab @@ -56,7 +56,7 @@ We are constantly making fixes and improvements to Continue, but the latest chan On JetBrains, the "pre-release" happens through their Early Access Program (EAP) channel. To download the latest EAP version, enable the EAP channel: -1. Open JetBrains settings (`cmd/ctrl + ,`) and go to "Plugins" +1. Open JetBrains settings (cmd/ctrl + ,) and go to "Plugins" 2. Click the gear icon at the top 3. Select "Manage Plugin Repositories..." 4. Add "[https://plugins.jetbrains.com/plugins/eap/list](https://plugins.jetbrains.com/plugins/eap/list)" to the list @@ -104,7 +104,7 @@ You may also set `requestOptions.caBundlePath` to an array of paths to multiple #### VS Code Proxy Settings -If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl+, to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. +If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl + , to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. #### code-server diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 5af3b8a2d..b4e5b7278 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -34,7 +34,7 @@ const config = { locales: ["en"], }, - themes: [["docusaurus-json-schema-plugin", {}]], + themes: [], presets: [ [ @@ -91,6 +91,13 @@ const config = { label: "Customize", href: "/customize/overview", }, + { + type: "docSidebar", + sidebarId: "customizingSidebar", + position: "left", + label: "Reference", + href: "/reference", + }, { to: "https://github.com/continuedev/continue", label: "GitHub", @@ -230,7 +237,7 @@ const config = { from: "/changelog", }, { - to: "/customize/config", + to: "/reference", from: ["/customization/code-config", "/reference/config"], }, { diff --git a/docs/package-lock.json b/docs/package-lock.json index 7b89d26f0..756266105 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -13,7 +13,6 @@ "@docusaurus/preset-classic": "^3.5.2", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", - "docusaurus-json-schema-plugin": "^1.11.0", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" @@ -3145,70 +3144,6 @@ "micromark-util-symbol": "^1.0.1" } }, - "node_modules/@stoplight/json": { - "version": "3.21.0", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.21.0.tgz", - "integrity": "sha512-5O0apqJ/t4sIevXCO3SBN9AHCEKKR/Zb4gaj7wYe5863jme9g02Q0n/GhM7ZCALkL+vGPTe4ZzTETP8TFtsw3g==", - "dependencies": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - }, - "engines": { - "node": ">=8.3.0" - } - }, - "node_modules/@stoplight/json-ref-resolver": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/@stoplight/json-ref-resolver/-/json-ref-resolver-3.1.6.tgz", - "integrity": "sha512-YNcWv3R3n3U6iQYBsFOiWSuRGE5su1tJSiX6pAPRVk7dP0L7lqCteXGzuVRQ0gMZqUl8v1P0+fAKxF6PLo9B5A==", - "dependencies": { - "@stoplight/json": "^3.21.0", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^12.3.0 || ^13.0.0", - "@types/urijs": "^1.19.19", - "dependency-graph": "~0.11.0", - "fast-memoize": "^2.5.2", - "immer": "^9.0.6", - "lodash": "^4.17.21", - "tslib": "^2.6.0", - "urijs": "^1.19.11" - }, - "engines": { - "node": ">=8.3.0" - } - }, - "node_modules/@stoplight/ordered-object-literal": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@stoplight/ordered-object-literal/-/ordered-object-literal-1.0.5.tgz", - "integrity": "sha512-COTiuCU5bgMUtbIFBuyyh2/yVVzlr5Om0v5utQDgBCuQUOPgU1DwoffkTfg4UBQOvByi5foF4w4T+H9CoRe5wg==", - "engines": { - "node": ">=8" - } - }, - "node_modules/@stoplight/path": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@stoplight/path/-/path-1.3.2.tgz", - "integrity": "sha512-lyIc6JUlUA8Ve5ELywPC8I2Sdnh1zc1zmbYgVarhXIp9YeAB0ReeqmGEOWNtlHkbP2DAA1AL65Wfn2ncjK/jtQ==", - "engines": { - "node": ">=8" - } - }, - "node_modules/@stoplight/types": { - "version": "13.20.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.20.0.tgz", - "integrity": "sha512-2FNTv05If7ib79VPDA/r9eUet76jewXFH2y2K5vuge6SXbRHtWBhcaRmu+6QpF4/WRNoJj5XYRSwLGXDxysBGA==", - "dependencies": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - }, - "engines": { - "node": "^12.20 || >=14.13" - } - }, "node_modules/@svgr/babel-plugin-add-jsx-attribute": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-8.0.0.tgz", @@ -3540,9 +3475,10 @@ } }, "node_modules/@types/estree": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", - "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==" + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "license": "MIT" }, "node_modules/@types/estree-jsx": { "version": "1.0.3", @@ -3802,11 +3738,6 @@ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.2.tgz", "integrity": "sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ==" }, - "node_modules/@types/urijs": { - "version": "1.19.25", - "resolved": "https://registry.npmjs.org/@types/urijs/-/urijs-1.19.25.tgz", - "integrity": "sha512-XOfUup9r3Y06nFAZh3WvO0rBU4OtlfPB/vgxpjg+NRdGU6CN6djdc6OEiH+PcqHCY6eFLo9Ista73uarf4gnBg==" - }, "node_modules/@types/ws": { "version": "8.5.10", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.10.tgz", @@ -3834,145 +3765,162 @@ "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==" }, "node_modules/@webassemblyjs/ast": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.6.tgz", - "integrity": "sha512-IN1xI7PwOvLPgjcf180gC1bqn3q/QaOCwYUahIOhbYUu8KA/3tw2RT/T0Gidi1l7Hhj5D/INhJxiICObqpMu4Q==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.13.1.tgz", + "integrity": "sha512-+Zp/YJMBws+tg2Nuy5jiFhwvPiSeIB0gPp1Ie/TyqFg69qJ/vRrOKQ7AsFLn3solq5/9ubkBjrGd0UcvFjFsYA==", + "license": "MIT", "dependencies": { - "@webassemblyjs/helper-numbers": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6" + "@webassemblyjs/helper-numbers": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1" } }, "node_modules/@webassemblyjs/floating-point-hex-parser": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.6.tgz", - "integrity": "sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==" + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.12.1.tgz", + "integrity": "sha512-0vqwjuCO3Sa6pO3nfplawORkL1GUgza/H1A62SdXHSFCmAHoRcrtX/yVG3f1LuMYW951cvYRcRt6hThhz4FnCQ==", + "license": "MIT" }, "node_modules/@webassemblyjs/helper-api-error": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.6.tgz", - "integrity": "sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==" + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.12.1.tgz", + "integrity": "sha512-czovmKZdRk4rYauCOuMV/EImC3qyfcqyJuOYyDRYR6PZSOW37VWe26fAZQznbvKjlwJdyxLl6mIfx47Cfz8ykw==", + "license": "MIT" }, "node_modules/@webassemblyjs/helper-buffer": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.6.tgz", - "integrity": "sha512-z3nFzdcp1mb8nEOFFk8DrYLpHvhKC3grJD2ardfKOzmbmJvEf/tPIqCY+sNcwZIY8ZD7IkB2l7/pqhUhqm7hLA==" + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.13.1.tgz", + "integrity": "sha512-J0gf97+D3CavG7aO5XmtwxRWMiMEuxQ6t8Aov8areSnyI5P5fM0HV0m8bE3iLfDQZBhxLCc15tRsFVOGyAJ0ng==", + "license": "MIT" }, "node_modules/@webassemblyjs/helper-numbers": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.6.tgz", - "integrity": "sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==", + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.12.1.tgz", + "integrity": "sha512-Vp6k5nXOMvI9dWJqDGCMvwAc8+G6tI2YziuYWqxk7XYnWHdxEJo19CGpqm/kRh86rJxwYANLGuyreARhM+C9lQ==", + "license": "MIT", "dependencies": { - "@webassemblyjs/floating-point-hex-parser": "1.11.6", - "@webassemblyjs/helper-api-error": "1.11.6", + "@webassemblyjs/floating-point-hex-parser": "1.12.1", + "@webassemblyjs/helper-api-error": "1.12.1", "@xtuc/long": "4.2.2" } }, "node_modules/@webassemblyjs/helper-wasm-bytecode": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.6.tgz", - "integrity": "sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==" + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.12.1.tgz", + "integrity": "sha512-flsRYmCqN2ZJmvAyNxZXPPFkwKoezeTUczytfBovql8cOjYTr6OTcZvku4UzyKFW0Kj+PgD+UaG8/IdX31EYWg==", + "license": "MIT" }, "node_modules/@webassemblyjs/helper-wasm-section": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.6.tgz", - "integrity": "sha512-LPpZbSOwTpEC2cgn4hTydySy1Ke+XEu+ETXuoyvuyezHO3Kjdu90KK95Sh9xTbmjrCsUwvWwCOQQNta37VrS9g==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.13.1.tgz", + "integrity": "sha512-lcVNbrM5Wm7867lmbU61l+R4dU7emD2X70f9V0PuicvsdVUS5vvXODAxRYGVGBAJ6rWmXMuZKjM0PoeBjAcm2A==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-buffer": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/wasm-gen": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-buffer": "1.13.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1", + "@webassemblyjs/wasm-gen": "1.13.1" } }, "node_modules/@webassemblyjs/ieee754": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.6.tgz", - "integrity": "sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==", + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.12.1.tgz", + "integrity": "sha512-fcrUCqE2dVldeVAHTWFiTiKMS9ivc5jOgB2c30zYOZnm3O54SWeMJWS/HXYK862we2AYHtf6GYuP9xG9J+5zyQ==", + "license": "MIT", "dependencies": { "@xtuc/ieee754": "^1.2.0" } }, "node_modules/@webassemblyjs/leb128": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.6.tgz", - "integrity": "sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==", + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.12.1.tgz", + "integrity": "sha512-jOU6pTFNf7aGm46NCrEU7Gj6cVuP55T7+kyo5TU/rCduZ5EdwMPBZwSwwzjPZ3eFXYFCmC5wZdPZN0ZWio6n4Q==", + "license": "Apache-2.0", "dependencies": { "@xtuc/long": "4.2.2" } }, "node_modules/@webassemblyjs/utf8": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.6.tgz", - "integrity": "sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==" + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.12.1.tgz", + "integrity": "sha512-zcZvnAY3/M28Of012dksIfC26qZQJlj2PQCCvxqlsRJHOYtasp+OvK8nRcg11TKzAAv3ja7Y0NEBMKAjH6ljnw==", + "license": "MIT" }, "node_modules/@webassemblyjs/wasm-edit": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.6.tgz", - "integrity": "sha512-Ybn2I6fnfIGuCR+Faaz7YcvtBKxvoLV3Lebn1tM4o/IAJzmi9AWYIPWpyBfU8cC+JxAO57bk4+zdsTjJR+VTOw==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.13.1.tgz", + "integrity": "sha512-YHnh/f4P4ggjPB+pcri8Pb2HHwCGK+B8qBE+NeEp/WTMQ7dAjgWTnLhXxUqb6WLOT25TK5m0VTCAKTYw8AKxcg==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-buffer": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/helper-wasm-section": "1.11.6", - "@webassemblyjs/wasm-gen": "1.11.6", - "@webassemblyjs/wasm-opt": "1.11.6", - "@webassemblyjs/wasm-parser": "1.11.6", - "@webassemblyjs/wast-printer": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-buffer": "1.13.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1", + "@webassemblyjs/helper-wasm-section": "1.13.1", + "@webassemblyjs/wasm-gen": "1.13.1", + "@webassemblyjs/wasm-opt": "1.13.1", + "@webassemblyjs/wasm-parser": "1.13.1", + "@webassemblyjs/wast-printer": "1.13.1" } }, "node_modules/@webassemblyjs/wasm-gen": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.6.tgz", - "integrity": "sha512-3XOqkZP/y6B4F0PBAXvI1/bky7GryoogUtfwExeP/v7Nzwo1QLcq5oQmpKlftZLbT+ERUOAZVQjuNVak6UXjPA==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.13.1.tgz", + "integrity": "sha512-AxWiaqIeLh3c1H+8d1gPgVNXHyKP7jDu2G828Of9/E0/ovVEsh6LjX1QZ6g1tFBHocCwuUHK9O4w35kgojZRqA==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/ieee754": "1.11.6", - "@webassemblyjs/leb128": "1.11.6", - "@webassemblyjs/utf8": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1", + "@webassemblyjs/ieee754": "1.12.1", + "@webassemblyjs/leb128": "1.12.1", + "@webassemblyjs/utf8": "1.12.1" } }, "node_modules/@webassemblyjs/wasm-opt": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.6.tgz", - "integrity": "sha512-cOrKuLRE7PCe6AsOVl7WasYf3wbSo4CeOk6PkrjS7g57MFfVUF9u6ysQBBODX0LdgSvQqRiGz3CXvIDKcPNy4g==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.13.1.tgz", + "integrity": "sha512-SUMlvCrfykC7dtWX5g4TSuMmWi9w9tK5kGIdvQMnLuvJfnFLsnAaF86FNbSBSAL33VhM/hOhx4t9o66N37IqSg==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-buffer": "1.11.6", - "@webassemblyjs/wasm-gen": "1.11.6", - "@webassemblyjs/wasm-parser": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-buffer": "1.13.1", + "@webassemblyjs/wasm-gen": "1.13.1", + "@webassemblyjs/wasm-parser": "1.13.1" } }, "node_modules/@webassemblyjs/wasm-parser": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.6.tgz", - "integrity": "sha512-6ZwPeGzMJM3Dqp3hCsLgESxBGtT/OeCvCZ4TA1JUPYgmhAx38tTPR9JaKy0S5H3evQpO/h2uWs2j6Yc/fjkpTQ==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.13.1.tgz", + "integrity": "sha512-8SPOcbqSb7vXHG+B0PTsJrvT/HilwV3WkJgxw34lmhWvO+7qM9xBTd9u4dn1Lb86WHpKswT5XwF277uBTHFikg==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-api-error": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/ieee754": "1.11.6", - "@webassemblyjs/leb128": "1.11.6", - "@webassemblyjs/utf8": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-api-error": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1", + "@webassemblyjs/ieee754": "1.12.1", + "@webassemblyjs/leb128": "1.12.1", + "@webassemblyjs/utf8": "1.12.1" } }, "node_modules/@webassemblyjs/wast-printer": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.6.tgz", - "integrity": "sha512-JM7AhRcE+yW2GWYaKeHL5vt4xqee5N2WcezptmgyhNS+ScggqcT1OtXykhAb13Sn5Yas0j2uv9tHgrjwvzAP4A==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.13.1.tgz", + "integrity": "sha512-q0zIfwpbFvaNkgbSzkZFzLsOs8ixZ5MSdTTMESilSAk1C3P8BKEWfbLEvIqyI/PjNpP9+ZU+/KwgfXx3T7ApKw==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/ast": "1.13.1", "@xtuc/long": "4.2.2" } }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", - "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==" + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "license": "BSD-3-Clause" }, "node_modules/@xtuc/long": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", - "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==" + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "license": "Apache-2.0" }, "node_modules/accepts": { "version": "1.3.8", @@ -4006,9 +3954,10 @@ } }, "node_modules/acorn": { - "version": "8.11.3", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", - "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", + "version": "8.14.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", + "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", + "license": "MIT", "bin": { "acorn": "bin/acorn" }, @@ -4016,14 +3965,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-import-assertions": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.9.0.tgz", - "integrity": "sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==", - "peerDependencies": { - "acorn": "^8" - } - }, "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", @@ -4435,20 +4376,21 @@ } }, "node_modules/body-parser": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", - "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", "dependencies": { "bytes": "3.1.2", - "content-type": "~1.0.4", + "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", "http-errors": "2.0.0", "iconv-lite": "0.4.24", "on-finished": "2.4.1", - "qs": "6.11.0", - "raw-body": "2.5.1", + "qs": "6.13.0", + "raw-body": "2.5.2", "type-is": "~1.6.18", "unpipe": "1.0.0" }, @@ -4461,6 +4403,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", "engines": { "node": ">= 0.8" } @@ -4469,6 +4412,7 @@ "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", "dependencies": { "ms": "2.0.0" } @@ -4476,7 +4420,8 @@ "node_modules/body-parser/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" }, "node_modules/bonjour-service": { "version": "1.2.1", @@ -4523,20 +4468,21 @@ } }, "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", "dependencies": { - "fill-range": "^7.0.1" + "fill-range": "^7.1.1" }, "engines": { "node": ">=8" } }, "node_modules/browserslist": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.3.tgz", - "integrity": "sha512-btwCFJVjI4YWDNfau8RhZ+B1Q/VLoUITrm3RlP6y1tYGWIOa+InuYiRGXUBXo8nA1qKmHMyLB/iVQg5TT4eFoA==", + "version": "4.24.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.2.tgz", + "integrity": "sha512-ZIc+Q62revdMcqC6aChtW4jz3My3klmCO1fEmINZY/8J3EpBg5/A/D0AKmBveUh6pgoeycoMkVMko84tuYS+Gg==", "funding": [ { "type": "opencollective", @@ -4551,11 +4497,12 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "dependencies": { - "caniuse-lite": "^1.0.30001646", - "electron-to-chromium": "^1.5.4", + "caniuse-lite": "^1.0.30001669", + "electron-to-chromium": "^1.5.41", "node-releases": "^2.0.18", - "update-browserslist-db": "^1.1.0" + "update-browserslist-db": "^1.1.1" }, "bin": { "browserslist": "cli.js" @@ -4614,13 +4561,19 @@ } }, "node_modules/call-bind": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz", - "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "license": "MIT", "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.1", - "set-function-length": "^1.1.1" + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -4666,9 +4619,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001655", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001655.tgz", - "integrity": "sha512-jRGVy3iSGO5Uutn2owlb5gR6qsGngTw9ZTb4ali9f3glshcNmJ2noam4Mo9zia5P9Dk3jNNydy7vQjuE5dQmfg==", + "version": "1.0.30001677", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001677.tgz", + "integrity": "sha512-fmfjsOlJUpMWu+mAAtZZZHz7UEwsUxIIvu1TJfO1HqFQvB/B+ii0xr9B5HpbZY/mC4XZ8SvjHJqtAY6pDPQEog==", "funding": [ { "type": "opencollective", @@ -4682,7 +4635,8 @@ "type": "github", "url": "https://github.com/sponsors/ai" } - ] + ], + "license": "CC-BY-4.0" }, "node_modules/ccount": { "version": "2.0.1", @@ -5114,6 +5068,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -5124,9 +5079,10 @@ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" }, "node_modules/cookie": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", - "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -5660,16 +5616,20 @@ } }, "node_modules/define-data-property": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", - "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", "dependencies": { - "get-intrinsic": "^1.2.1", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.0" + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" }, "engines": { "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/define-lazy-prop": { @@ -5721,18 +5681,11 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", "engines": { "node": ">= 0.8" } }, - "node_modules/dependency-graph": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/dependency-graph/-/dependency-graph-0.11.0.tgz", - "integrity": "sha512-JeMq7fEshyepOWDfcfHK06N3MhyPhz++vtqWhMT5O9A3K42rdsEDpfdVqjaqaAhsw6a+ZqeDvQVtD0hFHQWrzg==", - "engines": { - "node": ">= 0.6.0" - } - }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -5745,6 +5698,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", "engines": { "node": ">= 0.8", "npm": "1.2.8000 || >= 1.4.16" @@ -5831,22 +5785,6 @@ "node": ">=6" } }, - "node_modules/docusaurus-json-schema-plugin": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/docusaurus-json-schema-plugin/-/docusaurus-json-schema-plugin-1.11.0.tgz", - "integrity": "sha512-Nd2WCoO4+Ke0fDOltdlaLwGmseCRMBuDxZd+QsaPCwJbogvNggBIEqFwFpRxlW+rIOTqB7ayeZ0jS0SFHn27fA==", - "dependencies": { - "@stoplight/json-ref-resolver": "^3.1.5", - "monaco-editor": "^0.44.0", - "monaco-editor-webpack-plugin": "^7.0.1", - "react-monaco-editor": "^0.55.0" - }, - "peerDependencies": { - "@docusaurus/core": "^3.0.0", - "@docusaurus/theme-classic": "^3.0.0", - "react": ">=17 <= 18" - } - }, "node_modules/dom-converter": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.2.0.tgz", @@ -5950,12 +5888,14 @@ "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.13", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.13.tgz", - "integrity": "sha512-lbBcvtIJ4J6sS4tb5TLp1b4LyfCdMkwStzXPyAgVgTRAsep4bvrAGaBOP7ZJtQMNJpSQ9SqG4brWOroNaQtm7Q==" + "version": "1.5.52", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.52.tgz", + "integrity": "sha512-xtoijJTZ+qeucLBDNztDOuQBE1ksqjvNjvqFoST3nGC7fSpqJ+X6BdTBaY5BHG+IhWWmpc6b/KfpeuEDupEPOQ==", + "license": "ISC" }, "node_modules/emoji-regex": { "version": "9.2.2", @@ -5985,17 +5925,19 @@ } }, "node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", "engines": { "node": ">= 0.8" } }, "node_modules/enhanced-resolve": { - "version": "5.15.0", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.15.0.tgz", - "integrity": "sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg==", + "version": "5.17.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz", + "integrity": "sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==", + "license": "MIT", "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.2.0" @@ -6023,6 +5965,27 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.4.1.tgz", @@ -6223,6 +6186,7 @@ "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -6275,36 +6239,37 @@ } }, "node_modules/express": { - "version": "4.18.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", - "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", + "version": "4.21.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz", + "integrity": "sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ==", + "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.1", + "body-parser": "1.20.3", "content-disposition": "0.5.4", "content-type": "~1.0.4", - "cookie": "0.5.0", + "cookie": "0.7.1", "cookie-signature": "1.0.6", "debug": "2.6.9", "depd": "2.0.0", - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", - "finalhandler": "1.2.0", + "finalhandler": "1.3.1", "fresh": "0.5.2", "http-errors": "2.0.0", - "merge-descriptors": "1.0.1", + "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "2.4.1", "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", + "path-to-regexp": "0.1.10", "proxy-addr": "~2.0.7", - "qs": "6.11.0", + "qs": "6.13.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", - "send": "0.18.0", - "serve-static": "1.15.0", + "send": "0.19.0", + "serve-static": "1.16.2", "setprototypeof": "1.2.0", "statuses": "2.0.1", "type-is": "~1.6.18", @@ -6340,9 +6305,10 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, "node_modules/express/node_modules/path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", + "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==", + "license": "MIT" }, "node_modules/express/node_modules/range-parser": { "version": "1.2.1", @@ -6393,19 +6359,6 @@ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" }, - "node_modules/fast-memoize": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/fast-memoize/-/fast-memoize-2.5.2.tgz", - "integrity": "sha512-Ue0LwpDYErFbmNnZSF0UH6eImUwDmogUO1jyE+JbN2gsQz/jICm1Ve7t9QT0rNSsfJt+Hs4/S3GnsDVjL4HVrw==" - }, - "node_modules/fast-url-parser": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/fast-url-parser/-/fast-url-parser-1.1.3.tgz", - "integrity": "sha512-5jOCVXADYNuRkKFzNJ0dCCewsZiYo0dz8QNYljkOpFC6r2U4OBmKtvm/Tsuh4w1YYdDqDb31a8TVhBJ2OJKdqQ==", - "dependencies": { - "punycode": "^1.3.2" - } - }, "node_modules/fastq": { "version": "1.16.0", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.16.0.tgz", @@ -6521,9 +6474,10 @@ } }, "node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", "dependencies": { "to-regex-range": "^5.0.1" }, @@ -6532,12 +6486,13 @@ } }, "node_modules/finalhandler": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", - "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", "dependencies": { "debug": "2.6.9", - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "on-finished": "2.4.1", "parseurl": "~1.3.3", @@ -6552,6 +6507,7 @@ "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", "dependencies": { "ms": "2.0.0" } @@ -6559,7 +6515,8 @@ "node_modules/finalhandler/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" }, "node_modules/find-cache-dir": { "version": "4.0.0", @@ -6600,15 +6557,16 @@ } }, "node_modules/follow-redirects": { - "version": "1.15.5", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", - "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", "funding": [ { "type": "individual", "url": "https://github.com/sponsors/RubenVerborgh" } ], + "license": "MIT", "engines": { "node": ">=4.0" }, @@ -6778,6 +6736,7 @@ "version": "0.5.2", "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -6835,15 +6794,20 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", - "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "license": "MIT", "dependencies": { + "es-errors": "^1.3.0", "function-bind": "^1.1.2", "has-proto": "^1.0.1", "has-symbols": "^1.0.3", "hasown": "^2.0.0" }, + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -6902,7 +6866,8 @@ "node_modules/glob-to-regexp": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", - "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==" + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "license": "BSD-2-Clause" }, "node_modules/global-dirs": { "version": "3.0.1", @@ -7101,11 +7066,12 @@ } }, "node_modules/has-property-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", - "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", "dependencies": { - "get-intrinsic": "^1.2.2" + "es-define-property": "^1.0.0" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -7553,6 +7519,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", "dependencies": { "depd": "2.0.0", "inherits": "2.0.4", @@ -7583,9 +7550,10 @@ } }, "node_modules/http-proxy-middleware": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.6.tgz", - "integrity": "sha512-ya/UeJ6HVBYxrgYotAZo1KvPWlgB48kUJLDePFeneHsVujFaW5WNj2NgWCAE//B1Dl02BIfYlpNgBy8Kf8Rjmw==", + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz", + "integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==", + "license": "MIT", "dependencies": { "@types/http-proxy": "^1.17.8", "http-proxy": "^1.18.1", @@ -7640,6 +7608,7 @@ "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3" }, @@ -7947,6 +7916,7 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", "engines": { "node": ">=0.12.0" } @@ -8188,11 +8158,6 @@ "node": ">=6" } }, - "node_modules/jsonc-parser": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-2.2.1.tgz", - "integrity": "sha512-o6/yDBYccGvTz1+QFevz6l6OBZ2+fMVu2JZ9CIhzsYRX4mjaK5IyX9eldUdCmga16zlgQxyrj5pt9kzuj2C02w==" - }, "node_modules/jsonfile": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", @@ -8784,6 +8749,7 @@ "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -8800,9 +8766,13 @@ } }, "node_modules/merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, "node_modules/merge-stream": { "version": "2.0.0", @@ -10497,11 +10467,12 @@ ] }, "node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", "dependencies": { - "braces": "^3.0.2", + "braces": "^3.0.3", "picomatch": "^2.3.1" }, "engines": { @@ -10512,6 +10483,7 @@ "version": "1.6.0", "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", "bin": { "mime": "cli.js" }, @@ -10599,23 +10571,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/monaco-editor": { - "version": "0.44.0", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.44.0.tgz", - "integrity": "sha512-5SmjNStN6bSuSE5WPT2ZV+iYn1/yI9sd4Igtk23ChvqB7kDk9lZbB9F5frsuvpB+2njdIeGGFf2G4gbE6rCC9Q==" - }, - "node_modules/monaco-editor-webpack-plugin": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/monaco-editor-webpack-plugin/-/monaco-editor-webpack-plugin-7.1.0.tgz", - "integrity": "sha512-ZjnGINHN963JQkFqjjcBtn1XBtUATDZBMgNQhDQwd78w2ukRhFXAPNgWuacaQiDZsUr4h1rWv5Mv6eriKuOSzA==", - "dependencies": { - "loader-utils": "^2.0.2" - }, - "peerDependencies": { - "monaco-editor": ">= 0.31.0", - "webpack": "^4.5.0 || 5.x" - } - }, "node_modules/mrmime": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.0.tgz", @@ -10808,9 +10763,13 @@ } }, "node_modules/object-inspect": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", - "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -10849,6 +10808,7 @@ "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", "dependencies": { "ee-first": "1.1.1" }, @@ -11138,9 +11098,10 @@ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" }, "node_modules/path-to-regexp": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.8.0.tgz", - "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.9.0.tgz", + "integrity": "sha512-xIp7/apCFJuUHdDLWe8O1HIkb0kQrOMb/0u6FXQjemHn/ii5LrIzU6bdECnsiTF/GjZkMEKg1xdiZwNqDYlZ6g==", + "license": "MIT", "dependencies": { "isarray": "0.0.1" } @@ -11932,11 +11893,6 @@ "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", "dev": true }, - "node_modules/punycode": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", - "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==" - }, "node_modules/pupa": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/pupa/-/pupa-3.1.0.tgz", @@ -11952,11 +11908,12 @@ } }, "node_modules/qs": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", - "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.0.4" + "side-channel": "^1.0.6" }, "engines": { "node": ">=0.6" @@ -12020,9 +11977,10 @@ } }, "node_modules/raw-body": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", - "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", "dependencies": { "bytes": "3.1.2", "http-errors": "2.0.0", @@ -12037,6 +11995,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", "engines": { "node": ">= 0.8" } @@ -12273,19 +12232,6 @@ "webpack": ">=4.41.1 || 5.x" } }, - "node_modules/react-monaco-editor": { - "version": "0.55.0", - "resolved": "https://registry.npmjs.org/react-monaco-editor/-/react-monaco-editor-0.55.0.tgz", - "integrity": "sha512-GdEP0Q3Rn1dczfKEEyY08Nes5plWwIYU4sWRBQO0+jsQWQsKMHKCC6+hPRwR7G/4aA3V/iU9jSmWPzVJYMVFSQ==", - "dependencies": { - "prop-types": "^15.8.1" - }, - "peerDependencies": { - "@types/react": ">=16 <= 18", - "monaco-editor": "^0.44.0", - "react": ">=16 <= 18" - } - }, "node_modules/react-router": { "version": "5.3.4", "resolved": "https://registry.npmjs.org/react-router/-/react-router-5.3.4.tgz", @@ -12872,15 +12818,11 @@ } ] }, - "node_modules/safe-stable-stringify": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-1.1.1.tgz", - "integrity": "sha512-ERq4hUjKDbJfE4+XtZLFPCDi8Vb1JqaxAPTxWFLBx8XcAlf9Bda/ZJdVezs/NAfsMQScyIlUMx+Yeu7P7rx5jw==" - }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" }, "node_modules/sax": { "version": "1.3.0", @@ -12993,9 +12935,10 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/send": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", - "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", "dependencies": { "debug": "2.6.9", "depd": "2.0.0", @@ -13019,6 +12962,7 @@ "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", "dependencies": { "ms": "2.0.0" } @@ -13026,17 +12970,29 @@ "node_modules/send/node_modules/debug/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } }, "node_modules/send/node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" }, "node_modules/send/node_modules/range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -13050,24 +13006,25 @@ } }, "node_modules/serve-handler": { - "version": "6.1.5", - "resolved": "https://registry.npmjs.org/serve-handler/-/serve-handler-6.1.5.tgz", - "integrity": "sha512-ijPFle6Hwe8zfmBxJdE+5fta53fdIY0lHISJvuikXB3VYFafRjMRpOffSPvCYsbKyBA7pvy9oYr/BT1O3EArlg==", + "version": "6.1.6", + "resolved": "https://registry.npmjs.org/serve-handler/-/serve-handler-6.1.6.tgz", + "integrity": "sha512-x5RL9Y2p5+Sh3D38Fh9i/iQ5ZK+e4xuXRd/pGbM4D13tgo/MGwbttUk8emytcr1YYzBYs+apnUngBDFYfpjPuQ==", + "license": "MIT", "dependencies": { "bytes": "3.0.0", "content-disposition": "0.5.2", - "fast-url-parser": "1.1.3", "mime-types": "2.1.18", "minimatch": "3.1.2", "path-is-inside": "1.0.2", - "path-to-regexp": "2.2.1", + "path-to-regexp": "3.3.0", "range-parser": "1.2.0" } }, "node_modules/serve-handler/node_modules/path-to-regexp": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-2.2.1.tgz", - "integrity": "sha512-gu9bD6Ta5bwGrrU8muHzVOBFFREpp2iRkVfhBJahwJ6p6Xw20SjT0MxLnwkjOibQmGSYhiUnf2FLe7k+jcFmGQ==" + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz", + "integrity": "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==", + "license": "MIT" }, "node_modules/serve-index": { "version": "1.9.1", @@ -13140,29 +13097,32 @@ } }, "node_modules/serve-static": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", - "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", "dependencies": { - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "parseurl": "~1.3.3", - "send": "0.18.0" + "send": "0.19.0" }, "engines": { "node": ">= 0.8.0" } }, "node_modules/set-function-length": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.0.tgz", - "integrity": "sha512-4DBHDoyHlM1IRPGYcoxexgh67y4ueR53FKV1yyxwFMY7aCqcN/38M1+SwZ/qJQ8iLv7+ck385ot4CcisOAPT9w==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", "dependencies": { - "define-data-property": "^1.1.1", + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.2", + "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.1" + "has-property-descriptors": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -13171,7 +13131,8 @@ "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" }, "node_modules/shallow-clone": { "version": "3.0.1", @@ -13233,13 +13194,18 @@ } }, "node_modules/side-channel": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "license": "MIT", "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -13439,6 +13405,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", "engines": { "node": ">= 0.8" } @@ -13810,6 +13777,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", "dependencies": { "is-number": "^7.0.0" }, @@ -13821,6 +13789,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", "engines": { "node": ">=0.6" } @@ -13880,6 +13849,7 @@ "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" @@ -13892,6 +13862,7 @@ "version": "1.52.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -13900,6 +13871,7 @@ "version": "2.1.35", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", "dependencies": { "mime-db": "1.52.0" }, @@ -14115,14 +14087,15 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", "engines": { "node": ">= 0.8" } }, "node_modules/update-browserslist-db": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", - "integrity": "sha512-EdRAaAyk2cUE1wOf2DkEhzxqOQvFOoRJFNS6NeyJ01Gp2beMRpBAINjM2iDXE3KCuKhwnvHIQCJm6ThL2Z+HzQ==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz", + "integrity": "sha512-R8UzCaa9Az+38REPiJ1tXlImTJXlVfgHZsglwBD/k6nj76ctsH1E3q4doGrukiLQd3sGQYu56r5+lo5r94l29A==", "funding": [ { "type": "opencollective", @@ -14137,9 +14110,10 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "dependencies": { - "escalade": "^3.1.2", - "picocolors": "^1.0.1" + "escalade": "^3.2.0", + "picocolors": "^1.1.0" }, "bin": { "update-browserslist-db": "cli.js" @@ -14234,11 +14208,6 @@ "node": ">=6" } }, - "node_modules/urijs": { - "version": "1.19.11", - "resolved": "https://registry.npmjs.org/urijs/-/urijs-1.19.11.tgz", - "integrity": "sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ==" - }, "node_modules/url-loader": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/url-loader/-/url-loader-4.1.1.tgz", @@ -14417,9 +14386,10 @@ } }, "node_modules/watchpack": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.0.tgz", - "integrity": "sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.2.tgz", + "integrity": "sha512-TnbFSbcOCcDgjZ4piURLCbJ3nJhznVh9kw6F6iokjiFPl8ONxe9A6nMDVXDiNbrSfLILs6vB07F7wLBrwPYzJw==", + "license": "MIT", "dependencies": { "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.1.2" @@ -14446,33 +14416,33 @@ } }, "node_modules/webpack": { - "version": "5.89.0", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.89.0.tgz", - "integrity": "sha512-qyfIC10pOr70V+jkmud8tMfajraGCZMBWJtrmuBymQKCrLTRejBI8STDp1MCyZu/QTdZSeacCQYpYNQVOzX5kw==", + "version": "5.96.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.96.1.tgz", + "integrity": "sha512-l2LlBSvVZGhL4ZrPwyr8+37AunkcYj5qh8o6u2/2rzoPc8gxFJkLj1WxNgooi9pnoc06jh0BjuXnamM4qlujZA==", + "license": "MIT", "dependencies": { - "@types/eslint-scope": "^3.7.3", - "@types/estree": "^1.0.0", - "@webassemblyjs/ast": "^1.11.5", - "@webassemblyjs/wasm-edit": "^1.11.5", - "@webassemblyjs/wasm-parser": "^1.11.5", - "acorn": "^8.7.1", - "acorn-import-assertions": "^1.9.0", - "browserslist": "^4.14.5", + "@types/eslint-scope": "^3.7.7", + "@types/estree": "^1.0.6", + "@webassemblyjs/ast": "^1.12.1", + "@webassemblyjs/wasm-edit": "^1.12.1", + "@webassemblyjs/wasm-parser": "^1.12.1", + "acorn": "^8.14.0", + "browserslist": "^4.24.0", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.15.0", + "enhanced-resolve": "^5.17.1", "es-module-lexer": "^1.2.1", "eslint-scope": "5.1.1", "events": "^3.2.0", "glob-to-regexp": "^0.4.1", - "graceful-fs": "^4.2.9", + "graceful-fs": "^4.2.11", "json-parse-even-better-errors": "^2.3.1", "loader-runner": "^4.2.0", "mime-types": "^2.1.27", "neo-async": "^2.6.2", "schema-utils": "^3.2.0", "tapable": "^2.1.1", - "terser-webpack-plugin": "^5.3.7", - "watchpack": "^2.4.0", + "terser-webpack-plugin": "^5.3.10", + "watchpack": "^2.4.1", "webpack-sources": "^3.2.3" }, "bin": { @@ -14526,9 +14496,10 @@ } }, "node_modules/webpack-dev-middleware": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-5.3.3.tgz", - "integrity": "sha512-hj5CYrY0bZLB+eTO+x/j67Pkrquiy7kWepMHmUMoPsmcUaeEnQJqFzHJOyxgWlq746/wUuA64p9ta34Kyb01pA==", + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-5.3.4.tgz", + "integrity": "sha512-BVdTqhhs+0IfoeAf7EoH5WE+exCmqGerHfDM0IL096Px60Tq2Mn9MAbnaGUe6HiMa41KMCYF19gyzZmBcq/o4Q==", + "license": "MIT", "dependencies": { "colorette": "^2.0.10", "memfs": "^3.4.3", @@ -14633,9 +14604,10 @@ } }, "node_modules/webpack-dev-server/node_modules/ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "license": "MIT", "engines": { "node": ">=10.0.0" }, @@ -14877,9 +14849,10 @@ } }, "node_modules/ws": { - "version": "7.5.9", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz", - "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==", + "version": "7.5.10", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", + "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", + "license": "MIT", "engines": { "node": ">=8.3.0" }, diff --git a/docs/package.json b/docs/package.json index 423c60bde..23af5df45 100644 --- a/docs/package.json +++ b/docs/package.json @@ -21,7 +21,6 @@ "@docusaurus/preset-classic": "^3.5.2", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", - "docusaurus-json-schema-plugin": "^1.11.0", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" @@ -46,4 +45,4 @@ "engines": { "node": ">=20.11.0" } -} +} \ No newline at end of file diff --git a/docs/sidebars.js b/docs/sidebars.js index 755d7f720..10db5727d 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -131,7 +131,6 @@ const sidebars = { }, ], }, - "customize/config", "customize/changelog", ], }; diff --git a/docs/src/css/custom.css b/docs/src/css/custom.css index da6a4abd6..f0b798f64 100644 --- a/docs/src/css/custom.css +++ b/docs/src/css/custom.css @@ -15,6 +15,14 @@ --ifm-color-primary-lightest: rgb(67, 31, 242); --ifm-code-font-size: 95%; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1); + --ifm-list-item-margin: 0.70rem; + /* These vars control the colors of the kbd tag 3d keycap */ + --kbd-keycap-bg-color: #ffffffce; + --kbd-keycap-border-color: #ccc; + --kbd-text-color: #ca3a18; + --kbd-shadow-color: #b4b4b4; + --kbd-shadow-color-outer: #9c9c9c; + --kbd-shadow-tint: rgba(0, 0, 0, .4); } /* For readability concerns, you should choose a lighter palette in dark mode. */ @@ -26,5 +34,34 @@ --ifm-color-primary-light: #59bc89ff; --ifm-color-primary-lighter: #59bc89ff; --ifm-color-primary-lightest: #59bc89ff; - --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3); + --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.4); + /* These vars control the colors of the kbd tag 3d keycap */ + --kbd-keycap-bg-color: #414859; + --kbd-keycap-border-color: #495265; + --kbd-text-color: #9ad7fa; + --kbd-shadow-color: #2e3341; + --kbd-shadow-color-outer: #373e4b; + --kbd-shadow-tint: rgba(173, 212, 247, 0.4); +} + +kbd { + display: inline-block; + padding: 0.3em 0.4em; + margin: 0.1em .4em; + font-family: var(--ifm-font-family-monospace); + font-size: .8rem; + font-weight: 500; + line-height: .8; + color: var(--kbd-text-color); + text-align: center; + white-space: nowrap; + background-color: var(--kbd-keycap-bg-color); + border: 1px solid var(--kbd-keycap-border-color); + border-radius: 0.3em; + box-shadow: + 0 2px 0 1px var(--kbd-shadow-color), + 0 3px 0 2px var(--kbd-shadow-color-outer), + 0 4px 6px var(--kbd-shadow-tint); + position: relative; + top: 0; } diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json deleted file mode 100644 index ce4e8e1a4..000000000 --- a/docs/static/schemas/config.json +++ /dev/null @@ -1,2920 +0,0 @@ -{ - "title": "config.json", - "$ref": "#/definitions/SerializedContinueConfig", - "definitions": { - "BaseCompletionOptions": { - "title": "BaseCompletionOptions", - "type": "object", - "properties": { - "stream": { - "title": "Stream", - "description": "Whether to stream the LLM response. Currently only respected by the 'anthropic' provider. Otherwise will always stream.", - "type": "boolean", - "default": true - }, - "temperature": { - "title": "Temperature", - "description": "The temperature of the completion.", - "type": "number" - }, - "topP": { - "title": "Top P", - "description": "The topP of the completion.", - "type": "number" - }, - "topK": { - "title": "Top K", - "description": "The topK of the completion.", - "type": "integer" - }, - "presencePenalty": { - "title": "Presence Penalty", - "description": "The presence penalty Aof the completion.", - "type": "number" - }, - "frequencePenalty": { - "title": "Frequency Penalty", - "description": "The frequency penalty of the completion.", - "type": "number" - }, - "mirostat": { - "title": "Mirostat", - "description": "Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0). Only available for Ollama, LM Studio, and llama.cpp providers", - "type": "number" - }, - "stop": { - "title": "Stop", - "description": "The stop tokens of the completion.", - "type": "array", - "items": { - "type": "string" - } - }, - "maxTokens": { - "title": "Max Tokens", - "description": "The maximum number of tokens to generate.", - "default": 600, - "type": "integer" - }, - "numThreads": { - "title": "Number of threads", - "description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)", - "type": "integer" - }, - "keepAlive": { - "title": "Ollama keep_alive", - "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", - "type": "integer" - } - } - }, - "ClientCertificateOptions": { - "title": "ClientCertificateOptions", - "type": "object", - "properties": { - "cert": { - "title": "Cert Path", - "description": "Path to the client certificate file", - "type": "string" - }, - "key": { - "title": "Key Path", - "description": "Path to the client certificate key file", - "type": "string" - }, - "passphrase": { - "title": "Passphrase", - "description": "Passphrase for the client certificate key file", - "type": "string" - } - }, - "required": ["cert", "key"] - }, - "RequestOptions": { - "title": "RequestOptions", - "type": "object", - "properties": { - "timeout": { - "title": "Timeout", - "description": "Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.", - "default": 7200, - "type": "integer" - }, - "verifySsl": { - "title": "Verify Ssl", - "description": "Whether to verify SSL certificates for requests.", - "type": "boolean" - }, - "caBundlePath": { - "title": "Ca Bundle Path", - "description": "Path to a custom CA bundle to use when making the HTTP request", - "anyOf": [ - { - "type": "string" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - }, - "proxy": { - "title": "Proxy", - "description": "Proxy URL to use when making the HTTP request", - "type": "string" - }, - "headers": { - "title": "Headers", - "description": "Headers to use when making the HTTP request", - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "extraBodyProperties": { - "title": "Extra Body Properties", - "description": "This object will be merged with the body when making the HTTP requests", - "type": "object" - }, - "noProxy": { - "title": "No Proxy", - "description": "A list of hostnames for which Continue should not use the proxy specified in requestOptions.proxy", - "type": "array", - "items": { - "type": "string" - } - }, - "clientCertificate": { - "title": "Client Certificate", - "description": "Client certificate to use when making the HTTP request", - "$ref": "#/definitions/ClientCertificateOptions" - } - } - }, - "ModelDescription": { - "title": "ModelDescription", - "type": "object", - "properties": { - "title": { - "title": "Title", - "description": "The title you wish to give your model.", - "type": "string" - }, - "provider": { - "title": "Provider", - "description": "The provider of the model. This is used to determine the type of model, and how to interact with it.", - "enum": [ - "openai", - "free-trial", - "anthropic", - "anthropic-vertexai", - "cohere", - "bedrock", - "bedrockimport", - "sagemaker", - "together", - "ollama", - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "replicate", - "gemini", - "gemini-vertexai", - "lmstudio", - "llamafile", - "mistral", - "mistral-vertexai", - "deepinfra", - "groq", - "fireworks", - "cloudflare", - "deepseek", - "azure", - "msty", - "watsonx", - "openrouter", - "sambanova", - "nvidia", - "vllm", - "cerebras" - ], - "markdownEnumDescriptions": [ - "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", - "### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)", - "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", - "### Anthropic Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", - "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)", - "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)", - "### Sagemaker\nSagemaker is AWS' machine learning platform.", - "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", - "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", - "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", - "### Huggingface Inference API\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfaceinferenceapi)", - "### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/llamacpp)", - "### Replicate\nReplicate is a hosted service that makes it easy to run ML models. To get started with Replicate:\n1. Obtain an API key from [here](https://replicate.com)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/replicatellm)", - "### Gemini API\nTo get started with Google Makersuite, obtain your API key from [here](https://makersuite.google.com) and paste it below.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/geminiapi)", - "### Gemini API on Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### LMStudio\nLMStudio provides a professional and well-designed GUI for exploring, configuring, and serving LLMs. It is available on both Mac and Windows. To get started:\n1. Download from [lmstudio.ai](https://lmstudio.ai/) and open the application\n2. Search for and download the desired model from the home screen of LMStudio.\n3. In the left-bar, click the '<->' icon to open the Local Inference Server and press 'Start Server'.\n4. Once your model is loaded and the server has started, you can begin using Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/lmstudio)", - "### Llamafile\nTo get started with llamafiles, find and download a binary on their [GitHub repo](https://github.com/Mozilla-Ocho/llamafile#binary-instructions). Then run it with the following command:\n\n```shell\nchmod +x ./llamafile\n./llamafile\n```\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/llamafile)", - "### Mistral API\n\nTo get access to the Mistral API, obtain your API key from the [Mistral platform](https://docs.mistral.ai/)", - "### Mistral API on Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### DeepInfra\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/deepinfra)", - "### Groq\nGroq provides extremely fast inference of open-source language models. To get started, obtain an API key from [their console](https://console.groq.com/keys).", - "### Fireworks\nFireworks is a fast inference engine for open-source language models. To get started, obtain an API key from [their console](https://fireworks.ai/api-keys).", - "### Cloudflare Workers AI\n\n[Reference](https://developers.cloudflare.com/workers-ai/)", - "### 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)", - "### IBM 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.", - "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", - "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", - "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", - "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/)." - ], - "type": "string" - }, - "model": { - "title": "Model", - "description": "The name of the model. Used to autodetect prompt template.", - "type": "string" - }, - "apiKey": { - "title": "Api Key", - "description": "OpenAI, Anthropic, Cohere, Together, or other API key", - "type": "string" - }, - "apiBase": { - "title": "Api Base", - "description": "The base URL of the LLM API.", - "type": "string" - }, - "region": { - "title": "Region", - "description": "The region where the model is hosted", - "anyOf": [ - { - "enum": [ - "us-east-1", - "us-east-2", - "us-west-1", - "us-west-2", - "eu-west-1", - "eu-central-1", - "ap-southeast-1", - "ap-northeast-1", - "ap-south-1", - "us-central1", - "us-east1", - "us-east4", - "us-east5", - "us-west1", - "us-west4", - "us-south1", - "northamerica-northeast1", - "southamerica-east1", - "europe-central2", - "europe-north1", - "europe-west1", - "europe-west2", - "europe-west3", - "europe-west4", - "europe-west6", - "europe-west8", - "europe-west9", - "europe-southwest1", - "asia-east1", - "asia-east2", - "asia-south1", - "asia-northeast1", - "asia-northeast3", - "asia-southeast1", - "australia-southeast1", - "me-central1", - "me-central2", - "me-west1" - ], - "type": "string" - }, - { - "type": "string" - } - ] - }, - "profile": { - "title": "Profile", - "description": "The AWS security profile to use", - "type": "string" - }, - "modelArn": { - "title": "Profile", - "description": "The AWS arn for the imported model", - "type": "string" - }, - "contextLength": { - "title": "Context Length", - "description": "The maximum context length of the LLM in tokens, as counted by countTokens.", - "default": 2048, - "type": "integer" - }, - "maxStopWords": { - "title": "Max Stop Words", - "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", - "type": "integer" - }, - "template": { - "title": "Template", - "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", - "enum": [ - "llama2", - "alpaca", - "zephyr", - "phi2", - "phind", - "anthropic", - "chatml", - "none", - "deepseek", - "openchat", - "xwin-coder", - "neural-chat", - "codellama-70b", - "llava", - "gemma", - "llama3" - ], - "type": "string" - }, - "promptTemplates": { - "title": "Prompt Templates", - "markdownDescription": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See [here](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt) for an example.", - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "completionOptions": { - "title": "Completion Options", - "description": "Options for the completion endpoint. Read more about the completion options in the documentation.", - "default": { - "temperature": null, - "topP": null, - "topK": null, - "presencePenalty": null, - "frequencyPenalty": null, - "stop": null, - "maxTokens": 600 - }, - "allOf": [ - { - "$ref": "#/definitions/BaseCompletionOptions" - } - ] - }, - "systemMessage": { - "title": "System Message", - "description": "A system message that will always be followed by the LLM", - "type": "string" - }, - "requestOptions": { - "title": "Request Options", - "description": "Options for the HTTP request to the LLM.", - "default": { - "timeout": 7200, - "verifySsl": null, - "caBundlePath": null, - "proxy": null, - "headers": null, - "extraBodyProperties": null - }, - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - }, - "apiType": { - "title": "Api Type", - "markdownDescription": "OpenAI API type, either `openai` or `azure`", - "enum": ["openai", "azure"] - }, - "apiVersion": { - "title": "Api Version", - "description": "Azure OpenAI API version (e.g. 2023-07-01-preview)", - "type": "string" - }, - "engine": { - "title": "Engine", - "description": "Azure OpenAI engine", - "type": "string" - }, - "capabilities": { - "type": "object", - "description": "We will attempt to automatically detect the capabilities of the model based on its title and provider, but this may not always be accurate. You can override the model's capabilities here.", - "properties": { - "uploadImage": { - "type": "boolean", - "description": "Indicates whether the model can upload images." - } - } - } - }, - "required": ["title", "provider", "model"], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "type": "str" - } - }, - "not": { - "required": ["provider"] - } - }, - "then": { - "properties": { - "model": { - "description": "Choose a provider first, then model options will be shown here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai", - "anthropic", - "cohere", - "gemini", - "huggingface-inference-api", - "replicate", - "together", - "cloudflare", - "sambanova" - ] - } - }, - "required": ["provider"] - }, - "then": { - "required": ["apiKey"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["bedrockimport"] - } - }, - "required": ["provider"] - }, - "then": { - "required": ["modelArn"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["huggingface-tgi", "huggingface-inference-api"] - } - } - }, - "then": { - "required": ["apiBase"] - }, - "required": ["provider"] - }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "engine": { - "type": "string" - }, - "apiType": { - "type": "string" - }, - "apiVersion": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["cloudflare"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "accountId": { - "type": "string" - }, - "aiGatewaySlug": { - "type": "string" - }, - "model": { - "anyOf": [ - { - "enum": [ - "@cf/meta/llama-3-8b-instruct", - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq", - "@cf/deepseek-ai/deepseek-math-7b-instruct", - "@cf/thebloke/discolm-german-7b-v1-awq", - "@cf/tiiuae/falcon-7b-instruct", - "@cf/google/gemma-2b-it-lora", - "@hf/google/gemma-7b-it", - "@cf/google/gemma-7b-it-lora", - "@hf/nousresearch/hermes-2-pro-mistral-7b", - "@cf/meta/llama-2-7b-chat-fp16", - "@cf/meta/llama-2-7b-chat-int8", - "@cf/meta-llama/llama-2-7b-chat-hf-lora", - "@hf/thebloke/llama-2-13b-chat-awq", - "@hf/thebloke/llamaguard-7b-awq", - "@cf/mistral/mistral-7b-instruct-v0.1", - "@hf/mistral/mistral-7b-instruct-v0.2", - "@cf/mistral/mistral-7b-instruct-v0.2-lora", - "@hf/thebloke/neural-chat-7b-v3-1-awq", - "@cf/openchat/openchat-3.5-0106", - "@hf/thebloke/openhermes-2.5-mistral-7b-awq", - "@cf/microsoft/phi-2", - "@cf/qwen/qwen1.5-0.5b-chat", - "@cf/qwen/qwen1.5-1.8b-chat", - "@cf/qwen/qwen1.5-7b-chat-awq", - "@cf/qwen/qwen1.5-14b-chat-awq", - "@cf/defog/sqlcoder-7b-2", - "@hf/nexusflow/starling-lm-7b-beta", - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0", - "@hf/thebloke/zephyr-7b-beta-awq", - "@hf/thebloke/deepseek-coder-6.7b-base-awq" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["replicate"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "llama3-8b", - "llama3-70b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "llama2-7b", - "llama2-13b" - ] - }, - { - "type": "string" - } - ] - }, - "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models)." - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["free-trial"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": [ - "gpt-4o", - "codestral-latest", - "llama3.1-70b", - "llama3.1-405b", - "gpt-3.5-turbo", - "gemini-pro", - "claude-3-5-sonnet-20240620", - "claude-3-haiku-20240307", - "AUTODETECT" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - }, - "apiType": { - "not": { - "const": "azure" - } - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-turbo", - "gpt-4-vision-preview", - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b", - "mistral-tiny", - "mistral-small", - "mistral-medium", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["anthropic"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "claude-2", - "claude-instant-1", - "claude-3-5-sonnet-20240620", - "claude-3-opus-20240229", - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2.1" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["anthropic-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-5-opus", - "claude-3-5-sonnet", - "claude-3-5-haiku", - "claude-3-opus", - "claude-3-sonnet", - "claude-3-haiku" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["cohere"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": ["command-r", "command-r-plus"] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["bedrock"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["sagemaker"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "markdownDescription": "SageMaker endpoint name" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["gemini"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - } - } - }, - "model": { - "enum": [ - "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["gemini-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - }, - { "type": "string" } - ] - } - }, - "required": ["projectId", "region"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["together"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "phind-codellama-34b" - ] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models)." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["deepinfra"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation)." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "text-gen-webui", - "llamafile" - ] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["ollama"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phi-2", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library)." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["mistral"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": [ - "codestral-latest", - "codestral-mamba-latest", - "open-mistral-7b", - "open-mixtral-8x7b", - "open-mixtral-8x22b", - "mistral-small-latest", - "mistral-large-latest" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["mistral-vertexai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "codestral", - "mistral-nemo", - "mistral-large" - ] - }, - { "type": "string" } - ] - } - }, - "required": ["projectId", "region"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["deepseek"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "enum": ["deepseek-chat", "deepseek-coder"] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["groq"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": [ - "llama2-70b", - "mistral-8x7b", - "gemma", - "gemma2", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "AUTODETECT" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["fireworks"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": ["starcoder-7b"] - } - } - } - }, - { - "if": { - "properties": { - "apiType": { - "const": "azure" - } - }, - "required": ["apiType"] - }, - "then": { - "required": ["engine", "apiVersion", "apiBase"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["openai"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "useLegacyCompletionsEndpoint": { - "type": "boolean" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "const": "llamafile" - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "llamafileCommand": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["cerebras"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "enum": ["llama3.1-8b", "llama3.1-70b"] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["text-gen-webui"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "streamingUrl": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["flowise"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "timeout": { - "title": "Timeout", - "description": "Set the timeout for each request to Flowise. If you are running a local version of Flowise it might takes a while to respond, you might want to set this to avoid timeouts.", - "default": 5000, - "type": "integer" - }, - "additionalHeaders": { - "description": "A list of additional headers", - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "title": "Key", - "description": "Header key", - "type": "string" - }, - "value": { - "title": "Value", - "description": "Header value", - "type": "string" - } - }, - "required": ["key", "value"] - } - }, - "additionalFlowiseConfiguration": { - "description": "A list of additional properties to be sent along `overrideConfig`", - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "title": "Key", - "description": "Configuration Property key", - "type": "string" - }, - "value": { - "title": "Value", - "description": "Configuration Property value" - } - }, - "required": ["key", "value"] - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-turbo", - "gpt-4-vision-preview", - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "claude-2", - "claude-instant-1", - "claude-3-5-sonnet-20240620", - "claude-3-opus-20240229", - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2.1", - "command-r", - "command-r-plus", - "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash", - "mistral-tiny", - "mistral-small", - "mistral-medium", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["watsonx"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "watsonxUrl": { - "type": "string" - }, - "watsonxApiKey": { - "type": "string" - }, - "watsonxApiVersion": { - "type": "string" - }, - "watsonxProjectId": { - "type": "string" - }, - "watsonxStopToken": { - "type": "string" - }, - "watsonxFullUrl": { - "type": "string" - }, - "model": { - "enum": [ - "ibm/granite-13b-chat-v2", - "ibm/granite-20b-code-instruct", - "mistralai/mistral-large", - "meta-llama/llama-3-8b-instruct", - "meta-llama/llama-3-70b-instruct" - ] - } - }, - "required": ["watsonxUrl", "watsonxProjectId"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["sambanova"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": ["llama3.1-8b", "llama3.1-70b", "llama3.1-405b"] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option." - } - } - } - } - ] - }, - "ModelRoles": { - "title": "ModelRoles", - "type": "object", - "properties": { - "default": { - "title": "Default", - "description": "The default model. If other model roles are not set, they will fall back to default.", - "type": "string" - }, - "chat": { - "title": "Chat", - "description": "The model to use for chat. If not set, will fall back to default.", - "type": "string" - }, - "edit": { - "title": "Edit", - "description": "The model to use for editing. If not set, will fall back to default.", - "type": "string" - }, - "summarize": { - "title": "Summarize", - "description": "The model to use for summarization. If not set, will fall back to default.", - "type": "string" - } - }, - "required": ["default"] - }, - "SlashCommand": { - "title": "SlashCommand", - "type": "object", - "properties": { - "name": { - "title": "Name", - "anyOf": [ - { - "enum": [ - "issue", - "share", - "cmd", - "edit", - "comment", - "http", - "commit", - "review" - ], - "type": "string", - "markdownEnumDescriptions": [ - "Generate a link to a drafted GitHub issue", - "Export the current chat session to markdown", - "Generate a terminal command and paste it into the terminal", - "Edit the highlighted code with given instructions", - "Add comments to the highlighted code", - "Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", - "Generate a commit message for the current changes", - "Review code and give feedback" - ] - }, - { - "type": "string" - } - ] - }, - "description": { - "title": "Description", - "type": "string" - }, - "step": { - "title": "Step", - "description": "This property is no longer required and has no effect. To use a built-in slash command, instead set the 'name' property to one of the pre-configured options.", - "type": "string" - }, - "params": { - "title": "Params", - "default": {}, - "type": "object" - } - }, - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["issue"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "repositoryUrl": { - "type": "string", - "description": "Enter the URL of the GitHub repository for which you want to generate the issue." - } - }, - "required": ["repositoryUrl"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["edit"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "recap": { - "type": "boolean", - "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit." - }, - "tokenLimit": { - "type": "integer", - "markdownDescription": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["share"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "outputDir": { - "type": "string", - "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory." - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["commit"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "includeUnstaged": { - "type": "boolean", - "markdownDescription": "If includeUnstaged is set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." - } - } - } - } - } - } - ], - "required": ["name", "description"] - }, - "CustomCommand": { - "title": "CustomCommand", - "type": "object", - "properties": { - "name": { - "title": "Name", - "type": "string" - }, - "prompt": { - "title": "Prompt", - "type": "string" - }, - "description": { - "title": "Description", - "type": "string" - } - }, - "required": ["name", "prompt", "description"] - }, - "ContextProviderWithParams": { - "title": "ContextProviderWithParams", - "type": "object", - "properties": { - "name": { - "title": "Name", - "anyOf": [ - { - "enum": [ - "diff", - "terminal", - "debugger", - "open", - "google", - "search", - "http", - "codebase", - "problems", - "folder", - "issue", - "docs", - "tree", - "highlights", - "outline", - "postgres", - "code", - "currentFile", - "url", - "database", - "os", - "repo-map", - "greptile", - "web" - ], - "markdownEnumDescriptions": [ - "Reference the contents of the current changes as given by `git diff`", - "Reference the last terminal command", - "Reference the contents of the local variables in the debugger with top n level (defaulting to 3) of call stack for that thread", - "Reference the contents of all open or pinned files.", - "Enter a search phrase and include the Google search results as context", - "Reference the results of a ripgrep search in your codebase", - "Write a custom context provider at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", - "Use embeddings to automatically find relevant files from throughout the codebase", - "Reference all linting errors and warnings in the currently open file", - "Include important files from a folder in the prompt, as determined by similarity search", - "Reference GitHub issues from a repository", - "Retrieve important pages from a documentation website, as determined by similarity search", - "Display a file tree of the current workspace", - "Include important highlighted sections from your code", - "Include a repo map showing important code objects", - "References Postgres table schema and sample rows", - "Reference specific functions and classes from throughout your codebase", - "Reference the contents of the currently active file", - "Reference the contents of a page at a URL", - "Reference table schemas", - "Operating system and CPU Information", - "Map of files in the repository with important code highlights", - "Query your greptile index of the current repo", - "Search the web for sources related to your question" - ], - "type": "string" - }, - { - "type": "string" - } - ] - }, - "params": { - "title": "Params", - "default": {}, - "type": "object" - } - }, - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["discord"] - } - } - }, - "then": { - "allOf": [ - { - "properties": { - "params": { - "properties": { - "discordKey": { - "type": "string", - "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." - }, - "guildId": { - "type": "string", - "description": "The ID of the guild (server) from which to fetch channels and messages." - }, - "channels": { - "type": "array", - "description": "A list of channel objects to search for messages", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The unique ID of the channel" - }, - "name": { - "type": "string", - "description": "The name of the channel" - } - }, - "required": ["id"] - } - } - }, - "required": ["discordKey"] - } - } - }, - { - "oneOf": [ - { - "properties": { - "params": { - "required": ["guildId"] - } - } - }, - { - "properties": { - "params": { - "required": ["channels"] - } - } - } - ] - } - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["google"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "serperApiKey": { - "type": "string", - "description": "Your API key for https://serper.dev in order to get Google search results" - } - }, - "required": ["serperApiKey"] - } - }, - "required": ["params"] - } - }, - { - "if": { "properties": { "name": { "enum": ["web"] } } }, - "then": { - "properties": { - "params": { - "properties": { - "n": { - "title": "N", - "description": "The number of results to return", - "default": 6, - "type": "integer" - } - } - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["open"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "onlyPinned": { - "type": "boolean", - "description": "If set to true, only 'pinned' files will be included.", - "default": false - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["issue"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "githubToken": { - "type": "string", - "description": "Your GitHub token to access the GitHub API. Required for private repositories." - }, - "repos": { - "type": "array", - "description": "A list of repositories to search for issues", - "items": { - "type": "object", - "properties": { - "owner": { - "type": "string", - "description": "The owner of the repository" - }, - "repo": { - "type": "string", - "description": "The name of the repository" - }, - "type": { - "type": "string", - "description": "The type of issues to search for", - "enum": ["open", "closed", "all"] - } - }, - "required": ["owner", "repo"] - } - } - }, - "required": ["repos"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["database"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "connections": { - "type": "array", - "description": "A list of database connections", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "A unique name for this database connection" - }, - "connection_type": { - "type": "string", - "description": "The type of database (e.g., 'postgres', 'mysql')", - "enum": ["postgres", "mysql", "sqlite"] - }, - "connection": { - "type": "object", - "properties": { - "user": { - "type": "string", - "description": "The database user name" - }, - "host": { - "type": "string", - "description": "The host address of the database server" - }, - "database": { - "type": "string", - "description": "The name of the database to connect to" - }, - "password": { - "type": "string", - "description": "The password for the database user" - }, - "port": { - "type": "integer", - "description": "The port number to connect to at the host" - }, - "filename": { - "type": "string", - "description": "File location for simple file DB's" - } - }, - "required": [] - } - }, - "required": ["name", "connection_type", "connection"] - } - } - }, - "required": ["connections"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["gitlab-mr"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "domain": { - "type": "string", - "description": "Your GitLab domain, will default to gitlab.com" - }, - "token": { - "type": "string", - "description": "Your private access token." - }, - "filterComments": { - "type": "boolean", - "description": "If you have code selected, filters out comments that aren't related to the selection." - } - }, - "required": ["token"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["jira"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "domain": { - "type": "string", - "description": "Your Jira domain, for example company.atlassian.net." - }, - "email": { - "type": "string", - "description": "The email that you log into Jira with" - }, - "token": { - "type": "string", - "description": "Your atlassian API token from https://id.atlassian.com/manage-profile/security/api-tokens" - }, - "issueQuery": { - "type": "string", - "description": "Customize the query used to find Jira issues" - }, - "apiVersion": { - "type": "integer", - "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." - }, - "requestOptions": { - "title": "Request Options", - "description": "Options for the HTTPS request to Jira.", - "default": { - "timeout": 7200, - "verifySsl": null, - "caBundlePath": null, - "proxy": null, - "headers": null, - "extraBodyProperties": null - }, - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - } - }, - "required": ["domain", "token"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["http"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "url": { - "type": "string", - "description": "The HTTP endpoint of your context provider server." - }, - "options": { - "title": "Custom Options", - "description": "Additional options to pass to your custom HTTP server.", - "type": "object" - } - }, - "required": ["url"] - } - }, - "required": ["params"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["codebase", "folder"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "nRetrieve": { - "title": "N Retrieve", - "description": "Number of results to initially retrieve from vector database", - "default": 50, - "type": "integer" - }, - "nFinal": { - "title": "N Final", - "description": "Final number of results to use after re-ranking", - "default": 10, - "type": "integer" - }, - "useReranking": { - "title": "Use Reranking", - "description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results. Disabling re-ranking will give faster, but less accurate, results.", - "default": true, - "type": "boolean" - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["postgres"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "host": { - "title": "Host", - "description": "Database host", - "default": "localhost", - "type": "string" - }, - "port": { - "title": "Port", - "description": "Database port", - "default": 5432, - "type": "integer" - }, - "user": { - "title": "User", - "description": "Database user", - "default": "postgres", - "type": "string" - }, - "password": { - "title": "Password", - "description": "Database password", - "type": "string" - }, - "database": { - "title": "Database", - "description": "Database name", - "default": "postgres", - "type": "string" - }, - "schema": { - "title": "Schema", - "description": "Database schema", - "default": "public", - "type": "string" - }, - "sampleRows": { - "title": "Sample Rows", - "description": "Number of rows to sample from the database", - "default": 3, - "type": "integer" - } - } - } - }, - "required": ["host", "port", "user", "password", "database"] - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["greptile"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "GithubToken": { - "title": "GithubToken", - "description": "Your github access token", - "default": "", - "type": "string" - }, - "GreptileToken": { - "title": "GreptileToken", - "description": "Your greptile access token", - "default": "", - "type": "string" - } - } - } - }, - "required": ["GreptileToken", "GithubToken"] - } - } - ], - "required": ["name"] - }, - "SerializedContinueConfig": { - "title": "config.json", - "type": "object", - "properties": { - "docs": { - "title": "Docs", - "description": "A list of documentation sites to be indexed", - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "The title of the documentation site" - }, - "startUrl": { - "type": "string", - "description": "The starting URL for indexing the documentation" - }, - "rootUrl": { - "type": "string", - "description": "The root URL of the documentation site" - }, - "maxDepth": { - "type": "integer", - "description": "The maximum depth to crawl the documentation site" - }, - "favicon": { - "type": "string", - "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" - } - }, - "required": ["title", "startUrl"] - } - }, - "allowAnonymousTelemetry": { - "title": "Allow Anonymous Telemetry", - "markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", - "default": true, - "type": "boolean" - }, - "models": { - "title": "Models", - "markdownDescription": "Learn about setting up models in [the documentation](https://docs.continue.dev/model-setup/overview).", - "default": [ - { - "title": "GPT-4 (trial)", - "provider": "free-trial", - "model": "gpt-4", - "apiKey": "" - } - ], - "type": "array", - "items": { - "$ref": "#/definitions/ModelDescription" - } - }, - "systemMessage": { - "title": "System Message", - "description": "A system message that will always be followed by the LLM", - "type": "string" - }, - "completionOptions": { - "title": "Completion Options", - "description": "Default options for completion. These will be overriden by any options set for a specific model.", - "default": { - "temperature": null, - "topP": null, - "topK": null, - "presencePenalty": null, - "frequencyPenalty": null, - "stop": null, - "maxTokens": 600 - }, - "allOf": [ - { - "$ref": "#/definitions/BaseCompletionOptions" - } - ] - }, - "requestOptions": { - "title": "Request Options", - "description": "Default request options for all fetch requests from models and context providers. These will be overriden by any model-specific request options.", - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - }, - "slashCommands": { - "title": "Slash Commands", - "markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands).", - "default": [], - "type": "array", - "items": { - "$ref": "#/definitions/SlashCommand" - } - }, - "customCommands": { - "title": "Custom Commands", - "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", - "default": [ - { - "name": "test", - "prompt": "{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - "description": "This is an example custom command. Open config.json to edit it and create more" - } - ], - "type": "array", - "items": { - "$ref": "#/definitions/CustomCommand" - } - }, - "contextProviders": { - "title": "Context Providers", - "markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://docs.continue.dev/customization/context-providers).", - "default": [], - "type": "array", - "items": { - "$ref": "#/definitions/ContextProviderWithParams" - } - }, - "userToken": { - "title": "User Token", - "description": "An optional token to identify the user.", - "type": "string" - }, - "disableIndexing": { - "title": "Disable Indexing", - "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", - "default": false, - "type": "boolean" - }, - "disableSessionTitles": { - "title": "Disable Session Titles", - "markdownDescription": "If set to `true`, Continue will not make extra requests to the LLM to generate a summary title of each session.", - "default": false, - "type": "boolean" - }, - "embeddingsProvider": { - "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", - "type": "object", - "properties": { - "provider": { - "enum": [ - "huggingface-tei", - "transformers.js", - "ollama", - "openai", - "cohere", - "free-trial", - "gemini", - "voyage", - "nvidia", - "bedrock", - "sagemaker" - ] - }, - "model": { - "type": "string" - }, - "apiKey": { - "type": "string" - }, - "apiBase": { - "type": "string" - }, - "requestOptions": { - "title": "Request Options", - "description": "Request options to be used in any fetch requests made by the embeddings provider", - "$ref": "#/definitions/RequestOptions" - }, - "maxChunkSize": { - "title": "Maximum Chunk Size", - "description": "The maximum number of tokens that each chunk of a document is allowed to have", - "type": "integer", - "minimum": 128, - "exclusiveMaximum": 2147483647 - }, - "maxBatchSize": { - "title": "Maximum Batch Size", - "description": "The maximum number of chunks that can be sent to the embeddings provider in a single request", - "type": "integer", - "minimum": 1, - "exclusiveMaximum": 2147483647 - }, - "region": { - "title": "Region", - "description": "The region where the model is hosted", - "$ref": "#/definitions/ModelDescription/properties/region" - }, - "profile": { - "title": "Profile", - "description": "The AWS security profile to use", - "type": "string" - } - }, - "required": ["provider"], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "enum": ["cohere", "voyage", "nvidia", "gemini"] - } - }, - "required": ["provider"] - }, - "then": { - "required": ["apiKey"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["sagemaker"] - } - }, - "required": ["provider"] - }, - "then": { - "properties": { - "model": { - "markdownDescription": "SageMaker endpoint name" - } - }, - "required": ["model"] - } - } - ] - }, - "reranker": { - "title": "Reranker", - "markdownDescription": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", - "type": "object", - "properties": { - "name": { - "enum": [ - "cohere", - "voyage", - "llm", - "free-trial", - "huggingface-tei" - ] - }, - "params": { - "type": "object" - } - }, - "required": ["name"], - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["cohere"] - } - }, - "required": ["name"] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "model": { - "enum": [ - "rerank-english-v3.0", - "rerank-multilingual-v3.0", - "rerank-english-v2.0", - "rerank-multilingual-v2.0" - ] - }, - "apiBase": { - "type": "string" - }, - "apiKey": { - "type": "string" - } - }, - "required": ["apiKey"] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["llm"] - } - }, - "required": ["name"] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "modelTitle": { - "type": "string" - } - }, - "required": ["modelTitle"] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["voyage"] - } - }, - "required": ["name"] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "apiKey": { - "type": "string" - }, - "model": { - "enum": [ - "rerank-lite-1", - "rerank-1", - "rerank-2", - "rerank-2-lite" - ] - } - }, - "required": ["apiKey"] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": ["huggingface-tei"] - } - }, - "required": ["name"] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "apiBase": { - "type": "string", - "default": "http://localhost:8080" - }, - "truncate": { - "type": "boolean", - "description": "Wether to truncate long sequences to the maximum allowed context length.", - "default": false - }, - "truncation_direction": { - "enum": ["Right", "Left"], - "markdownDescription": "Wether to truncate sequences from the `left` or `right`.", - "default": "Right" - } - }, - "required": ["apiBase"] - } - }, - "if": { - "properties": { - "truncate": { - "const": true - } - } - }, - "then": { - "required": ["truncation_direction"] - } - } - } - ] - }, - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", - "default": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:1.3b-base" - }, - "oneOf": [ - { - "$ref": "#/definitions/ModelDescription" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/ModelDescription" - } - } - ] - }, - "tabAutocompleteOptions": { - "title": "TabAutocompleteOptions", - "type": "object", - "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", - "properties": { - "disable": { - "type": "boolean", - "description": "Disable tab autocomplete. This can also be done from the IDE settings.", - "default": false - }, - "useCopyBuffer": { - "type": "boolean", - "description": "Determines whether the copy buffer will be considered when contructing the prompt." - }, - "useFileSuffix": { - "type": "boolean", - "description": "Determines whether to use the file suffix in the prompt." - }, - "maxPromptTokens": { - "type": "number", - "description": "The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context." - }, - "debounceDelay": { - "type": "number", - "description": "The delay in milliseconds before triggering autocomplete after a keystroke." - }, - "maxSuffixPercentage": { - "type": "number", - "description": "The maximum percentage of the prompt that can be dedicated to the suffix." - }, - "prefixPercentage": { - "type": "number", - "description": "The percentage of the input that should be dedicated to the prefix." - }, - "template": { - "type": "string", - "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." - }, - "multilineCompletions": { - "enum": ["always", "never", "auto"], - "description": "If set to true, Continue will only complete a single line at a time." - }, - "useCache": { - "type": "boolean", - "description": "Whether to cache completions" - }, - "onlyMyCode": { - "type": "boolean", - "description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository" - }, - "useOtherFiles": { - "type": "boolean", - "description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files." - }, - "disableInFiles": { - "description": "A list of files / glob patterns in which to disable tab autocomplete. For example, *.csv if you'd like to disable autocomplete in .csv files.", - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": [] - }, - "ui": { - "type": "object", - "properties": { - "codeBlockToolbarPosition": { - "enum": ["top", "bottom"], - "default": "top", - "description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar." - }, - "fontSize": { - "type": "number" - }, - "displayRawMarkdown": { - "type": "boolean", - "description": "If set to true, we will display the model output as raw markdown.", - "default": false - }, - "showChatScrollbar": { - "title": "Show Chat Scrollbar", - "markdownDescription": "If set to `true`, a scrollbar will be displayed in the chat window to navigate through messages.", - "default": false, - "type": "boolean" - } - } - }, - "analytics": { - "type": "object", - "properties": { - "provider": { - "type": "string", - "enum": ["posthog", "logstash"], - "description": "The 3rd party analytics provider to use.", - "default": "posthog", - "markdownEnumDescriptions": [ - "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", - "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" - ] - }, - "url": { - "type": "string", - "description": "The URL to which analytics will be sent" - }, - "clientKey": { - "type": "string", - "description": "The client key to use for analytics" - } - }, - "required": ["provider"], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "enum": ["posthog"] - } - } - }, - "then": { - "required": ["clientKey"] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": ["logstash"] - } - } - }, - "then": { - "required": ["url"] - } - } - ] - }, - "experimental": { - "type": "object", - "title": "Experimental", - "description": "Experimental properties are subject to change.", - "properties": { - "defaultContext": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/definitions/ContextProviderWithParams" - }, - { - "properties": { - "query": { - "type": "string", - "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." - } - } - } - ] - } - }, - "modelRoles": { - "type": "object", - "properties": { - "inlineEdit": { - "description": "The 'title' property of the model you wish to use for inline edits", - "type": "string" - }, - "applyCodeBlock": { - "description": "The 'title' property of the model you wish to use for applying code blocks", - "type": "string" - }, - "repoMapFileSelection": { - "description": "The 'title' property of the model you wish to use for repo map file selections", - "type": "string" - } - } - }, - "readResponseTTS": { - "type": "boolean", - "default": true, - "description": "Automatically read LLM chat responses aloud using system TTS models" - }, - "promptPath": { - "type": "string" - }, - "quickActions": { - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "The title of the quick action that will display in the Code Lens." - }, - "prompt": { - "type": "string", - "description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated." - }, - "sendToChat": { - "type": "boolean", - "description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.", - "default": false - } - }, - "required": ["prompt", "title"] - }, - "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." - }, - "contextMenuPrompts": { - "type": "object", - "properties": { - "comment": { - "type": "string", - "default": "Write comments for this code. Do not change anything about the code itself." - }, - "docstring": { - "type": "string", - "default": "Write a docstring for this code. Do not change anything about the code itself." - }, - "fix": { - "type": "string", - "default": "Fix this code" - }, - "optimize": { - "type": "string", - "default": "Optimize this code" - }, - "fixGrammar": { - "type": "string", - "default": "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing." - } - } - } - } - } - } - } - } -} diff --git a/extensions/intellij/.gitignore b/extensions/intellij/.gitignore index 9873b602d..13ca3bab9 100644 --- a/extensions/intellij/.gitignore +++ b/extensions/intellij/.gitignore @@ -1,2 +1,5 @@ src/main/resources/webview -src/main/resources/bin \ No newline at end of file +!src/main/resources/webview/index.html +src/main/resources/bin +src/main/resources/config_schema.json +src/main/resources/continue_rc_schema.json \ No newline at end of file diff --git a/extensions/intellij/.run/Prompt Logs.run.xml b/extensions/intellij/.run/Prompt Logs.run.xml new file mode 100644 index 000000000..23fec409a --- /dev/null +++ b/extensions/intellij/.run/Prompt Logs.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Continue (CE).run.xml b/extensions/intellij/.run/Run Continue (CE).run.xml new file mode 100644 index 000000000..edca42d64 --- /dev/null +++ b/extensions/intellij/.run/Run Continue (CE).run.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Continue.run.xml b/extensions/intellij/.run/Run Continue.run.xml index 32ba73bb9..2cc85210f 100644 --- a/extensions/intellij/.run/Run Continue.run.xml +++ b/extensions/intellij/.run/Run Continue.run.xml @@ -1,8 +1,9 @@ - - + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run_Continue.xml b/extensions/intellij/.run/Run_Continue.xml deleted file mode 100644 index 8aa354813..000000000 --- a/extensions/intellij/.run/Run_Continue.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml new file mode 100644 index 000000000..4284b852f --- /dev/null +++ b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Start Core Dev Server.run.xml b/extensions/intellij/.run/Start Core Dev Server.run.xml new file mode 100644 index 000000000..0fb8233ef --- /dev/null +++ b/extensions/intellij/.run/Start Core Dev Server.run.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Tail Dev Logs.run.xml b/extensions/intellij/.run/Start GUI Dev Server.run.xml similarity index 78% rename from extensions/intellij/.run/Tail Dev Logs.run.xml rename to extensions/intellij/.run/Start GUI Dev Server.run.xml index 5685b4fd8..5f574019a 100644 --- a/extensions/intellij/.run/Tail Dev Logs.run.xml +++ b/extensions/intellij/.run/Start GUI Dev Server.run.xml @@ -1,11 +1,11 @@ - -