Merge branch 'main' into s-inline-keyboard-shortcuts

This commit is contained in:
Patrick Erichsen 2025-03-03 18:59:15 -08:00
commit 3e85b517af
525 changed files with 17078 additions and 8975 deletions

View file

@ -0,0 +1,5 @@
## 0.0.92 - 2025-02-26
### Fixed
* Off-screen rendering to solve white flash on load and lack of changing cursor type
* OSR-related fixes for non-Mac users
* Fixes for inline edit in JetBrains

View file

@ -0,0 +1,7 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved theme matching
### Fixed
* Fixes interference between SonarQube and Continue autocomplete
* Numerous reliability improvements

View file

@ -0,0 +1,6 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved apply quality
### Fixed
* Numerous reliability improvements

View file

@ -1,5 +0,0 @@
project: extensions/intellij
kind: Fixed
body: Off-screen rendering to solve white flash on load and lack of changing cursor
type
time: 2024-10-07T18:38:20.733658-07:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Fixed
body: OSR-related fixes for non-Mac users
time: 2024-11-08T11:43:22.623155-08:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Fixed
body: Fixes for inline edit in JetBrains
time: 2024-11-08T11:47:07.953304-08:00

View file

@ -4,7 +4,7 @@ description: Generate unit tests for core utilities
Write jest tests for the provided code.
Use jest version ^29 (e.g. jest 29.7.0)
Use best practices. Be clear and consise.
Use best practices. Be clear and concise.
Aim for 100% code coverage where reasonable.
Multiple tests can be written, split up tests for best clarity and readability.
Only use typescript, and if the file/code is not typescript, warn the user.
@ -15,7 +15,7 @@ Use double quotes (or backticks if needed) for strings
The code being tested is used in IDE extensions, and it:
- accesses code workspaces through the IDE ("workspace directories")
- persists extension-related data to the the local machine of the user ("global directory"), and
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accesed via a remote "control plane" using the `ControlPlaneClient`
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accessed via a remote "control plane" using the `ControlPlaneClient`
Jest testing setup includes
- @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live.
@ -31,7 +31,7 @@ Jest testing setup includes
Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests.
IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible.
IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible.
Instead, generate actual mock files and data for operations
Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests

View file

@ -27,16 +27,17 @@ body:
- **Continue version**: v0.9.4
- **IDE version**: VSCode 1.85.1
- Model: Claude Sonnet 3.5
- config.json: `{ "models": ... }`
- Assistant configuration
value: |
- OS:
- Continue version:
- IDE version:
- Model:
- config.json:
```json
- config:
```yaml
```
OR link to assistant in Continue hub:
render: Markdown
validations:
required: false

View file

@ -6,11 +6,11 @@ name: JetBrains Release
on:
release:
types: [ prereleased ]
types: [prereleased]
workflow_dispatch:
inputs:
publish_build:
description: 'Whether or not to publish the built extension to the JetBrains marketplace'
description: "Whether or not to publish the built extension to the JetBrains marketplace"
required: true
default: false
@ -31,7 +31,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-jetbrains ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -241,6 +241,12 @@ jobs:
name: continue-binary-win32-x64
path: ./binary/bin/win32-x64/
- name: Upload artifact (win32-arm64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-win32-arm64
path: ./binary/bin/win32-arm64/
- name: Upload artifact (linux-arm64)
uses: actions/upload-artifact@v4
with:
@ -345,7 +351,7 @@ jobs:
# Run tests and upload a code coverage report
test:
name: Test
needs: [ build ]
needs: [build]
runs-on: ubuntu-latest
steps:
# Check out current repository
@ -387,7 +393,7 @@ jobs:
inspectCode:
if: false
name: Inspect code
needs: [ build ]
needs: [build]
runs-on: ubuntu-latest
permissions:
contents: write
@ -422,7 +428,7 @@ jobs:
verify:
if: false
name: Verify plugin
needs: [ build ]
needs: [build]
runs-on: ubuntu-latest
steps:
# Free GitHub Actions Environment Disk Space

View file

@ -20,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.8.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -208,7 +208,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- build
if: github.event.inputs.publish_build == 'true'
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
steps:

View file

@ -4,22 +4,12 @@ on:
pull_request:
branches:
- main
paths:
- "extensions/intellij/**"
- "extensions/vscode/**"
- "core/**"
- "gui/**"
- ".github/workflows/**"
- staging
push:
branches:
- main
paths:
- "extensions/intellij/**"
- "extensions/vscode/**"
- "core/**"
- "gui/**"
- ".github/workflows/**"
- staging
jobs:
install-root:
@ -290,6 +280,8 @@ jobs:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest

View file

@ -4,6 +4,13 @@ on:
release:
types: [prereleased]
workflow_dispatch:
inputs:
publish_build:
description: "Whether or not to publish the built extension to the VS Code marketplace"
required: true
default: false
jobs:
check_release_name:
runs-on: ubuntu-latest
@ -13,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.9.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -21,7 +28,7 @@ jobs:
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
strategy:
matrix:
include:
@ -197,6 +204,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- build
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
steps:
@ -209,8 +217,8 @@ jobs:
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
- name: Pull latest changes
run: git pull origin main
- name: Pull latest changes from release
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
# 1. Download the artifacts
- uses: actions/download-artifact@v4

19
.vscode/launch.json vendored
View file

@ -138,6 +138,25 @@
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
},
{
"name": "[config-yaml] Jest Test Debugger, Current Open File",
"type": "node",
"request": "launch",
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/packages/config-yaml/node_modules/jest/bin/jest.js",
"--runInBand",
"--config",
"${workspaceRoot}/packages/config-yaml/jest.config.mjs",
"${relativeFile}"
],
"cwd": "${workspaceRoot}/packages/config-yaml",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
}
]
}

View file

@ -13,6 +13,9 @@
"args": ["-l"]
}
},
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"search.exclude": {
"**/package-lock.json": true,

85
.vscode/tasks.json vendored
View file

@ -6,16 +6,14 @@
"type": "npm",
"script": "tsc:watch",
"isBackground": true,
"problemMatcher": {
"base": "$tsc-watch",
"background": {
"activeOnStart": true,
"beginsPattern": "Starting compilation in watch mode...",
"endsPattern": "Found 0 errors"
}
"problemMatcher": ["$tsc-watch"],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"revealProblems": "onProblem"
"reveal": "always",
"panel": "new"
}
},
// Compile and bundle the extension
@ -73,7 +71,27 @@
}
]
},
// Build the React app. It gets bundled into the extension as a file resource and has a seprate build step
{
"label": "vscode-extension:package",
"dependsOn": ["vscode-extension:esbuild"],
"type": "npm",
"script": "package",
"path": "extensions/vscode",
"problemMatcher": [
{
"pattern": [
{
"regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
]
}
]
},
{
"label": "vscode-extension:continue-ui:build",
"type": "shell",
@ -186,6 +204,55 @@
"command": "node",
"args": ["${workspaceFolder}/scripts/uninstall.js"],
"problemMatcher": []
},
{
"label": "refresh-dependencies:core",
"type": "shell",
"command": "npm",
"args": ["install"],
"problemMatcher": [],
"options": {
"cwd": "${workspaceFolder}/core"
},
"presentation": {
"close": true
}
},
{
"label": "refresh-dependencies:vscode",
"type": "shell",
"command": "npm",
"args": ["install"],
"problemMatcher": [],
"options": {
"cwd": "${workspaceFolder}/extensions/vscode"
},
"presentation": {
"close": true
}
},
{
"label": "refresh-dependencies:gui",
"type": "shell",
"command": "npm",
"args": ["install"],
"problemMatcher": [],
"options": {
"cwd": "${workspaceFolder}/gui"
},
"presentation": {
"close": true
}
},
{
"label": "refresh-dependencies:all",
"dependsOn": [
"refresh-dependencies:core",
"refresh-dependencies:gui",
"refresh-dependencies:vscode"
],
"type": "shell",
"problemMatcher": []
}
]
}

View file

@ -128,7 +128,7 @@ nvm use
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
3. To package the extension, run `npm run package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
##### Debugging

View file

@ -8,7 +8,7 @@
<div align="center">
**[Continue](https://docs.continue.dev) is the leading open-source AI code assistant. You can connect any models and any context to build custom autocomplete and chat experiences inside [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)**
**[Continue](https://docs.continue.dev) enables to developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
</div>
@ -46,7 +46,7 @@
## Actions
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases.
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases
![actions](docs/static/img/actions.gif)

View file

@ -53,7 +53,7 @@ const targetToLanceDb = {
"linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
"linux-x64": "@lancedb/vectordb-linux-x64-gnu",
"win32-x64": "@lancedb/vectordb-win32-x64-msvc",
"win32-arm64": "@lancedb/vectordb-win32-x64-msvc", // they don't have a win32-arm64 build
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
};
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
@ -248,9 +248,15 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
// Download and unzip prebuilt sqlite3 binary for the target
console.log("[info] Downloading node-sqlite3");
const downloadUrl = `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
target === "win32-arm64" ? "win32-ia32" : target
}.tar.gz`;
const downloadUrl =
// node-sqlite3 doesn't have a pre-built binary for win32-arm64
target === "win32-arm64"
? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz"
: `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
target
}.tar.gz`;
execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
@ -279,7 +285,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
// Informs the `continue-binary` of where to look for node_sqlite3.node
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// fs.writeFileSync(`${targetDir}/package.json`, "");
fs.writeFileSync(`${targetDir}/package.json`, "");
}
// Cleanup - this is needed when running locally

View file

@ -0,0 +1,6 @@
const path = require('path');
process.env.CONTINUE_DEVELOPMENT = true;
process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
require('./out/index.js');

View file

@ -48,13 +48,13 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.23",
"@continuedev/config-yaml": "^1.0.52",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",
"@modelcontextprotocol/sdk": "^1.0.0",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
@ -107,7 +107,7 @@
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"
"zod": "^3.24.2"
},
"devDependencies": {
"@babel/preset-env": "^7.24.7",
@ -2556,9 +2556,10 @@
}
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==",
"version": "1.7.9",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
"integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
@ -3166,10 +3167,11 @@
}
},
"node_modules/cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
@ -5135,12 +5137,13 @@
}
},
"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==",
"dev": true,
"license": "MIT",
"dependencies": {
"braces": "^3.0.2",
"braces": "^3.0.3",
"picomatch": "^2.3.1"
},
"engines": {

20
binary/prompt-logs.js Normal file
View file

@ -0,0 +1,20 @@
const fs = require('fs');
const path = require('path');
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
const logFilePath = path.join(logDirPath, "prompt.log");
if (!fs.existsSync(logDirPath)) {
fs.mkdirSync(logDirPath, { recursive: true });
}
if (!fs.existsSync(logFilePath)) {
fs.createWriteStream(logFilePath).end();
}
console.log("Watching logs at " + logFilePath)
fs.watch(logFilePath, () => {
// console.clear();
fs.createReadStream(logFilePath).pipe(process.stdout);
});

View file

@ -75,7 +75,7 @@ class IPCMessengerBase<
console.warn(`Error running handler for "${msg.messageType}": `, e);
this._onErrorHandlers.forEach((handler) => {
handler(e);
handler(msg, e);
});
}
});
@ -112,9 +112,9 @@ class IPCMessengerBase<
lines.forEach((line) => this._handleLine(line));
}
private _onErrorHandlers: ((error: Error) => void)[] = [];
private _onErrorHandlers: ((message: Message, error: Error) => void)[] = [];
onError(handler: (error: Error) => void) {
onError(handler: (message: Message, error: Error) => void) {
this._onErrorHandlers.push(handler);
}
@ -217,7 +217,7 @@ export class CoreBinaryMessenger<
extends IPCMessengerBase<ToProtocol, FromProtocol>
implements IMessenger<ToProtocol, FromProtocol>
{
private errorHandler: (error: Error) => void = () => {};
private errorHandler: (message: Message, error: Error) => void = () => {};
private messageHandlers: Map<
keyof ToProtocol,
(message: Message<any>) => Promise<any> | any

View file

@ -41,9 +41,9 @@ export class TcpMessenger<
});
}
private _onErrorHandlers: ((error: Error) => void)[] = [];
private _onErrorHandlers: ((message: Message, error: Error) => void)[] = [];
onError(handler: (error: Error) => void) {
onError(handler: (message: Message, error: Error) => void) {
this._onErrorHandlers.push(handler);
}
@ -111,7 +111,7 @@ export class TcpMessenger<
console.warn(`Error running handler for "${msg.messageType}": `, e);
this._onErrorHandlers.forEach((handler) => {
handler(e);
handler(msg, e);
});
}
});

View file

@ -134,6 +134,13 @@ export class CompletionProvider {
token: AbortSignal | undefined,
): Promise<AutocompleteOutcome | undefined> {
try {
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
);
token = controller.signal;
}
const startTime = Date.now();
const options = await this._getAutocompleteOptions();
@ -158,14 +165,6 @@ export class CompletionProvider {
return undefined;
}
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
);
token = controller.signal;
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
helper,

View file

@ -240,6 +240,14 @@ export const Solidity = {
endOfLine: [";"],
};
// Lua
export const Lua = {
name: "Lua",
topLevelKeywords: ["function"],
singleLineComment: "--",
endOfLine: [],
};
// YAML
export const YAML: AutocompleteLanguageInfo = {
name: "YAML",
@ -367,6 +375,8 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
yaml: YAML,
yml: YAML,
md: Markdown,
lua: Lua,
luau: Lua,
};
export function languageForFilepath(fileUri: string): AutocompleteLanguageInfo {

View file

@ -11,6 +11,8 @@ import {
AutocompleteSnippetType,
} from "./types";
const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled
export interface SnippetPayload {
rootPathSnippets: AutocompleteCodeSnippet[];
importDefinitionSnippets: AutocompleteCodeSnippet[];
@ -29,6 +31,27 @@ function racePromise<T>(promise: Promise<T[]>): Promise<T[]> {
return Promise.race([promise, timeoutPromise]);
}
class DiffSnippetsCache {
private cache: Map<number, any> = new Map();
private lastTimestamp: number = 0;
public set<T>(timestamp: number, value: T): T {
// Clear old cache entry if exists
if (this.lastTimestamp !== timestamp) {
this.cache.clear();
}
this.lastTimestamp = timestamp;
this.cache.set(timestamp, value);
return value;
}
public get(timestamp: number): any | undefined {
return this.cache.get(timestamp);
}
}
const diffSnippetsCache = new DiffSnippetsCache();
// 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)
async function getIdeSnippets(
@ -90,14 +113,31 @@ const getClipboardSnippets = async (
const getDiffSnippets = async (
ide: IDE,
): Promise<AutocompleteDiffSnippet[]> => {
const diff = await ide.getDiff(true);
const currentTimestamp = ide.getLastFileSaveTimestamp ?
ide.getLastFileSaveTimestamp() :
Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
return diff.map((item) => {
// Check cache first
const cached = diffSnippetsCache.get(currentTimestamp) as AutocompleteDiffSnippet[];
if (cached) {
return cached;
}
let diff: string[] = [];
try {
diff = await ide.getDiff(true);
} catch (e) {
console.error("Error getting diff for autocomplete", e);
}
return diffSnippetsCache.set(currentTimestamp, diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
});
}));
};
export const getAllSnippets = async ({
@ -122,10 +162,8 @@ export const getAllSnippets = async ({
clipboardSnippets,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
),
racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)),
racePromise(contextRetrievalService.getSnippetsFromImportDefinitions(helper)),
IDE_SNIPPETS_ENABLED ? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)) : [],
racePromise(getDiffSnippets(ide)),
racePromise(getClipboardSnippets(ide)),
]);

View file

@ -51,6 +51,8 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
};
// https://github.com/QwenLM/Qwen2.5-Coder?tab=readme-ov-file#3-file-level-code-completion-fill-in-the-middle
// This issue asks about the use of <|repo_name|> and <|file_sep|> together with <|fim_prefix|>, <|fim_suffix|> and <|fim_middle|>
// https://github.com/QwenLM/Qwen2.5-Coder/issues/343
const qwenCoderFimTemplate: AutocompleteTemplate = {
template:
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
@ -85,6 +87,11 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
snippets,
workspaceUris,
): [string, string] => {
function getFileName(snippet: { uri: string, uniquePath: string }) {
return snippet.uri.startsWith("file://") ? snippet.uniquePath : snippet.uri
}
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
return [
@ -111,14 +118,12 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
return snippet.content;
}
return `+++++ ${relativePaths[i].uri} \n${snippet.content}`;
return `+++++ ${getFileName(relativePaths[i])} \n${snippet.content}`;
})
.join("\n\n");
return [
`${otherFiles}\n\n+++++ ${
relativePaths[relativePaths.length - 1].uri
}\n${prefix}`,
`${otherFiles}\n\n+++++ ${getFileName(relativePaths[relativePaths.length - 1])}\n${prefix}`,
suffix,
];
},
@ -126,7 +131,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
return `[SUFFIX]${suffix}[PREFIX]${prefix}`;
},
completionOptions: {
stop: ["[PREFIX]", "[SUFFIX]"],
stop: ["[PREFIX]", "[SUFFIX]", "\n+++++ "],
},
};
@ -218,9 +223,8 @@ const codegeexFimTemplate: AutocompleteTemplate = {
[...snippets.map((snippet) => snippet.filepath), filepath],
workspaceUris,
);
const baseTemplate = `###PATH:${
relativePaths[relativePaths.length - 1]
}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1]
}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
if (snippets.length === 0) {
return `<|user|>\n${baseTemplate}<|assistant|>\n`;
}
@ -395,7 +399,8 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
lowerCaseModel.includes("gpt") ||
lowerCaseModel.includes("davinci-002") ||
lowerCaseModel.includes("claude") ||
lowerCaseModel.includes("granite3")
lowerCaseModel.includes("granite3") ||
lowerCaseModel.includes("granite-3")
) {
return holeFillerTemplate;
}

View file

@ -42,24 +42,100 @@ export const getSnippets = (
helper: HelperVars,
payload: SnippetPayload,
): AutocompleteSnippet[] => {
const snippets = [
...payload.diffSnippets,
...payload.clipboardSnippets,
...payload.recentlyVisitedRangesSnippets,
...shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
),
),
];
const snippets = {
"clipboard": payload.clipboardSnippets,
"recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets,
"recentlyEditedRanges": payload.recentlyEditedRangeSnippets,
"diff": payload.diffSnippets,
"base": shuffleArray(filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
)),
}
// Define snippets with their priorities
const snippetConfigs: {
key: keyof typeof snippets;
enabledOrPriority: boolean | number;
defaultPriority: number;
snippets: AutocompleteSnippet[];
}[] = [
{
key: "clipboard",
enabledOrPriority: helper.options.experimental_includeClipboard,
defaultPriority: 1,
snippets: payload.clipboardSnippets,
},
{
key: "recentlyVisitedRanges",
enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges,
defaultPriority: 2,
snippets: payload.recentlyVisitedRangesSnippets,
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
if they are visible. We should handle them separately so that we can control their priority
and whether they should be included or not. */
},
{
key: "recentlyEditedRanges",
enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges,
defaultPriority: 3,
snippets: payload.recentlyEditedRangeSnippets,
},
{
key: "diff",
enabledOrPriority: helper.options.experimental_includeDiff,
defaultPriority: 4,
snippets: payload.diffSnippets,
// TODO: diff is commonly too large, thus anything lower in priority is not included.
},
{
key: "base",
enabledOrPriority: true,
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
)),
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
// always not inlucded due to diff being commonly large
},
];
// Create a readable order of enabled snippets
const snippetOrder = snippetConfigs
.filter(({ enabledOrPriority }) => enabledOrPriority)
.map(({ key, enabledOrPriority, defaultPriority }) => ({
key,
priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority,
}))
.sort((a, b) => a.priority - b.priority);
// Log the snippet order for debugging - uncomment if needed
/* console.log(
'Snippet processing order:',
snippetOrder
.map(({ key, priority }) => `${key} (priority: ${priority})`).join("\n")
); */
// Convert configs to prioritized snippets
let prioritizedSnippets = snippetOrder
.flatMap(({ key, priority }) =>
snippets[key].map(snippet => ({ snippet, priority }))
)
.sort((a, b) => a.priority - b.priority)
.map(({ snippet }) => snippet);
// Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
// while looking at the prompts in the Continue's output
prioritizedSnippets = prioritizedSnippets.filter((snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue"));
const finalSnippets = [];
let remainingTokenCount = getRemainingTokenCount(helper);
while (remainingTokenCount > 0 && snippets.length > 0) {
const snippet = snippets.shift();
while (remainingTokenCount > 0 && prioritizedSnippets.length > 0) {
const snippet = prioritizedSnippets.shift();
if (!snippet || !isValidSnippet(snippet)) {
continue;
}

View file

@ -1,4 +1,4 @@
import { logDevData } from "../../util/devdata";
import { DataLogger } from "../../data/log";
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
import { Telemetry } from "../../util/posthog";
import { getUriFileExtension } from "../../util/uri";
@ -96,7 +96,14 @@ export class AutocompleteLoggingService {
}
private logAutocompleteOutcome(outcome: AutocompleteOutcome) {
logDevData("autocomplete", outcome);
void DataLogger.getInstance().logDevData({
name: "autocomplete",
data: {
...outcome,
useFileSuffix: true, // from outdated schema
},
});
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture(
"autocomplete",
@ -113,6 +120,7 @@ export class AutocompleteLoggingService {
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
},
true,
);

View file

@ -10,7 +10,7 @@ export function slashFromCustomCommand(
return {
name: customCommand.name,
description: customCommand.description ?? "",
run: async function* ({ input, llm, history, ide }) {
run: async function* ({ input, llm, history, ide, completionOptions }) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${customCommand.name}`)) {
@ -20,11 +20,16 @@ export function slashFromCustomCommand(
}
// Render prompt template
const promptUserInput = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
);
let promptUserInput: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
promptUserInput = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
);
} else {
promptUserInput = customCommand.prompt + "\n\n" + userInput;
}
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
@ -67,6 +72,7 @@ export function slashFromCustomCommand(
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
completionOptions,
)) {
yield renderChatMessage(chunk);
}

View file

@ -10,11 +10,11 @@ import { defaultConfig } from "./default";
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.listProfiles();
expect(profiles.length).toBe(1);
expect(profiles[0].id).toBe("local");
expect(profiles?.length).toBe(1);
expect(profiles?.[0].id).toBe("local");
const currentProfile = testConfigHandler.currentProfile;
expect(currentProfile.profileDescription.id).toBe("local");
expect(currentProfile?.profileDescription.id).toBe("local");
});
test("should load the default config successfully", async () => {

View file

@ -1,11 +1,6 @@
import * as fs from "node:fs";
import {
AssistantUnrolled,
ConfigResult,
FullSlug,
} from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
import {
ControlPlaneClient,
@ -27,7 +22,7 @@ import { localPathToUri } from "../util/pathToUri.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
ONBOARDING_LOCAL_MODEL_TITLE,
LOCAL_ONBOARDING_PROVIDER_TITLE,
} from "./onboarding.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@ -36,7 +31,6 @@ import {
ProfileDescription,
ProfileLifecycleManager,
} from "./ProfileLifecycleManager.js";
import { clientRenderHelper } from "./yaml/clientRender.js";
export type { ProfileDescription };
@ -47,55 +41,94 @@ type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
export class ConfigHandler {
private readonly globalContext = new GlobalContext();
private additionalContextProviders: IContextProvider[] = [];
private profiles: ProfileLifecycleManager[];
private selectedProfileId: string;
private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded
private selectedProfileId: string | null = null;
private localProfileManager: ProfileLifecycleManager;
controlPlaneClient: ControlPlaneClient;
initializedPromise: Promise<void>;
constructor(
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private readonly writeLog: (text: string) => Promise<void>,
private controlPlaneClient: ControlPlaneClient,
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.writeLog = writeLog;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
);
// Set local profile as default
const localProfileLoader = new LocalProfileLoader(
ide,
ideSettingsPromise,
controlPlaneClient,
this.controlPlaneClient,
writeLog,
);
this.profiles = [new ProfileLifecycleManager(localProfileLoader, this.ide)];
this.selectedProfileId = localProfileLoader.description.id;
this.localProfileManager = new ProfileLifecycleManager(
localProfileLoader,
this.ide,
);
// Always load local profile immediately in case control plane doesn't load
// Profiles are loaded asynchronously
this.initializedPromise = new Promise((resolve, reject) => {
this.init()
.then(() => {
resolve();
})
.catch((e) => {
reject(e);
});
});
}
/**
* Retrieves the titles of additional context providers that are of type "submenu".
*
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
*/
getAdditionalSubmenuContextProviders(): string[] {
return this.additionalContextProviders
.filter((provider) => provider.description.type === "submenu")
.map((provider) => provider.description.title);
}
private async init() {
try {
void this.loadConfig();
await this.fetchControlPlaneProfiles();
} catch (e) {
// If this fails, make sure at least local profile is loaded
console.error("Failed to fetch control plane profiles in init: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
}
try {
const configResult = await this.loadConfig();
this.notifyConfigListeners(configResult);
} catch (e) {
console.error("Failed to load config: ", e);
}
// Load control plane profiles
void this.fetchControlPlaneProfiles();
}
// This will be the local profile
private get fallbackProfile() {
return this.profiles[0];
}
get currentProfile() {
if (!this.selectedProfileId) {
return null;
}
// IMPORTANT
// We must fall back to null, not the first or local profiles
// Because GUI must be the source of truth for selected profile
return (
this.profiles.find(
this.profiles?.find(
(p) => p.profileDescription.id === this.selectedProfileId,
) ?? this.fallbackProfile
) ?? null
);
}
get inactiveProfiles() {
return this.profiles.filter(
return (this.profiles ?? []).filter(
(p) => p.profileDescription.id !== this.selectedProfileId,
);
}
@ -112,74 +145,84 @@ export class ConfigHandler {
}
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}platform/${openProfileId}`);
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
}
}
private async loadPlatformProfiles() {
async listOrganizations() {
return await this.controlPlaneClient.listOrganizations();
}
async loadAssistantsForSelectedOrg() {
// Get the profiles and create their lifecycle managers
this.controlPlaneClient
.listAssistants()
.then(async (assistants) => {
const hubProfiles = await Promise.all(
assistants.map(async (assistant) => {
let renderedConfig: AssistantUnrolled | undefined = undefined;
if (assistant.configResult.config) {
renderedConfig = await clientRenderHelper(
YAML.stringify(assistant.configResult.config),
this.ide,
this.controlPlaneClient,
);
}
const userId = await this.controlPlaneClient.userId;
const selectedOrgId = await this.getSelectedOrgId();
const profileLoader = new PlatformProfileLoader(
{ ...assistant.configResult, config: renderedConfig },
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
let profiles: ProfileLifecycleManager[] | null = null;
if (!userId) {
// Not logged in
profiles = [this.localProfileManager];
} else {
// Logged in
const assistants =
await this.controlPlaneClient.listAssistants(selectedOrgId);
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
const hubProfiles = assistants.map((assistant) => {
const profileLoader = new PlatformProfileLoader(
{
...assistant.configResult,
config: assistant.configResult.config,
},
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
this.profiles = [
...this.profiles.filter(
(profile) => profile.profileDescription.id === "local",
),
...hubProfiles,
];
this.notifyProfileListeners(
this.profiles.map((profile) => profile.profileDescription),
);
// Check the last selected workspace, and reload if it isn't local
const workspaceId = await this.getWorkspaceId();
const lastSelectedWorkspaceIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId];
if (selectedWorkspaceId) {
this.selectedProfileId = selectedWorkspaceId;
await this.loadConfig();
} else {
// Otherwise we stick with local profile, and record choice
lastSelectedWorkspaceIds[workspaceId] = this.selectedProfileId;
this.globalContext.update(
"lastSelectedProfileForWorkspace",
lastSelectedWorkspaceIds,
);
}
})
.catch((e) => {
console.error("Failed to list assistants: ", e);
return new ProfileLifecycleManager(profileLoader, this.ide);
});
if (selectedOrgId === null) {
// Personal
profiles = [...hubProfiles, this.localProfileManager];
} else {
// Organization
profiles = hubProfiles;
}
}
await this.updateAvailableProfiles(profiles);
}
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
this.profiles = profiles;
// If the last selected profile is in the list choose that
// Otherwise, choose the first profile
const previouslySelectedProfileId =
await this.getPersistedSelectedProfileId();
// Check if the previously selected profile exists in the current profiles
const profileExists = profiles.some(
(profile) =>
profile.profileDescription.id === previouslySelectedProfileId,
);
const selectedProfileId = profileExists
? previouslySelectedProfileId
: (profiles[0]?.profileDescription.id ?? null);
// Notify listeners
const profileDescriptions = profiles.map(
(profile) => profile.profileDescription,
);
this.notifyProfileListeners(profileDescriptions, selectedProfileId);
await this.setSelectedProfile(selectedProfileId);
}
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
@ -204,78 +247,81 @@ export class ConfigHandler {
return false;
}
private async fetchControlPlaneProfiles() {
if (await useHub(this.ideSettingsPromise)) {
clearInterval(this.platformProfilesRefreshInterval);
await this.loadPlatformProfiles();
private async reloadHubAssistants() {
const selectedOrgId = await this.getSelectedOrgId();
const newFullSlugsList =
await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId);
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
// If so, we do the full (more expensive) reload
this.platformProfilesRefreshInterval = setInterval(async () => {
const newFullSlugsList =
await this.controlPlaneClient.listAssistantFullSlugs();
if (newFullSlugsList) {
const shouldReload = this.fullSlugsListsDiffer(
newFullSlugsList,
this.lastFullSlugsList,
);
if (shouldReload) {
await this.loadPlatformProfiles();
}
this.lastFullSlugsList = newFullSlugsList;
}
}, PlatformProfileLoader.RELOAD_INTERVAL);
} else {
this.controlPlaneClient
.listWorkspaces()
.then(async (workspaces) => {
this.profiles = this.profiles.filter(
(profile) => profile.profileDescription.id === "local",
);
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
this.profiles.push(
new ProfileLifecycleManager(profileLoader, this.ide),
);
});
this.notifyProfileListeners(
this.profiles.map((profile) => profile.profileDescription),
);
// Check the last selected workspace, and reload if it isn't local
const workspaceId = await this.getWorkspaceId();
const lastSelectedWorkspaceIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId];
if (selectedWorkspaceId) {
this.selectedProfileId = selectedWorkspaceId;
await this.loadConfig();
} else {
// Otherwise we stick with local profile, and record choice
lastSelectedWorkspaceIds[workspaceId] = this.selectedProfileId;
this.globalContext.update(
"lastSelectedProfileForWorkspace",
lastSelectedWorkspaceIds,
);
}
})
.catch((e) => {
console.error(e);
});
if (newFullSlugsList) {
const shouldReload = this.fullSlugsListsDiffer(
newFullSlugsList,
this.lastFullSlugsList,
);
if (shouldReload) {
await this.loadAssistantsForSelectedOrg();
}
this.lastFullSlugsList = newFullSlugsList;
}
}
async setSelectedProfile(profileId: string) {
private async fetchControlPlaneProfiles() {
if (await useHub(this.ideSettingsPromise)) {
clearInterval(this.platformProfilesRefreshInterval);
await this.loadAssistantsForSelectedOrg();
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
// If so, we do the full (more expensive) reload
this.platformProfilesRefreshInterval = setInterval(
this.reloadHubAssistants.bind(this),
PlatformProfileLoader.RELOAD_INTERVAL,
);
} else {
try {
const workspaces = await this.controlPlaneClient.listWorkspaces();
const profiles = [this.localProfileManager];
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
});
await this.updateAvailableProfiles(profiles);
} catch (e: any) {
console.error("Failed to load profiles: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
}
}
}
async getPersistedSelectedProfileId(): Promise<string | null> {
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
return lastSelectedIds[workspaceId] ?? null;
}
async getSelectedOrgId(): Promise<string | null> {
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
return selectedOrgs[await this.getWorkspaceId()] ?? null;
}
async setSelectedOrgId(orgId: string | null) {
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
selectedOrgs[await this.getWorkspaceId()] = orgId;
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
}
async setSelectedProfile(profileId: string | null) {
this.selectedProfileId = profileId;
const result = await this.loadConfig();
this.notifyConfigListeners(result);
@ -307,21 +353,32 @@ export class ConfigHandler {
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
);
this.fetchControlPlaneProfiles().catch((e) => {
this.fetchControlPlaneProfiles().catch(async (e) => {
console.error("Failed to fetch control plane profiles: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
await this.reloadConfig();
});
}
private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = [];
private profilesListeners: ((
profiles: ProfileDescription[],
selectedProfileId: string | null,
) => void)[] = [];
onDidChangeAvailableProfiles(
listener: (profiles: ProfileDescription[]) => void,
listener: (
profiles: ProfileDescription[],
selectedProfileId: string | null,
) => void,
) {
this.profilesListeners.push(listener);
}
private notifyProfileListeners(profiles: ProfileDescription[]) {
private notifyProfileListeners(
profiles: ProfileDescription[],
selectedProfileId: string | null,
) {
for (const listener of this.profilesListeners) {
listener(profiles);
listener(profiles, selectedProfileId);
}
}
@ -338,33 +395,54 @@ export class ConfigHandler {
this.updateListeners.push(listener);
}
async reloadConfig(additionalContextProviders: IContextProvider[] = []) {
// TODO: this isn't right, there are two different senses in which you want to "reload"
// TODO: this isn't right, there are two different senses in which you want to "reload"
async reloadConfig() {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
const { config, errors, configLoadInterrupted } =
await this.currentProfile.reloadConfig(additionalContextProviders);
await this.currentProfile.reloadConfig(this.additionalContextProviders);
if (config) {
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
}
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
return { config, errors };
return { config, errors, configLoadInterrupted };
}
getSerializedConfig(): Promise<
async getSerializedConfig(): Promise<
ConfigResult<BrowserSerializedContinueConfig>
> {
return this.currentProfile.getSerializedConfig(
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
return await this.currentProfile.getSerializedConfig(
this.additionalContextProviders,
);
}
listProfiles(): ProfileDescription[] {
return this.profiles.map((p) => p.profileDescription);
listProfiles(): ProfileDescription[] | null {
return this.profiles?.map((p) => p.profileDescription) ?? null;
}
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
return await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
@ -374,7 +452,7 @@ export class ConfigHandler {
const { config } = await this.loadConfig();
const model = config?.models.find((m) => m.title === title);
if (!model) {
if (title === ONBOARDING_LOCAL_MODEL_TITLE) {
if (title === LOCAL_ONBOARDING_PROVIDER_TITLE) {
// Special case, make calls to Ollama before we have it in the config
const ollama = new Ollama({
model: LOCAL_ONBOARDING_CHAT_MODEL,
@ -392,6 +470,6 @@ export class ConfigHandler {
registerCustomContextProvider(contextProvider: IContextProvider) {
this.additionalContextProviders.push(contextProvider);
void this.reloadConfig(this.additionalContextProviders);
void this.reloadConfig();
}
}

View file

@ -27,6 +27,7 @@ export interface OrganizationDescription {
id: string;
iconUrl: string;
name: string;
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
}
export class ProfileLifecycleManager {
@ -50,7 +51,9 @@ export class ProfileLifecycleManager {
}
// Clear saved config and reload
async reloadConfig(additionalContextProviders: IContextProvider[] = []): Promise<ConfigResult<ContinueConfig>> {
async reloadConfig(
additionalContextProviders: IContextProvider[] = [],
): Promise<ConfigResult<ContinueConfig>> {
this.savedConfigResult = undefined;
this.savedBrowserConfigResult = undefined;
this.pendingConfigPromise = undefined;
@ -73,7 +76,21 @@ export class ProfileLifecycleManager {
// Set pending config promise
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
const result = await this.profileLoader.doLoadConfig();
let result: ConfigResult<ContinueConfig>;
try {
result = await this.profileLoader.doLoadConfig();
} catch (e: any) {
result = {
errors: [
{
fatal: true,
message: e.message,
},
],
config: undefined,
configLoadInterrupted: true,
};
}
if (result.config) {
// Add registered context providers

View file

@ -5,20 +5,6 @@ import {
SlashCommandDescription,
} from "../";
export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = {
model: "claude-3-5-sonnet-latest",
provider: "anthropic",
apiKey: "",
title: "Claude 3.5 Sonnet",
};
export const DEFAULT_AUTOCOMPLETE_MODEL_CONFIG: ModelDescription = {
title: "Codestral",
provider: "mistral",
model: "codestral-latest",
apiKey: "",
};
export const FREE_TRIAL_MODELS: ModelDescription[] = [
{
title: "Claude 3.5 Sonnet (Free Trial)",
@ -93,15 +79,15 @@ export const defaultSlashCommandsJetBrains = [
];
export const defaultConfig: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
models: [],
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
data: [],
};
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
models: [],
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
data: [],
};

View file

@ -3,6 +3,11 @@ import * as fs from "fs";
import os from "os";
import path from "path";
import {
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as JSONC from "comment-json";
import * as tar from "tar";
@ -18,6 +23,7 @@ import {
EmbeddingsProviderDescription,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
ILLM,
@ -30,14 +36,16 @@ import {
import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index.js";
} from "../commands/index";
import { AllRerankers } from "../context/allRerankers";
import { MCPManagerSingleton } from "../context/mcp";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
import { useHub } from "../control-plane/env";
import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
import { BaseLLM } from "../llm";
import { llmFromDescription } from "../llm/llms";
@ -61,8 +69,8 @@ import {
getContinueDotEnv,
getEsbuildBinaryPath,
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -70,9 +78,8 @@ import {
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { useHub } from "../control-plane/env";
import { localPathToUri } from "../util/pathToUri";
import { modifyContinueConfigWithSharedConfig } from "./sharedConfig";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util";
import { validateConfig } from "./validation.js";
export function resolveSerializedConfig(
@ -166,10 +173,9 @@ function loadSerializedConfig(
? [...defaultSlashCommandsVscode]
: [...defaultSlashCommandsJetBrains];
// Temporarily disabling this check until we can verify the commands are accuarate
// if (!isSupportedLanceDbCpuTarget(ide)) {
// config.disableIndexing = true;
// }
if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) {
config.disableIndexing = true;
}
return { config, errors, configLoadInterrupted: false };
}
@ -226,18 +232,12 @@ export function isContextProviderWithParams(
return (contextProvider as ContextProviderWithParams).name !== undefined;
}
const getCodebaseProvider = async (params: any) => {
const { default: CodebaseContextProvider } = await import(
"../context/providers/CodebaseContextProvider"
);
return new CodebaseContextProvider(params);
};
/** Only difference between intermediate and final configs is the `models` array */
async function intermediateToFinalConfig(
config: Config,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -326,6 +326,7 @@ async function intermediateToFinalConfig(
...model.requestOptions,
...config.requestOptions,
};
model.roles = model.roles ?? ["chat", "apply", "edit", "summarize"]; // Default to chat role if not specified
}
if (allowFreeTrial) {
@ -397,7 +398,7 @@ async function intermediateToFinalConfig(
new FileContextProvider({}),
// Add codebase provider if indexing is enabled
...(!config.disableIndexing
? [await getCodebaseProvider(codebaseContextParams)]
? [new CodebaseContextProvider(codebaseContextParams)]
: []),
// Add prompt files provider if enabled
...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []),
@ -435,23 +436,28 @@ async function intermediateToFinalConfig(
}
// Embeddings Provider
const embeddingsProviderDescription = config.embeddingsProvider as
| EmbeddingsProviderDescription
| undefined;
if (embeddingsProviderDescription?.provider) {
const { provider, ...options } = embeddingsProviderDescription;
function getEmbeddingsILLM(
embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
): ILLM | null {
if (!embedConfig) {
return null;
}
if ("providerName" in embedConfig) {
return embedConfig;
}
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
config.embeddingsProvider = new embeddingsProviderClass();
return new embeddingsProviderClass();
} else {
const llmOptions: LLMOptions = {
model: options.model ?? "UNSPECIFIED",
...options,
};
config.embeddingsProvider = new embeddingsProviderClass(
return new embeddingsProviderClass(
llmOptions,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
@ -460,42 +466,74 @@ async function intermediateToFinalConfig(
}),
);
}
} else {
errors.push({
fatal: false,
message: `Embeddings provider ${provider} not found. Using default`,
});
}
return null;
}
if (!config.embeddingsProvider) {
config.embeddingsProvider = new TransformersJsEmbeddingsProvider();
}
const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider);
// Reranker
if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) {
function getRerankingILLM(
rerankingConfig: ILLM | RerankerDescription | undefined,
): ILLM | null {
if (!rerankingConfig) {
return null;
}
if ("providerName" in rerankingConfig) {
return rerankingConfig;
}
const { name, params } = config.reranker as RerankerDescription;
const rerankerClass = AllRerankers[name];
if (name === "llm") {
const llm = models.find((model) => model.title === params?.modelTitle);
if (!llm) {
console.warn(`Unknown model ${params?.modelTitle}`);
errors.push({
fatal: false,
message: `Unknown reranking model ${params?.modelTitle}`,
});
return null;
} else {
config.reranker = new LLMReranker(llm);
return new LLMReranker(llm);
}
} else if (rerankerClass) {
const llmOptions: LLMOptions = {
model: "rerank-2",
...params,
};
config.reranker = new rerankerClass(llmOptions);
return new rerankerClass(llmOptions);
}
return null;
}
const newReranker = getRerankingILLM(config.reranker);
let continueConfig: ContinueConfig = {
const continueConfig: ContinueConfig = {
...config,
contextProviders,
models,
embeddingsProvider: config.embeddingsProvider as any,
tabAutocompleteModels,
reranker: config.reranker as any,
tools: allTools,
modelsByRole: {
chat: models,
edit: models,
apply: models,
summarize: models,
autocomplete: [...tabAutocompleteModels],
embed: newEmbedder ? [newEmbedder] : [],
rerank: newReranker ? [newReranker] : [],
},
selectedModelByRole: {
chat: null, // Not implemented (uses GUI defaultModel)
edit: null,
apply: null,
embed: newEmbedder ?? null,
autocomplete: null,
rerank: newReranker ?? null,
summarize: null, // Not implemented
},
};
// Apply MCP if specified
@ -517,6 +555,8 @@ async function intermediateToFinalConfig(
continueConfig,
mcpId,
abortController.signal,
"MCP Server",
server.faviconUrl,
);
if (mcpError) {
errors.push(mcpError);
@ -535,47 +575,112 @@ async function intermediateToFinalConfig(
);
}
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
if (inlineEditModel) {
const match = continueConfig.models.find(
(m) => m.title === inlineEditModel,
);
if (match) {
continueConfig.selectedModelByRole.edit = match;
continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set
} else {
errors.push({
fatal: false,
message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`,
});
}
}
const applyBlockModel = getModelByRole(
continueConfig,
"applyCodeBlock",
)?.title;
if (applyBlockModel) {
const match = continueConfig.models.find(
(m) => m.title === applyBlockModel,
);
if (match) {
continueConfig.selectedModelByRole.apply = match;
continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set
} else {
errors.push({
fatal: false,
message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`,
});
}
}
// Add transformers JS to the embed models list if not already added
if (
ideInfo.ideType === "vscode" &&
!continueConfig.modelsByRole.embed.find(
(m) => m.providerName === "transformers.js",
)
) {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
}
return { config: continueConfig, errors };
}
function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
return {
provider: llm.providerName,
model: llm.model,
title: llm.title ?? llm.model,
apiKey: llm.apiKey,
apiBase: llm.apiBase,
contextLength: llm.contextLength,
template: llm.template,
completionOptions: llm.completionOptions,
systemMessage: llm.systemMessage,
requestOptions: llm.requestOptions,
promptTemplates: llm.promptTemplates as any,
capabilities: llm.capabilities,
roles: llm.roles,
};
}
async function finalToBrowserConfig(
final: ContinueConfig,
ide: IDE,
): Promise<BrowserSerializedContinueConfig> {
return {
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
models: final.models.map((m) => ({
provider: m.providerName,
model: m.model,
title: m.title ?? m.model,
apiKey: m.apiKey,
apiBase: m.apiBase,
contextLength: m.contextLength,
template: m.template,
completionOptions: m.completionOptions,
systemMessage: m.systemMessage,
requestOptions: m.requestOptions,
promptTemplates: m.promptTemplates as any,
capabilities: m.capabilities,
})),
models: final.models.map(llmToSerializedModelDescription),
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map((s) => ({
name: s.name,
description: s.description,
params: s.params, //PZTODO: is this why params aren't referenced properly by slash commands?
params: s.params, // TODO: is this why params aren't referenced properly by slash commands?
})),
contextProviders: final.contextProviders?.map((c) => c.description),
disableIndexing: final.disableIndexing,
disableSessionTitles: final.disableSessionTitles,
userToken: final.userToken,
embeddingsProvider: final.embeddingsProvider?.embeddingId,
ui: final.ui,
experimental: final.experimental,
docs: final.docs,
tools: final.tools,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),
modelsByRole: Object.fromEntries(
Object.entries(final.modelsByRole).map(([k, v]) => [
k,
v.map(llmToSerializedModelDescription),
]),
) as Record<ModelRole, ModelDescription[]>, // TODO better types here
selectedModelByRole: Object.fromEntries(
Object.entries(final.selectedModelByRole).map(([k, v]) => [
k,
v ? llmToSerializedModelDescription(v) : null,
]),
) as Record<ModelRole, ModelDescription | null>, // TODO better types here
// data not included here because client doesn't need
};
}
@ -763,7 +868,7 @@ async function loadContinueConfigFromJson(
ide: IDE,
workspaceConfigs: ContinueRcJson[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -777,7 +882,7 @@ async function loadContinueConfigFromJson(
} = loadSerializedConfig(
workspaceConfigs,
ideSettings,
ideType,
ideInfo.ideType,
overrideConfigJson,
ide,
);
@ -794,16 +899,16 @@ async function loadContinueConfigFromJson(
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyContinueConfigWithSharedConfig(
serialized,
sharedConfig,
);
const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
// Convert serialized to intermediate config
let intermediate = await serializedToIntermediateConfig(withShared, ide);
// Apply config.ts to modify intermediate config
const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType);
const configJsContents = await buildConfigTsandReadConfigJs(
ide,
ideInfo.ideType,
);
if (configJsContents) {
try {
// Try config.ts first
@ -863,6 +968,7 @@ async function loadContinueConfigFromJson(
intermediate,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,

View file

@ -1,13 +1,9 @@
import * as fs from "fs";
import * as JSONC from "comment-json";
import { IDE, SerializedContinueConfig } from "..";
import { SharedConfigSchema } from "./sharedConfig";
import { IDE } from "..";
import { deduplicateArray } from "../util";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigJson } from "../util/paths";
import { resolveSerializedConfig } from "./load";
import { deduplicateArray } from "../util";
import { SharedConfigSchema } from "./sharedConfig";
/*
This migration function eliminates deprecated values from the json file
@ -201,10 +197,10 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
if (effected) {
new GlobalContext().updateSharedConfig(shareConfigUpdates);
editConfigJson(() => config);
void ide.showToast(
"warning",
"Migrated deprecated Continue JSON settings. Edit in the Settings Page",
);
// void ide.showToast(
// "warning",
// "Migrated deprecated Continue JSON settings. Edit in the Settings Page",
// );
}
} catch (e) {
throw new Error(`Migration: Failed to parse config.json: ${e}`);

View file

@ -3,10 +3,12 @@ import { SerializedContinueConfig } from "../";
import { FREE_TRIAL_MODELS } from "./default";
export const TRIAL_FIM_MODEL = "codestral-latest";
export const ONBOARDING_LOCAL_MODEL_TITLE = "Ollama";
export const LOCAL_ONBOARDING_PROVIDER_TITLE = "Ollama";
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b-base";
export const LOCAL_ONBOARDING_FIM_TITLE = "Qwen2.5-Coder 1.5B";
export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b";
export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";
export const LOCAL_ONBOARDING_EMBEDDINGS_MODEL = "nomic-embed-text:latest";
/**
* We set the "best" chat + autocopmlete models by default
@ -35,13 +37,13 @@ export function setupLocalConfig(
...config.models.filter((model) => model.provider !== "free-trial"),
],
tabAutocompleteModel: {
title: "Qwen2.5-Coder 1.5B",
title: LOCAL_ONBOARDING_FIM_TITLE,
provider: "ollama",
model: LOCAL_ONBOARDING_FIM_MODEL,
},
embeddingsProvider: {
provider: "ollama",
model: "nomic-embed-text",
model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL,
},
};
}
@ -68,24 +70,3 @@ export function setupQuickstartConfig(
},
};
}
export function setupLocalConfigAfterFreeTrial(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: [
{
title: LOCAL_ONBOARDING_CHAT_TITLE,
provider: "ollama",
model: LOCAL_ONBOARDING_CHAT_MODEL,
},
{
title: ONBOARDING_LOCAL_MODEL_TITLE,
provider: "ollama",
model: "AUTODETECT",
},
...config.models.filter((model) => model.provider !== "free-trial"),
],
};
}

View file

@ -38,6 +38,7 @@ export default class LocalProfileLoader implements IProfileLoader {
undefined,
undefined,
undefined,
this.description.id,
);
this.description.errors = result.errors;

View file

@ -1,8 +1,8 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas/index.js";
import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
@ -43,7 +43,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
packageSlug,
versionSlug,
},
title: `${ownerSlug}/${packageSlug}@${versionSlug}`,
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
iconUrl: this.iconUrl,
};
@ -69,6 +69,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
},
this.description.id,
);
return {

View file

@ -4,6 +4,7 @@ import {
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import {
ContinueConfig,
@ -21,9 +22,10 @@ import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { loadContinueConfigFromJson } from "../load";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
export default async function doLoadConfig(
ide: IDE,
@ -33,7 +35,7 @@ export default async function doLoadConfig(
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
workspaceId?: string,
profileId: string,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
@ -59,7 +61,7 @@ export default async function doLoadConfig(
ide,
workspaceConfigs.map((c) => JSON.stringify(c)),
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -75,7 +77,7 @@ export default async function doLoadConfig(
ide,
workspaceConfigs,
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -86,6 +88,11 @@ export default async function doLoadConfig(
configLoadInterrupted = result.configLoadInterrupted;
}
// Rectify model selections for each role
if (newConfig) {
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
}
if (configLoadInterrupted || !newConfig) {
return { errors, config: newConfig, configLoadInterrupted: true };
}
@ -117,7 +124,7 @@ export default async function doLoadConfig(
controlPlaneProxyUrl += "/";
}
const controlPlaneProxyInfo = {
workspaceId,
profileId,
controlPlaneProxyUrl,
workOsAccessToken,
};
@ -147,21 +154,26 @@ async function injectControlPlaneProxyInfo(
config: ContinueConfig,
info: ControlPlaneProxyInfo,
): Promise<ContinueConfig> {
[...config.models, ...(config.tabAutocompleteModels ?? [])].forEach(
async (model) => {
Object.keys(config.modelsByRole).forEach((key) => {
config.modelsByRole[key as ModelRole].forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
},
);
});
});
if (config.embeddingsProvider?.providerName === "continue-proxy") {
(config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info;
}
Object.keys(config.selectedModelByRole).forEach((key) => {
const model = config.selectedModelByRole[key as ModelRole];
if (model?.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
if (config.reranker?.providerName === "continue-proxy") {
(config.reranker as ContinueProxy).controlPlaneProxyInfo = info;
}
config.models.forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
return config;
}

View file

@ -0,0 +1,67 @@
import { ModelRole } from "@continuedev/config-yaml";
import { ContinueConfig, ILLM } from "..";
import {
GlobalContext,
GlobalContextModelSelections,
} from "../util/GlobalContext";
export function rectifySelectedModelsFromGlobalContext(
continueConfig: ContinueConfig,
profileId: string,
): ContinueConfig {
const configCopy = { ...continueConfig };
const globalContext = new GlobalContext();
const currentSelectedModels = globalContext.get("selectedModelsByProfileId");
const currentForProfile: GlobalContextModelSelections =
currentSelectedModels?.[profileId] ?? {};
let fellBack = false;
// chat and summarize not implemented yet
// default chat model is stored in GUI still
const roles: ModelRole[] = [
"autocomplete",
"apply",
"edit",
"embed",
"rerank",
];
for (const role of roles) {
let newModel: ILLM | null = null;
const currentSelection = currentForProfile[role] ?? null;
if (currentSelection) {
const match = continueConfig.modelsByRole[role].find(
(m) => m.title === currentSelection,
);
if (match) {
newModel = match;
}
}
if (!newModel && continueConfig.modelsByRole[role].length > 0) {
newModel = continueConfig.modelsByRole[role][0];
}
if (!(currentSelection === (newModel?.title ?? null))) {
fellBack = true;
}
configCopy.selectedModelByRole[role] = newModel;
}
// In the case shared config wasn't respected,
// Rewrite the shared config
if (fellBack) {
globalContext.update("selectedModelsByProfileId", {
...currentSelectedModels,
[profileId]: Object.fromEntries(
Object.entries(configCopy.selectedModelByRole).map(([key, value]) => [
key,
value?.title ?? null,
]),
),
});
}
return configCopy;
}

View file

@ -1,13 +1,15 @@
import z from "zod";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
Config,
ContinueConfig,
SerializedContinueConfig,
} from "..";
export const sharedConfigSchema = z
.object({
// boolean fields in config.json
allowAnonymousTelemetry: z.boolean(),
disableIndexing: z.boolean(),
disableSessionTitles: z.boolean(),
@ -18,6 +20,7 @@ export const sharedConfigSchema = z
promptPath: z.string(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
codeBlockToolbarPosition: z.enum(["top", "bottom"]),
fontSize: z.number(),
codeWrap: z.boolean(),
@ -65,7 +68,19 @@ export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema {
return salvagedConfig;
}
export function modifyContinueConfigWithSharedConfig<
// Apply shared config to all forms of config
// - SerializedContinueConfig (config.json)
// - Config ("intermediate") - passed to config.ts
// - ContinueConfig
// - BrowserSerializedContinueConfig (final converted to be passed to GUI)
// This modify function is split into two steps
// - rectifySharedModelsFromSharedConfig - includes boolean flags like allowAnonymousTelemetry which
// must be added BEFORE config.ts and remote server config apply for JSON
// for security reasons
// - setSharedModelsFromSharedConfig - exists because of selectedModelsByRole
// Which don't exist on SerializedContinueConfig/Config types, so must be added after the fact
export function modifyAnyConfigWithSharedConfig<
T extends
| ContinueConfig
| BrowserSerializedContinueConfig
@ -92,6 +107,7 @@ export function modifyContinueConfigWithSharedConfig<
configCopy.ui = {
...configCopy.ui,
};
if (sharedConfig.codeBlockToolbarPosition !== undefined) {
configCopy.ui.codeBlockToolbarPosition =
sharedConfig.codeBlockToolbarPosition;
@ -119,6 +135,10 @@ export function modifyContinueConfigWithSharedConfig<
configCopy.disableSessionTitles = sharedConfig.disableSessionTitles;
}
if (sharedConfig.showSessionTabs !== undefined) {
configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs;
}
configCopy.experimental = {
...configCopy.experimental,
};
@ -135,28 +155,3 @@ export function modifyContinueConfigWithSharedConfig<
return configCopy;
}
// continueConfig.tabAutocompleteOptions = {
// ...continueConfig.tabAutocompleteOptions,
// useCache: sharedConfig.useAutocompleteCache,
// disableInFiles: sharedConfig.disableAutocompleteInFiles,
// multilineCompletions: sharedConfig.useAutocompleteMultilineCompletions,
// };
// continueConfig.ui = {
// ...continueConfig.ui,
// codeBlockToolbarPosition: sharedConfig.codeBlockToolbarPosition,
// fontSize: sharedConfig.fontSize,
// codeWrap: sharedConfig.codeWrap,
// displayRawMarkdown: sharedConfig.displayRawMarkdown,
// showChatScrollbar: sharedConfig.showChatScrollbar,
// };
// continueConfig.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
// continueConfig.disableIndexing = sharedConfig.disableIndexing;
// continueConfig.disableIndexing = sharedConfig.disableIndexing;
// continueConfig.disableSessionTitles = sharedConfig.disableSessionTitles;
// continueConfig.experimental = {
// ...continueConfig.experimental,
// useChromiumForDocsCrawling: sharedConfig.useChromiumForDocsCrawling,
// readResponseTTS: sharedConfig.readResponseTTS,
// promptPath: sharedConfig.promptPath,
// };

View file

@ -956,7 +956,7 @@ declare global {
fixGrammar?: string;
}
interface ModelRoles {
interface ExperimentalModelRoles {
inlineEdit?: string;
applyCodeBlock?: string;
repoMapFileSelection?: string;
@ -1024,7 +1024,7 @@ declare global {
interface ExperimentalConfig {
contextMenuPrompts?: ContextMenuConfig;
modelRoles?: ModelRoles;
modelRoles?: ExperimentalModelRoles;
defaultContext?: DefaultContextProvider[];
promptPath?: string;

View file

@ -1,4 +1,4 @@
import { execSync } from "child_process";
import fs from "fs";
import os from "os";
import {
@ -7,11 +7,13 @@ import {
IDE,
ILLM,
ModelDescription,
ModelRoles,
ExperimentalModelRoles,
} from "../";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigJson } from "../util/paths";
import { ConfigHandler } from "./ConfigHandler";
function stringify(obj: any, indentation?: number): string {
return JSON.stringify(
obj,
@ -22,19 +24,30 @@ function stringify(obj: any, indentation?: number): string {
);
}
export function addContextProvider(provider: ContextProviderWithParams) {
export function addContextProvider(provider: ContextProviderWithParams, configHandler?: ConfigHandler) {
let isAdded = false;
editConfigJson((config) => {
if (!config.contextProviders) {
config.contextProviders = [provider];
} else {
config.contextProviders = [];
}
if (!config.contextProviders.some((p) => p.name === provider.name)) {
config.contextProviders.push(provider);
isAdded = true;
}
return config;
});
if (isAdded && configHandler) {
void configHandler.reloadConfig();
}
}
export function addModel(model: ModelDescription, role?: keyof ModelRoles) {
export function addModel(
model: ModelDescription,
role?: keyof ExperimentalModelRoles,
) {
editConfigJson((config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
return config;
@ -85,7 +98,7 @@ export function deleteModel(title: string) {
});
}
export function getModelByRole<T extends keyof ModelRoles>(
export function getModelByRole<T extends keyof ExperimentalModelRoles>(
config: ContinueConfig,
role: T,
): ILLM | undefined {
@ -108,11 +121,13 @@ export function getModelByRole<T extends keyof ModelRoles>(
*
* See here for details: https://github.com/continuedev/continue/issues/940
*/
export function isSupportedLanceDbCpuTarget(ide: IDE) {
export function isSupportedLanceDbCpuTargetForLinux(ide?: IDE) {
const CPU_FEATURES_TO_CHECK = ["avx2", "fma"] as const;
const globalContext = new GlobalContext();
const globalContextVal = globalContext.get("isSupportedLanceDbCpuTarget");
const globalContextVal = globalContext.get(
"isSupportedLanceDbCpuTargetForLinux",
);
// If we've already checked the CPU target, return the cached value
if (globalContextVal !== undefined) {
@ -120,51 +135,35 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) {
}
const arch = os.arch();
const platform = os.platform();
// This check only applies to x64
//https://github.com/lancedb/lance/issues/2195#issuecomment-2057841311
if (arch !== "x64") {
globalContext.update("isSupportedLanceDbCpuTarget", true);
globalContext.update("isSupportedLanceDbCpuTargetForLinux", true);
return true;
}
try {
const cpuFlags = (() => {
switch (platform) {
case "darwin":
return execSync("sysctl -n machdep.cpu.features")
.toString()
.toLowerCase();
case "linux":
return execSync("cat /proc/cpuinfo").toString().toLowerCase();
case "win32":
return execSync("wmic cpu get caption /format:list")
.toString()
.toLowerCase();
default:
return "";
}
})();
const cpuFlags = fs.readFileSync("/proc/cpuinfo", "utf-8").toLowerCase();
const isSupportedLanceDbCpuTarget = cpuFlags
const isSupportedLanceDbCpuTargetForLinux = cpuFlags
? CPU_FEATURES_TO_CHECK.every((feature) => cpuFlags.includes(feature))
: true;
// If it's not a supported CPU target, and it's the first time we are checking,
// show a toast to inform the user that we are going to disable indexing.
if (!isSupportedLanceDbCpuTarget) {
if (!isSupportedLanceDbCpuTargetForLinux && ide) {
// We offload our async toast to `showUnsupportedCpuToast` to prevent making
// our config loading async upstream of `isSupportedLanceDbCpuTarget`
// our config loading async upstream of `isSupportedLanceDbCpuTargetForLinux`
void showUnsupportedCpuToast(ide);
}
globalContext.update(
"isSupportedLanceDbCpuTarget",
isSupportedLanceDbCpuTarget,
"isSupportedLanceDbCpuTargetForLinux",
isSupportedLanceDbCpuTargetForLinux,
);
return isSupportedLanceDbCpuTarget;
return isSupportedLanceDbCpuTargetForLinux;
} catch (error) {
// If we can't determine CPU features, default to true
return true;
@ -174,11 +173,13 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) {
async function showUnsupportedCpuToast(ide: IDE) {
const shouldOpenLink = await ide.showToast(
"warning",
"Codebase indexing is disabled due to CPU incompatibility",
"Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)",
"Learn more",
);
if (shouldOpenLink) {
void ide.openUrl("https://github.com/continuedev/continue/pull/3551");
void ide.openUrl(
"https://docs.continue.dev/troubleshooting#i-received-a-codebase-indexing-disabled---your-linux-system-lacks-required-cpu-features-avx2-fma-notification",
);
}
}

View file

@ -1,40 +0,0 @@
import {
clientRender,
PlatformClient,
SecretStore,
} from "@continuedev/config-yaml";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
export async function clientRenderHelper(
unrolledAssistant: string,
ide: IDE,
controlPlaneClient: ControlPlaneClient,
) {
const ideSecretStore: SecretStore = {
get: async function (secretName: string): Promise<string | undefined> {
const results = await ide.readSecrets([secretName]);
return results[secretName];
},
set: async function (
secretName: string,
secretValue: string,
): Promise<void> {
return await ide.writeSecrets({
[secretName]: secretValue,
});
},
};
const platformClient: PlatformClient = {
resolveFQSNs: controlPlaneClient.resolveFQSNs.bind(controlPlaneClient),
};
const userId = await controlPlaneClient.userId;
return await clientRender(
unrolledAssistant,
ideSecretStore,
userId ? platformClient : undefined,
);
}

View file

@ -1,5 +1,4 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas";
import { ModelConfig, AssistantUnrolled } from "@continuedev/config-yaml";
import { SerializedContinueConfig } from "../..";
@ -16,10 +15,11 @@ export function convertConfigJsonToConfigYaml(
name: model.title,
// defaultCompletionOptions: model.completionOptions,
provider: model.provider,
roles: ["chat"],
roles: ["chat", "edit", "apply", "summarize"],
}),
),
// ... tabAutocompleteModels
// TODO
// tabAutocompleteModels
// embeddingsModels
// rerankModels
],

View file

@ -1,4 +1,4 @@
import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas";
import { AssistantUnrolled } from "@continuedev/config-yaml";
// TODO
export const defaultConfigYaml: AssistantUnrolled = {

View file

@ -3,22 +3,26 @@ import fs from "node:fs";
import {
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
ModelRole,
parseAssistantUnrolled,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
SlashCommand,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
import { AllRerankers } from "../../context/allRerankers";
import { MCPManagerSingleton } from "../../context/mcp";
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider";
@ -28,16 +32,14 @@ import FreeTrial from "../../llm/llms/FreeTrial";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { allTools } from "../../tools";
import { GlobalContext } from "../../util/GlobalContext";
import { getConfigYamlPath } from "../../util/paths";
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { slashFromCustomCommand } from "../../commands";
import { allTools } from "../../tools";
import { clientRenderHelper } from "./clientRender";
import { llmsFromModelConfig } from "./models";
import { GlobalContext } from "../../util/GlobalContext";
import { modifyContinueConfigWithSharedConfig } from "../sharedConfig";
async function loadConfigYaml(
workspaceConfigs: string[],
@ -46,9 +48,14 @@ async function loadConfigYaml(
ide: IDE,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<AssistantUnrolled>> {
// const ideSettings = await ide.getIdeSettings();
let config =
overrideConfigYaml ??
(await clientRenderHelper(rawYaml, ide, controlPlaneClient));
// (ideSettings.continueTestEnvironment === "production"
// ? await clientRenderHelper(rawYaml, ide, controlPlaneClient)
// :
parseAssistantUnrolled(rawYaml);
// );
const errors = validateConfigYaml(config);
if (errors?.some((error) => error.fatal)) {
@ -91,22 +98,22 @@ async function configYamlToContinueConfig(
config: AssistantUnrolled,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
allowFreeTrial: boolean = true,
): Promise<ContinueConfig> {
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
const continueConfig: ContinueConfig = {
slashCommands: [
...(await slashCommandsFromV1PromptFiles(ide)),
...(config.prompts?.map(slashFromCustomCommand) ?? []),
],
models: [],
tabAutocompleteModels: [],
tools: allTools,
systemMessage: config.rules?.join("\n"),
embeddingsProvider: new TransformersJsEmbeddingsProvider(),
experimental: {
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
transport: {
@ -124,41 +131,123 @@ async function configYamlToContinueConfig(
faviconUrl: doc.faviconUrl,
})),
contextProviders: [],
modelsByRole: {
chat: [],
edit: [],
apply: [],
embed: [],
autocomplete: [],
rerank: [],
summarize: [],
},
selectedModelByRole: {
chat: null, // not currently used - defaultModel on GUI is used
edit: null, // not currently used
apply: null,
embed: null,
autocomplete: null,
rerank: null,
summarize: null,
},
data: config.data,
};
// Models
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
if (
["chat", "summarize", "apply", "edit"].some((role: any) =>
model.roles?.includes(role),
)
) {
// Main model array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
//
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
continueConfig.models.push(...llms);
}
if (model.roles?.includes("autocomplete")) {
// Autocomplete models array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.tabAutocompleteModels?.push(...llms);
if (model.roles?.includes("chat")) {
continueConfig.modelsByRole.chat.push(...llms);
}
if (model.roles?.includes("summarize")) {
continueConfig.modelsByRole.summarize.push(...llms);
}
if (model.roles?.includes("apply")) {
continueConfig.modelsByRole.apply.push(...llms);
}
if (model.roles?.includes("edit")) {
continueConfig.modelsByRole.edit.push(...llms);
}
if (model.roles?.includes("autocomplete")) {
continueConfig.modelsByRole.autocomplete.push(...llms);
}
if (model.roles?.includes("embed")) {
const { provider, ...options } = model;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
continueConfig.modelsByRole.embed.push(new embeddingsProviderClass());
} else {
continueConfig.modelsByRole.embed.push(
new embeddingsProviderClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
),
);
}
} else {
errors.push({
fatal: false,
message: `Unsupported embeddings model provider found: ${provider}`,
});
}
}
if (model.roles?.includes("rerank")) {
const { provider, ...options } = model;
const rerankerClass = AllRerankers[provider];
if (rerankerClass) {
continueConfig.modelsByRole.rerank.push(
new rerankerClass(options, (url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
),
);
} else {
errors.push({
fatal: false,
message: `Unsupported reranking model provider found: ${provider}`,
});
}
}
}
// Add transformers js to the embed models in vs code if not already added
if (
ideInfo.ideType === "vscode" &&
!continueConfig.modelsByRole.embed.find(
(m) => m.providerName === "transformers.js",
)
) {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
}
if (allowFreeTrial) {
@ -179,8 +268,6 @@ async function configYamlToContinueConfig(
);
}
// TODO: Split into model roles.
// Context providers
const codebaseContextParams: IContextProvider[] =
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
@ -210,92 +297,69 @@ async function configYamlToContinueConfig(
.filter((p) => !!p) ?? []) as IContextProvider[];
continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
// Embeddings Provider
const embedConfig = config.models?.find((model) =>
model.roles?.includes("embed"),
);
if (embedConfig) {
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
continueConfig.embeddingsProvider = new embeddingsProviderClass();
} else {
continueConfig.embeddingsProvider = new embeddingsProviderClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
);
}
}
}
// Reranker
const rerankConfig = config.models?.find((model) =>
model.roles?.includes("rerank"),
);
if (rerankConfig) {
const { provider, ...options } = rerankConfig;
const rerankerClass = AllRerankers[provider];
if (rerankerClass) {
continueConfig.reranker = new rerankerClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
);
}
if (
continueConfig.docs?.length &&
!continueConfig.contextProviders?.some(
(cp) => cp.description.title === "docs",
)
) {
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
config.mcpServers?.forEach(async (server) => {
const mcpId = server.name;
const mcpConnection = mcpManager.createConnection(mcpId, {
transport: {
type: "stdio",
args: [],
...server,
},
});
if (!mcpConnection) {
return;
}
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
2000,
);
try {
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
);
} catch (e: any) {
if (e.name !== "AbortError") {
throw e;
await Promise.all(
config.mcpServers?.map(async (server) => {
const mcpId = server.name;
const mcpConnection = mcpManager.createConnection(mcpId, {
transport: {
type: "stdio",
args: [],
...server,
},
});
if (!mcpConnection) {
return;
}
}
clearTimeout(mcpConnectionTimeout);
});
return continueConfig;
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
5000,
);
try {
const mcpError = await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
server.name,
server.faviconUrl,
);
if (mcpError) {
errors.push(mcpError);
}
} catch (e: any) {
errors.push({
fatal: false,
message: `Failed to load MCP server: ${e.message}`,
});
if (e.name !== "AbortError") {
throw e;
}
}
clearTimeout(mcpConnectionTimeout);
}) ?? [],
);
return { config: continueConfig, errors };
}
export async function loadContinueConfigFromYaml(
ide: IDE,
workspaceConfigs: string[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -305,7 +369,7 @@ export async function loadContinueConfigFromYaml(
): Promise<ConfigResult<ContinueConfig>> {
const rawYaml =
overrideConfigYaml === undefined
? fs.readFileSync(getConfigYamlPath(ideType), "utf-8")
? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8")
: "";
const configYamlResult = await loadConfigYaml(
@ -324,10 +388,11 @@ export async function loadContinueConfigFromYaml(
};
}
const continueConfig = await configYamlToContinueConfig(
const { config: continueConfig, errors } = await configYamlToContinueConfig(
configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -346,16 +411,14 @@ export async function loadContinueConfigFromYaml(
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyContinueConfigWithSharedConfig(
const withShared = modifyAnyConfigWithSharedConfig(
continueConfig,
sharedConfig,
);
return {
config: withShared,
errors: configYamlResult.errors,
errors: [...(configYamlResult.errors ?? []), ...errors],
configLoadInterrupted: false,
};
}
export { type BrowserSerializedContinueConfig };

View file

@ -35,15 +35,6 @@ async function modelConfigToBaseLLM(
return undefined;
}
const usingContinueProxy = model.provider === "continue-proxy";
const modelName = usingContinueProxy
? getContinueProxyModelName(
platformConfigMetadata!.ownerSlug,
platformConfigMetadata!.packageSlug,
model,
)
: model.model;
let options: LLMOptions = {
...model,
completionOptions: {
@ -56,10 +47,59 @@ async function modelConfigToBaseLLM(
writeLog,
uniqueId,
title: model.name,
model: modelName,
systemMessage,
promptTemplates: model.promptTemplates,
};
if (model.embedOptions?.maxBatchSize) {
options.maxEmbeddingBatchSize = model.embedOptions.maxBatchSize;
}
if (model.embedOptions?.maxChunkSize) {
options.maxEmbeddingChunkSize = model.embedOptions.maxChunkSize;
}
// These are params that are at model config level in JSON
// But we decided to move to nested `env` in YAML
// Since types vary and we don't want to blindly spread env for now,
// Each one is handled individually here
const env = model.env ?? {};
if (
"useLegacyCompletionsEndpoint" in env &&
typeof env.useLegacyCompletionsEndpoint === "boolean"
) {
options.useLegacyCompletionsEndpoint = env.useLegacyCompletionsEndpoint;
}
if ("apiType" in env && typeof env.apiType === "string") {
options.apiType = env.apiType;
}
if ("apiVersion" in env && typeof env.apiVersion === "string") {
options.apiVersion = env.apiVersion;
}
if ("deployment" in env && typeof env.deployment === "string") {
options.deployment = env.deployment;
}
if ("deploymentId" in env && typeof env.deploymentId === "string") {
options.deploymentId = env.deploymentId;
}
if ("projectId" in env && typeof env.projectId === "string") {
options.projectId = env.projectId;
}
if ("region" in env && typeof env.region === "string") {
options.region = env.region;
}
if ("profile" in env && typeof env.profile === "string") {
options.profile = env.profile;
}
if ("modelArn" in env && typeof env.modelArn === "string") {
options.modelArn = env.modelArn;
}
if ("aiGatewaySlug" in env && typeof env.aiGatewaySlug === "string") {
options.aiGatewaySlug = env.aiGatewaySlug;
}
if ("accountId" in env && typeof env.accountId === "string") {
options.accountId = env.accountId;
}
const llm = new cls(options);
return llm;
}

View file

@ -69,10 +69,14 @@ class MCPConnection {
private constructTransport(options: MCPOptions): Transport {
switch (options.transport.type) {
case "stdio":
const env: Record<string, string> = options.transport.env || {};
if (process.env.PATH !== undefined) {
env.PATH = process.env.PATH;
}
return new StdioClientTransport({
command: options.transport.command,
args: options.transport.args,
env: options.transport.env,
env,
});
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
@ -117,6 +121,8 @@ class MCPConnection {
config: ContinueConfig,
mcpId: string,
signal: AbortSignal,
name: string,
faviconUrl: string | undefined,
): Promise<ConfigValidationError | undefined> {
try {
await Promise.race([
@ -148,6 +154,7 @@ class MCPConnection {
title: resource.name,
description: resource.description,
id: resource.uri,
icon: faviconUrl,
}));
if (!config.contextProviders) {
@ -157,6 +164,7 @@ class MCPConnection {
config.contextProviders.push(
new MCPContextProvider({
submenuItems,
mcpId,
}),
);
}
@ -165,19 +173,20 @@ class MCPConnection {
if (capabilities?.tools) {
const { tools } = await this.client.listTools({}, { signal });
const continueTools: Tool[] = tools.map((tool: any) => ({
displayTitle: tool.name,
displayTitle: name + " " + tool.name,
function: {
description: tool.description,
name: tool.name,
parameters: tool.inputSchema,
},
faviconUrl,
readonly: false,
type: "function",
wouldLikeTo: `use the ${tool.name} tool`,
wouldLikeTo: `use the ${name} ${tool.name} tool`,
uri: encodeMCPToolUri(mcpId, tool.name),
}));
config.tools = [...config.tools, ...continueTools];
config.tools = [...continueTools, ...config.tools];
}
// Prompts <—> Slash commands

View file

@ -24,8 +24,12 @@ class CodeContextProvider extends BaseContextProvider {
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Assume the query is the id as returned by loadSubmenuItems
const workspaceDirs = await extras.ide.getWorkspaceDirs();
return [
await CodeSnippetsCodebaseIndex.getForId(Number.parseInt(query, 10)),
await CodeSnippetsCodebaseIndex.getForId(
Number.parseInt(query, 10),
workspaceDirs,
),
];
}

View file

@ -4,7 +4,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../";
import { getUriPathBasename } from "../../util/uri";
import { getUriDescription } from "../../util/uri";
class CurrentFileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -23,12 +23,27 @@ class CurrentFileContextProvider extends BaseContextProvider {
if (!currentFile) {
return [];
}
const baseName = getUriPathBasename(currentFile.path);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
currentFile.path,
await extras.ide.getWorkspaceDirs(),
);
let prefix = "This is the currently open file:";
let name = baseName;
// This allows frontend to retrieve when using alt + enter or default context with slightly different copy
if (query === "non-mention-usage") {
prefix =
"The following file is currently open. Don't reference it if it's not relevant to the user's message:";
name = "Active file: " + baseName;
}
return [
{
description: currentFile.path,
content: `This is the currently open file:\n\n\`\`\`${baseName}\n${currentFile.contents}\n\`\`\``,
name: baseName,
description: last2Parts,
content: `${prefix}\n\n\`\`\`${relativePathOrBasename}\n${currentFile.contents}\n\`\`\``,
name,
uri: {
type: "file",
value: currentFile.path,

View file

@ -23,7 +23,7 @@ class DocsContextProvider extends BaseContextProvider {
// Todo: consider a different renderInline so that when multiple docs are referenced in one message,
// Or the doc has an odd name unrelated to the content
// The name of the doc itself doesn't skew the embedding results
// renderInlineAs: "<docs-context-provider>",
renderInlineAs: "",
};
constructor(options: any) {

View file

@ -10,6 +10,7 @@ import { walkDirs } from "../../indexing/walkDir";
import {
getUriPathBasename,
getShortestUniqueRelativeUriPaths,
getUriDescription,
} from "../../util/uri";
const MAX_SUBMENU_ITEMS = 10_000;
@ -27,16 +28,22 @@ class FileContextProvider extends BaseContextProvider {
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Assume the query is a filepath
query = query.trim();
const content = await extras.ide.readFile(query);
const fileUri = query.trim();
const content = await extras.ide.readFile(fileUri);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
fileUri,
await extras.ide.getWorkspaceDirs(),
);
return [
{
name: query.split(/[\\/]/).pop() ?? query,
description: query,
content: `\`\`\`${query}\n${content}\n\`\`\``,
name: baseName,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``,
uri: {
type: "file",
value: query,
value: fileUri,
},
},
];

View file

@ -9,6 +9,7 @@ import {
import { MCPManagerSingleton } from "../mcp";
interface MCPContextProviderOptions {
mcpId: string;
submenuItems: ContextSubmenuItem[];
}
@ -74,10 +75,10 @@ class MCPContextProvider extends BaseContextProvider {
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
return (this.options as MCPContextProviderOptions).submenuItems.map(
(item, index) => ({
(item) => ({
...item,
id: JSON.stringify({
mcpId: String(index),
mcpId: (this.options as MCPContextProviderOptions).mcpId,
uri: item.id,
}),
}),

View file

@ -3,7 +3,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { findUriInDirs, getUriPathBasename } from "../../util/uri.js";
import { getUriDescription } from "../../util/uri.js";
import { BaseContextProvider } from "../index.js";
class OpenFilesContextProvider extends BaseContextProvider {
@ -24,14 +24,17 @@ class OpenFilesContextProvider extends BaseContextProvider {
? await ide.getPinnedFiles()
: await ide.getOpenFiles();
const workspaceDirs = await extras.ide.getWorkspaceDirs();
return await Promise.all(
openFiles.map(async (filepath: string) => {
const content = await ide.readFile(filepath);
const { relativePathOrBasename, last2Parts, baseName } =
getUriDescription(filepath, workspaceDirs);
return {
description: filepath,
content: `\`\`\`${
findUriInDirs(filepath, workspaceDirs).relativePathOrBasename
}\n${await ide.readFile(filepath)}\n\`\`\``,
name: getUriPathBasename(filepath),
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``,
name: baseName,
uri: {
type: "file",
value: filepath,

View file

@ -3,7 +3,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { getUriPathBasename } from "../../util/uri.js";
import { getUriDescription } from "../../util/uri.js";
import { BaseContextProvider } from "../index.js";
class ProblemsContextProvider extends BaseContextProvider {
@ -20,10 +20,14 @@ class ProblemsContextProvider extends BaseContextProvider {
): Promise<ContextItem[]> {
const ide = extras.ide;
const problems = await ide.getProblems();
const workspaceDirs = await ide.getWorkspaceDirs();
const items = await Promise.all(
problems.map(async (problem) => {
const fileName = getUriPathBasename(problem.filepath);
const { relativePathOrBasename, baseName } = getUriDescription(
problem.filepath,
workspaceDirs,
);
const content = await ide.readFile(problem.filepath);
const lines = content.split("\n");
const rangeContent = lines
@ -35,8 +39,8 @@ class ProblemsContextProvider extends BaseContextProvider {
return {
description: "Problems in current file",
content: `\`\`\`${fileName}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
name: `Warning in ${fileName}`,
content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
name: `Warning in ${baseName}`,
};
}),
);

View file

@ -7,7 +7,6 @@ import {
IContextProvider,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { ControlPlaneClient } from "../../control-plane/client";
import { TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
@ -31,8 +30,9 @@ async function getContextProviderExtras(
ide,
ideSettingsPromise,
async (text) => {},
new ControlPlaneClient(Promise.resolve(undefined), ideSettingsPromise),
Promise.resolve(undefined),
);
await configHandler.initializedPromise;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not found");
@ -42,10 +42,10 @@ async function getContextProviderExtras(
fullInput,
ide,
config,
embeddingsProvider: config.embeddingsProvider,
embeddingsProvider: config.selectedModelByRole.embed,
fetch: fetch,
llm: config.models[0],
reranker: config.reranker,
reranker: config.selectedModelByRole.rerank,
selectedCode: [],
};
}

View file

@ -7,6 +7,8 @@ import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCod
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
const DEFAULT_CHUNK_SIZE = 384;
export interface RetrievalPipelineOptions {
llm: ILLM;
config: ContinueConfig;
@ -16,13 +18,13 @@ export interface RetrievalPipelineOptions {
nFinal: number;
tags: BranchAndDir[];
filterDirectory?: string;
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
}
export interface RetrievalPipelineRunArguments {
query: string;
tags: BranchAndDir[];
filterDirectory?: string;
includeEmbeddings: boolean;
}
export interface IRetrievalPipeline {
@ -31,12 +33,21 @@ export interface IRetrievalPipeline {
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private ftsIndex = new FullTextSearchCodebaseIndex();
private lanceDbIndex: LanceDbIndex;
private lanceDbIndex: LanceDbIndex | null = null;
constructor(protected readonly options: RetrievalPipelineOptions) {
this.lanceDbIndex = new LanceDbIndex(
options.config.embeddingsProvider,
(uri) => options.ide.readFile(uri),
void this.initLanceDb();
}
private async initLanceDb() {
const embedModel = this.options.config.selectedModelByRole.embed;
if (!embedModel) {
return;
}
this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) =>
this.options.ide.readFile(uri),
);
}
@ -60,6 +71,11 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
return trigrams;
}
private escapeFtsQueryString(query: string): string {
const escapedDoubleQuotes = query.replace(/"/g, '""');
return `"${escapedDoubleQuotes}"`;
}
protected async retrieveFts(
args: RetrievalPipelineRunArguments,
n: number,
@ -69,7 +85,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
return [];
}
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
const tokens = this.escapeFtsQueryString(tokensRaw);
return await this.ftsIndex.retrieve({
n,
@ -109,7 +126,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
filepath,
contents,
maxChunkSize:
this.options.config.embeddingsProvider.maxEmbeddingChunkSize,
this.options.config.selectedModelByRole.embed
?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE,
digest: filepath,
});
@ -125,6 +143,13 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
input: string,
n: number,
): Promise<Chunk[]> {
if (!this.lanceDbIndex) {
console.warn(
"LanceDB index not available, skipping embeddings retrieval",
);
return [];
}
return this.lanceDbIndex.retrieve(
input,
n,

View file

@ -9,7 +9,7 @@ import BaseRetrievalPipeline, {
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
const { input, nFinal, filterDirectory, includeEmbeddings } = this.options;
const { input, nFinal, filterDirectory, config } = this.options;
// We give 1/4 weight to recently edited files, 1/4 to full text search,
// and the remaining 1/2 to embeddings
@ -21,7 +21,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
const embeddingsChunks = includeEmbeddings
const embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];

View file

@ -12,13 +12,12 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
private async _retrieveInitial(
args: RetrievalPipelineRunArguments,
): Promise<Chunk[]> {
const { input, nRetrieve, filterDirectory, includeEmbeddings } =
this.options;
const { input, nRetrieve, filterDirectory, config } = this.options;
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(args, nRetrieve);
const embeddingsChunks = includeEmbeddings
const embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
const recentlyEditedFilesChunks =
@ -42,7 +41,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen
retrievalResults = retrievalResults.filter(
(chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]),
(chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir,
);
}
@ -53,17 +52,18 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
}
private async _rerank(input: string, chunks: Chunk[]): Promise<Chunk[]> {
if (!this.options.config.reranker) {
throw new Error("No reranker provided");
if (!this.options.config.selectedModelByRole.rerank) {
throw new Error("No reranker set up");
}
// remove empty chunks -- some APIs fail on that
chunks = chunks.filter((chunk) => chunk.content);
let scores: number[] = await this.options.config.reranker.rerank(
input,
chunks,
);
let scores: number[] =
await this.options.config.selectedModelByRole.rerank.rerank(
input,
chunks,
);
// Filter out low-scoring results
let results = chunks;

View file

@ -2,7 +2,6 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
import { getModelByRole } from "../../config/util";
import generateRepoMap from "../../util/generateRepoMap";
import { renderChatMessage } from "../../util/messageContent";
import { getUriPathBasename } from "../../util/uri";
const SUPPORTED_MODEL_TITLE_FAMILIES = [
"claude-3",
@ -16,7 +15,7 @@ function isSupportedModel(
config: ContinueConfig,
modelTitle?: string,
): boolean {
if (config.experimental?.modelRoles?.applyCodeBlock) {
if (config.experimental?.modelRoles?.repoMapFileSelection) {
return true;
}

View file

@ -1,6 +1,5 @@
import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { getUriPathBasename } from "../../util/uri";
import { getUriDescription } from "../../util/uri";
import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils";
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline";
@ -14,26 +13,16 @@ export async function retrieveContextItemsFromEmbeddings(
options: any | undefined,
filterDirectory: string | undefined,
): Promise<ContextItem[]> {
if (!extras.embeddingsProvider) {
return [];
}
// transformers.js not supported in JetBrains IDEs right now
const isJetBrainsAndTransformersJs =
extras.embeddingsProvider.providerName ===
TransformersJsEmbeddingsProvider.providerName &&
(await extras.ide.getIdeInfo()).ideType === "jetbrains";
if (isJetBrainsAndTransformersJs) {
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",
);
}
// Currently you can use codebase without an embeddings provider and it will just skip the embeddings inputs
// if (!extras.embeddingsProvider) {
// void extras.ide.showToast(
// "warning",
// "Set up an embeddings model to use this feature. Visit the docs to learn more: " +
// "https://docs.continue.dev/customize/model-roles/embeddings",
// );
// return [];
// }
const includeEmbeddings = !!extras.config.selectedModelByRole.embed;
// Get tags to retrieve for
const workspaceDirs = await extras.ide.getWorkspaceDirs();
@ -78,7 +67,6 @@ export async function retrieveContextItemsFromEmbeddings(
input: extras.fullInput,
llm: extras.llm,
config: extras.config,
includeEmbeddings: !isJetBrainsAndTransformersJs,
};
const pipeline = new pipelineType(pipelineOptions);
@ -86,16 +74,17 @@ export async function retrieveContextItemsFromEmbeddings(
tags,
filterDirectory,
query: extras.fullInput,
includeEmbeddings,
});
if (results.length === 0) {
if (extras.config.disableIndexing) {
void extras.ide.showToast("warning", "No embeddings results found.");
void extras.ide.showToast("warning", "No results found.");
return [];
} else {
void extras.ide.showToast(
"warning",
"No embeddings results found. If you think this is an error, re-index your codebase.",
"No results found. If you think this is an error, re-index your codebase.",
);
// TODO - add "re-index" option to warning message which clears and reindexes codebase
}
@ -111,18 +100,17 @@ export async function retrieveContextItemsFromEmbeddings(
...results
.sort((a, b) => a.filepath.localeCompare(b.filepath))
.map((r) => {
const basename = getUriPathBasename(r.filepath);
const name = `${basename} (${r.startLine}-${r.endLine})`;
const description = `${r.filepath}`;
const { relativePathOrBasename, last2Parts, baseName } =
getUriDescription(r.filepath, workspaceDirs);
if (basename === "package.json") {
if (baseName === "package.json") {
console.warn("Retrieval pipeline: package.json detected");
}
return {
name,
description,
content: `\`\`\`${name}\n${r.content}\n\`\`\``,
name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``,
uri: {
type: "file" as const,
value: r.filepath,

View file

@ -4,13 +4,14 @@ import { getControlPlaneEnv } from "../env";
export async function getAuthUrlForTokenPage(
ideSettingsPromise: Promise<IdeSettings>,
useOnboarding: boolean,
): Promise<string> {
const env = await getControlPlaneEnv(ideSettingsPromise);
const url = new URL("https://api.workos.com/user_management/authorize");
const params = {
response_type: "code",
client_id: env.WORKOS_CLIENT_ID,
redirect_uri: `${env.APP_URL}tokens/callback`,
redirect_uri: `${env.APP_URL}tokens/${useOnboarding ? "onboarding-" : ""}callback`,
// redirect_uri: "http://localhost:3000/tokens/callback",
state: uuidv4(),
provider: "authkit",

View file

@ -40,7 +40,10 @@ export class ControlPlaneClient {
private readonly ideSettingsPromise: Promise<IdeSettings>,
) {}
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
async resolveFQSNs(
fqsns: FQSN[],
orgScopeId: string | null,
): Promise<(SecretResult | undefined)[]> {
const userId = await this.userId;
if (!userId) {
throw new Error("No user id");
@ -48,7 +51,7 @@ export class ControlPlaneClient {
const resp = await this.request("ide/sync-secrets", {
method: "POST",
body: JSON.stringify({ fqsns }),
body: JSON.stringify({ fqsns, orgScopeId }),
});
return (await resp.json()) as any;
}
@ -104,7 +107,7 @@ export class ControlPlaneClient {
}
}
public async listAssistants(organizationId?: string): Promise<
public async listAssistants(organizationId: string | null): Promise<
{
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
@ -132,38 +135,37 @@ export class ControlPlaneClient {
}
public async listOrganizations(): Promise<Array<OrganizationDescription>> {
return [
{
id: "1",
iconUrl:
"https://cdn.prod.website-files.com/663e06c56841363663ffbbcf/663e1b9fb023f0b622ad3608_log-text.svg",
name: "Continue",
},
];
// const userId = await this.userId;
// if (!userId) {
// return [];
// }
const userId = await this.userId;
// try {
// const resp = await this.request("ide/list-organizations", {
// method: "GET",
// });
// const { organizations } = (await resp.json()) as any;
// return organizations;
// } catch (e) {
// return [];
// }
if (!userId) {
return [];
}
try {
const resp = await this.request("ide/list-organizations", {
method: "GET",
});
const { organizations } = (await resp.json()) as any;
return organizations;
} catch (e) {
return [];
}
}
public async listAssistantFullSlugs(): Promise<FullSlug[] | null> {
public async listAssistantFullSlugs(
organizationId: string | null,
): Promise<FullSlug[] | null> {
const userId = await this.userId;
if (!userId) {
return null;
}
const url = organizationId
? `ide/list-assistant-full-slugs?organizationId=${organizationId}`
: "ide/list-assistant-full-slugs";
try {
const resp = await this.request("ide/list-assistant-full-slugs", {
const resp = await this.request(url, {
method: "GET",
});
const { fullSlugs } = (await resp.json()) as any;
@ -184,21 +186,4 @@ export class ControlPlaneClient {
});
return ((await resp.json()) as any).settings;
}
async syncSecrets(secretNames: string[]): Promise<Record<string, string>> {
const userId = await this.userId;
if (!userId) {
throw new Error("No user id");
}
try {
const resp = await this.request("ide/sync-secrets", {
method: "POST",
body: JSON.stringify({ secretNames }),
});
return (await resp.json()) as any;
} catch (e) {
return {};
}
}
}

View file

@ -1,4 +1,6 @@
import * as fs from "node:fs";
import { IdeSettings } from "..";
import { getStagingEnvironmentDotFilePath } from "../util/paths";
export interface ControlPlaneEnv {
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
@ -35,13 +37,11 @@ const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
};
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,
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/",
CONTROL_PLANE_URL: "https://api.continue-stage.tools/",
AUTH_TYPE: WORKOS_ENV_ID_STAGING,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "https://app-preview.continue.dev/",
APP_URL: "https://hub.continue-stage.tools/",
};
const TEST_ENV: ControlPlaneEnv = {
@ -60,21 +60,37 @@ const LOCAL_ENV: ControlPlaneEnv = {
APP_URL: "http://localhost:3000/",
};
export async function enableHubContinueDev() {
return true;
}
export async function getControlPlaneEnv(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<ControlPlaneEnv> {
const ideSettings = await ideSettingsPromise;
return getControlPlaneEnvSync(ideSettings.continueTestEnvironment);
return getControlPlaneEnvSync(
ideSettings.continueTestEnvironment,
ideSettings.enableControlServerBeta,
);
}
export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
enableControlServerBeta: IdeSettings["enableControlServerBeta"],
): ControlPlaneEnv {
if (fs.existsSync(getStagingEnvironmentDotFilePath())) {
return STAGING_ENV;
}
if (enableControlServerBeta === true) {
return PRODUCTION_ENV;
}
const env =
ideTestEnvironment === "production"
? "hub"
: ideTestEnvironment === "test"
? "test"
: ideTestEnvironment === "staging"
? "staging"
: ideTestEnvironment === "local"
? "local"
: process.env.CONTROL_PLANE_ENV;
@ -94,5 +110,8 @@ export async function useHub(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<boolean> {
const ideSettings = await ideSettingsPromise;
if (ideSettings.enableControlServerBeta) {
return false;
}
return ideSettings.continueTestEnvironment !== "none";
}

View file

@ -11,15 +11,17 @@ import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import {
setupBestConfig,
setupLocalConfig,
setupLocalConfigAfterFreeTrial,
setupQuickstartConfig,
} from "./config/onboarding";
import { addContextProvider, addModel, deleteModel } from "./config/util";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { ControlPlaneClient } from "./control-plane/client";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
import { DataLogger } from "./data/log";
import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
@ -30,14 +32,12 @@ import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { logDevData } from "./util/devdata";
import { DevDataSqliteDb } from "./util/devdataSqlite";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import {
editConfigJson,
getConfigJsonPath,
setupInitialDotContinueDirectory,
migrateV1DevDataFiles,
} from "./util/paths";
import { localPathToUri } from "./util/pathToUri";
import { Telemetry } from "./util/posthog";
@ -57,13 +57,11 @@ import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
configHandler: ConfigHandler;
codebaseIndexerPromise: Promise<CodebaseIndexer>;
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
codebaseIndexingState: IndexingProgressUpdate;
controlPlaneClient: ControlPlaneClient;
private docsService: DocsService;
private globalContext = new GlobalContext();
@ -73,10 +71,6 @@ export class Core {
private abortedMessageIds: Set<string> = new Set();
private async config() {
return (await this.configHandler.loadConfig()).config;
}
invoke<T extends keyof ToCoreProtocol>(
messageType: T,
data: ToCoreProtocol[T][0],
@ -100,7 +94,7 @@ export class Core {
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
migrateV1DevDataFiles();
this.codebaseIndexingState = {
status: "loading",
@ -108,22 +102,18 @@ export class Core {
progress: 0,
};
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
silent: true,
useOnboarding: false,
});
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
);
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.onWrite,
this.controlPlaneClient,
sessionInfoPromise,
);
this.docsService = DocsService.createSingleton(
@ -136,14 +126,34 @@ export class Core {
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
result: serializedResult,
profileId: this.configHandler.currentProfile.profileDescription.id,
profileId:
this.configHandler.currentProfile?.profileDescription.id ?? null,
});
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
if (additionalProviders.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: additionalProviders,
});
}
});
this.configHandler.onDidChangeAvailableProfiles((profiles) =>
this.messenger.send("didChangeAvailableProfiles", { profiles }),
this.configHandler.onDidChangeAvailableProfiles(
(profiles, selectedProfileId) =>
this.messenger.send("didChangeAvailableProfiles", {
profiles,
selectedProfileId,
}),
);
// Dev Data Logger
const dataLogger = DataLogger.getInstance();
dataLogger.core = this;
dataLogger.ideInfoPromise = ideInfoPromise;
dataLogger.ideSettingsPromise = ideSettingsPromise;
// Codebase Indexer and ContinueServerClient depend on IdeSettings
let codebaseIndexerResolve: (_: any) => void | undefined;
this.codebaseIndexerPromise = new Promise(
@ -190,12 +200,10 @@ export class Core {
const getLlm = async () => {
const { config } = await this.configHandler.loadConfig();
const selected = this.globalContext.get("selectedTabAutocompleteModel");
return (
config?.tabAutocompleteModels?.find(
(model) => model.title === selected,
) ?? config?.tabAutocompleteModels?.[0]
);
if (!config) {
return undefined;
}
return config.selectedModelByRole.autocomplete ?? undefined;
};
this.completionProvider = new CompletionProvider(
this.configHandler,
@ -209,18 +217,24 @@ export class Core {
// Note, VsCode's in-process messenger doesn't do anything with this
// It will only show for jetbrains
this.messenger.onError((err) => {
console.error(err);
this.messenger.onError((message, err) => {
void Telemetry.capture("core_messenger_error", {
message: err.message,
stack: err.stack,
});
void this.ide.showToast("error", err.message);
});
on("update/selectTabAutocompleteModel", async (msg) => {
this.globalContext.update("selectedTabAutocompleteModel", msg.data);
void this.configHandler.reloadConfig();
// Again, specifically for jetbrains to prevent duplicate error messages
// The same logic can currently be found in the webview protocol
// bc streaming errors are handled in the GUI
if (
["llm/streamChat", "chatDescriber/describe"].includes(
message.messageType,
)
) {
return;
} else {
void this.ide.showToast("error", err.message);
}
});
// Special
@ -253,8 +267,8 @@ export class Core {
});
// Dev data
on("devdata/log", (msg) => {
logDevData(msg.data.tableName, msg.data.data);
on("devdata/log", async (msg) => {
void DataLogger.getInstance().logDevData(msg.data);
});
// Edit config
@ -270,10 +284,8 @@ export class Core {
});
on("config/newPromptFile", async (msg) => {
await createNewPromptFileV2(
this.ide,
(await this.config())?.experimental?.promptPath,
);
const { config } = await this.configHandler.loadConfig();
await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
await this.configHandler.reloadConfig();
});
@ -294,22 +306,41 @@ export class Core {
return this.configHandler.listProfiles();
});
on("config/refreshProfiles", async (msg) => {
await this.configHandler.loadAssistantsForSelectedOrg();
});
on("config/addContextProvider", async (msg) => {
addContextProvider(msg.data);
addContextProvider(msg.data, this.configHandler);
});
on("config/updateSharedConfig", async (msg) => {
this.globalContext.updateSharedConfig(msg.data);
const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
await this.configHandler.reloadConfig();
return newSharedConfig;
});
on("config/updateSelectedModel", async (msg) => {
const newSelectedModels = this.globalContext.updateSelectedModel(
msg.data.profileId,
msg.data.role,
msg.data.title,
);
await this.configHandler.reloadConfig();
return newSelectedModels;
});
on("controlPlane/openUrl", async (msg) => {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.messenger.request("openUrl", `${env.APP_URL}${msg.data.path}`);
let url = `${env.APP_URL}${msg.data.path}`;
if (msg.data.orgSlug) {
url += `?org=${msg.data.orgSlug}`;
}
await this.messenger.request("openUrl", url);
});
on("controlPlane/listOrganizations", async (msg) => {
return await this.controlPlaneClient.listOrganizations();
return await this.configHandler.listOrganizations();
});
// Context providers
@ -326,7 +357,7 @@ export class Core {
});
on("context/loadSubmenuItems", async (msg) => {
const config = await this.config();
const { config } = await this.configHandler.loadConfig();
if (!config) {
return [];
}
@ -343,17 +374,26 @@ export class Core {
});
on("context/getContextItems", async (msg) => {
const { name, query, fullInput, selectedCode, selectedModelTitle } =
msg.data;
const config = await this.config();
const { config } = await this.configHandler.loadConfig();
if (!config) {
return [];
}
const { name, query, fullInput, selectedCode, selectedModelTitle } =
msg.data;
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
const provider = config.contextProviders?.find(
(provider) => provider.description.title === name,
);
const provider =
config.contextProviders?.find(
(provider) => provider.description.title === name,
) ??
[
// user doesn't need these in their config.json for the shortcuts to work
// option+enter
new CurrentFileContextProvider({}),
// cmd+enter
new CodebaseContextProvider({}),
].find((provider) => provider.description.title === name);
if (!provider) {
return [];
}
@ -367,11 +407,11 @@ export class Core {
const items = await provider.getContextItems(query, {
config,
llm,
embeddingsProvider: config.embeddingsProvider,
embeddingsProvider: config.selectedModelByRole.embed,
fullInput,
ide,
selectedCode,
reranker: config.reranker,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
@ -389,10 +429,35 @@ export class Core {
id,
}));
} catch (e) {
void this.ide.showToast(
"error",
`Error getting context items from ${name}: ${e}`,
);
let knownError = false;
if (e instanceof Error) {
// After removing transformers JS embeddings provider from jetbrains
// Should no longer see this error
// if (e.message.toLowerCase().includes("embeddings provider")) {
// knownError = true;
// const toastOption = "See Docs";
// void this.ide
// .showToast(
// "error",
// `Set up an embeddings model to use @${name}`,
// toastOption,
// )
// .then((userSelection) => {
// if (userSelection === toastOption) {
// void this.ide.openUrl(
// "https://docs.continue.dev/customize/model-roles/embeddings",
// );
// }
// });
// }
}
if (!knownError) {
void this.ide.showToast(
"error",
`Error getting context items from ${name}: ${e}`,
);
}
return [];
}
});
@ -405,7 +470,8 @@ export class Core {
on("config/getSerializedProfileInfo", async (msg) => {
return {
result: await this.configHandler.getSerializedConfig(),
profileId: this.configHandler.currentProfile.profileDescription.id,
profileId:
this.configHandler.currentProfile?.profileDescription.id ?? null,
};
});
@ -590,6 +656,7 @@ export class Core {
params,
historyIndex,
selectedCode,
completionOptions,
} = msg.data;
const { config } = await configHandler.loadConfig();
@ -638,6 +705,7 @@ export class Core {
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
completionOptions,
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
@ -693,6 +761,8 @@ export class Core {
llm,
data.input,
data.language,
false,
undefined,
)) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
@ -724,10 +794,6 @@ export class Core {
editConfigJsonCallback = setupQuickstartConfig;
break;
case "LocalAfterFreeTrial":
editConfigJsonCallback = setupLocalConfigAfterFreeTrial;
break;
case "Best":
editConfigJsonCallback = setupBestConfig;
break;
@ -831,12 +897,18 @@ export class Core {
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
}
});
on("files/deleted", async ({ data }) => {
if (data?.uris?.length) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
}
});
@ -882,11 +954,23 @@ export class Core {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
});
on("didChangeSelectedOrg", (msg) => {
void this.configHandler.setSelectedOrgId(msg.data.id);
void this.configHandler.reloadConfig();
void this.configHandler.loadAssistantsForSelectedOrg();
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
await this.configHandler.updateControlPlaneSessionInfo(
msg.data.sessionInfo,
);
});
on("auth/getAuthUrl", async (msg) => {
const url = await getAuthUrlForTokenPage(ideSettingsPromise);
const url = await getAuthUrlForTokenPage(
ideSettingsPromise,
msg.data.useOnboarding,
);
return { url };
});
@ -924,16 +1008,23 @@ export class Core {
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
const contextItems = await callTool(
tool.uri ?? tool.function.name,
tool,
JSON.parse(toolCall.function.arguments || "{}"),
{
ide: this.ide,
llm,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
},
);
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;
});
}
return { contextItems };
});
}
@ -1017,6 +1108,7 @@ export class Core {
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
this.indexingCancellationController = undefined;
}
// private

View file

@ -5,8 +5,9 @@ import sqlite3 from "sqlite3";
import { DatabaseConnection } from "../indexing/refreshIndex.js";
import { getDevDataSqlitePath } from "./paths.js";
import { getDevDataSqlitePath } from "../util/paths.js";
/* The Dev Data SQLITE table is only used for local tokens generated */
export class DevDataSqliteDb {
static db: DatabaseConnection | null = null;

226
core/data/log.ts Normal file
View file

@ -0,0 +1,226 @@
import fs from "fs";
import path from "path";
import {
allDevEventNames,
DataLogLevel,
DevDataLogEvent,
devDataVersionedSchemas,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as URI from "uri-js";
import { fileURLToPath } from "url";
import { AnyZodObject } from "zod";
import { Core } from "../core.js";
import { IdeInfo, IdeSettings } from "../index.js";
import { getDevDataFilePath } from "../util/paths.js";
import { joinPathsToUri } from "../util/uri.js";
const DEFAULT_DEV_DATA_LEVEL: DataLogLevel = "all";
export const LOCAL_DEV_DATA_VERSION = "0.2.0";
export class DataLogger {
private static instance: DataLogger | null = null;
core?: Core;
ideSettingsPromise?: Promise<IdeSettings>;
ideInfoPromise?: Promise<IdeInfo>;
private constructor() {}
public static getInstance(): DataLogger {
if (DataLogger.instance === null) {
DataLogger.instance = new DataLogger();
}
return DataLogger.instance;
}
async addBaseValues(
body: Record<string, any>,
eventName: string,
schema: string,
zodSchema: AnyZodObject,
): Promise<Record<string, any>> {
const newBody = { ...body };
const ideSettings = await this.ideSettingsPromise;
const ideInfo = await this.ideInfoPromise;
if ("eventName" in zodSchema.shape) {
newBody.eventName = eventName;
}
if ("timestamp" in zodSchema.shape) {
newBody.timestamp = new Date().toISOString();
}
if ("schema" in zodSchema.shape) {
newBody.schema = schema;
}
if ("userAgent" in zodSchema.shape) {
newBody.userAgent = ideInfo
? `${ideInfo.name}/${ideInfo.version} (Continue/${ideInfo.extensionVersion})`
: "Unknown/Unknown (Continue/Unknown)";
}
if ("selectedProfileId" in zodSchema.shape) {
newBody.selectedProfileId =
this.core?.configHandler.currentProfile?.profileDescription.id ?? "";
}
if ("userId" in zodSchema.shape) {
newBody.userId = ideSettings?.userToken ?? "";
}
return newBody;
}
async logDevData(event: DevDataLogEvent) {
// Local logs (always on for all levels)
try {
const filepath: string = getDevDataFilePath(
event.name,
LOCAL_DEV_DATA_VERSION,
);
const localSchema =
devDataVersionedSchemas[LOCAL_DEV_DATA_VERSION]["all"][event.name];
if (!localSchema) {
throw new Error(
`Schema ${LOCAL_DEV_DATA_VERSION} doesn't exist at level "all"`,
);
}
const eventDataWithBaseValues = await this.addBaseValues(
event.data,
event.name,
LOCAL_DEV_DATA_VERSION,
localSchema,
);
const parsed = localSchema?.safeParse(eventDataWithBaseValues);
if (parsed?.success) {
fs.writeFileSync(filepath, `${JSON.stringify(parsed.data)}\n`, {
flag: "a",
});
}
} catch (error) {
console.error("Error logging local dev data:", error);
}
// Remote logs
const config = (await this.core?.configHandler.loadConfig())?.config;
if (config?.data?.length) {
await Promise.allSettled(
config.data.map(async (dataConfig) => {
try {
// First extract the data schema based on the version and level
const { schema } = dataConfig;
const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
// Skip event if `events` is specified and does not include the event
const events = dataConfig.events ?? allDevEventNames;
if (!events.includes(event.name)) {
return;
}
const versionSchemas = devDataVersionedSchemas[schema];
if (!versionSchemas) {
throw new Error(
`Attempting to log dev data to non-existent version ${schema}`,
);
}
const levelSchemas = versionSchemas[level];
if (!levelSchemas) {
throw new Error(
`Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
);
}
const zodSchema = levelSchemas[event.name];
if (!zodSchema) {
throw new Error(
`Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
);
}
const eventDataWithBaseValues = await this.addBaseValues(
event.data,
event.name,
schema,
zodSchema,
);
const parsed = zodSchema.safeParse(eventDataWithBaseValues);
if (!parsed.success) {
throw new Error(
`Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
);
}
const uriComponents = URI.parse(dataConfig.destination);
// Send to remote server
if (
uriComponents.scheme === "https" ||
uriComponents.scheme === "http"
) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (dataConfig.apiKey) {
headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
}
// For events going to Continue, overwrite the access token
if (
uriComponents.host?.endsWith(".continue.dev") ||
uriComponents.host === "continue.dev"
) {
//
const accessToken =
await this.core?.configHandler.controlPlaneClient.getAccessToken();
headers["Authorization"] = `Bearer ${accessToken}`;
}
const profileId =
this.core?.configHandler.currentProfile?.profileDescription
.id ?? "";
const response = await fetchwithRequestOptions(
dataConfig.destination,
{
method: "POST",
headers,
body: JSON.stringify({
name: event.name,
data: parsed.data,
schema,
level,
profileId,
}),
},
dataConfig.requestOptions,
);
if (!response.ok) {
throw new Error(
`Post request failed. ${response.status}: ${response.statusText}`,
);
}
} else if (uriComponents.scheme === "file") {
// Write to jsonc file for local file URIs
const dirUri = joinPathsToUri(dataConfig.destination, schema);
const dirPath = fileURLToPath(dirUri);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
const filepath = path.join(dirPath, `${event.name}.jsonl`);
const jsonLine = JSON.stringify(event.data);
fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
} else {
throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
}
} catch (error) {
console.error(
`Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
);
}
}),
);
}
}
}

View file

@ -18,7 +18,8 @@ export async function applyCodeBlock(
llm: ILLM,
fastLlm: ILLM,
): Promise<[boolean, AsyncGenerator<DiffLine>]> {
if (canUseInstantApply(filename)) {
// This was buggy, removed for now, maybe forever
if (false && canUseInstantApply(filename)) {
const diffLines = await deterministicApplyLazyEdit(
oldFile,
newFile,

View file

@ -54,7 +54,8 @@ export async function* streamDiffLines(
llm: ILLM,
input: string,
language: string | undefined,
onlyOneInsertion?: boolean,
onlyOneInsertion: boolean,
overridePrompt: ChatMessage[] | undefined,
): AsyncGenerator<DiffLine> {
void Telemetry.capture(
"inlineEdit",
@ -80,14 +81,9 @@ export async function* streamDiffLines(
// Trim end of oldLines, otherwise we have trailing \r on every line for CRLF files
oldLines = oldLines.map((line) => line.trimEnd());
const prompt = constructPrompt(
prefix,
highlighted,
suffix,
llm,
input,
language,
);
const prompt =
overridePrompt ??
constructPrompt(prefix, highlighted, suffix, llm, input, language);
const inept = modelIsInept(llm.model);
const prediction: Prediction = {

82
core/index.d.ts vendored
View file

@ -1,6 +1,6 @@
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
interface Window {
ide?: "vscode";
@ -60,7 +60,7 @@ export interface IndexingStatus {
progress: number;
description: string;
status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending";
embeddingsProviderId: string;
embeddingsProviderId?: string;
isReindexing?: boolean;
debugInfo?: string;
title: string;
@ -94,6 +94,8 @@ export interface ILLM extends LLMOptions {
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
deployment?: string;
apiVersion?: string;
@ -177,8 +179,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
export interface ContextProviderExtras {
config: ContinueConfig;
fullInput: string;
embeddingsProvider: ILLM;
reranker: ILLM | undefined;
embeddingsProvider: ILLM | null;
reranker: ILLM | null;
llm: ILLM;
ide: IDE;
selectedCode: RangeInFile[];
@ -476,10 +478,18 @@ export interface LLMOptions {
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
aiGatewaySlug?: string;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
aiGatewaySlug?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
useLegacyCompletionsEndpoint?: boolean;
@ -500,17 +510,16 @@ export interface LLMOptions {
profile?: string;
modelArn?: string;
// AWS and GCP Options
// AWS and VertexAI Options
region?: string;
// GCP Options
capabilities?: ModelCapability;
// GCP and Watsonx Options
// VertexAI and Watsonx Options
projectId?: string;
// IBM watsonx Options
deploymentId?: string;
env?: Record<string, string | number | boolean>;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
@ -599,7 +608,7 @@ export interface IdeSettings {
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
continueTestEnvironment: "none" | "production" | "test" | "local";
continueTestEnvironment: "none" | "production" | "staging" | "local";
pauseCodebaseIndexOnStart: boolean;
}
@ -672,6 +681,10 @@ export interface IDE {
}
>;
getLastFileSaveTimestamp?(): number;
updateLastFileSaveTimestamp?(): void;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
@ -725,6 +738,7 @@ export interface ContinueSDK {
selectedCode: RangeInFile[];
config: ContinueConfig;
fetch: FetchFunction;
completionOptions?: LLMFullCompletionOptions;
}
export interface SlashCommand {
@ -859,6 +873,7 @@ export interface ToolExtras {
ide: IDE;
llm: ILLM;
fetch: FetchFunction;
tool: Tool;
}
export interface Tool {
@ -874,6 +889,7 @@ export interface Tool {
wouldLikeTo: string;
readonly: boolean;
uri?: string;
faviconUrl?: string;
}
interface ToolChoice {
@ -905,6 +921,7 @@ export interface BaseCompletionOptions {
export interface ModelCapability {
uploadImage?: boolean;
tools?: boolean;
}
export interface ModelDescription {
@ -912,8 +929,14 @@ export interface ModelDescription {
provider: string;
model: string;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
contextLength?: number;
maxStopWords?: number;
template?: TemplateType;
@ -921,8 +944,9 @@ export interface ModelDescription {
systemMessage?: string;
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
}
export interface EmbedOptions {
@ -933,15 +957,16 @@ export interface EmbedOptions {
apiType?: string;
apiVersion?: string;
requestOptions?: RequestOptions;
maxChunkSize?: number;
maxBatchSize?: number;
maxEmbeddingChunkSize?: number;
maxEmbeddingBatchSize?: number;
// AWS options
profile?: string;
// AWS and GCP Options
// AWS and VertexAI Options
region?: string;
// GCP and Watsonx Options
// VertexAI and Watsonx Options
projectId?: string;
}
@ -971,6 +996,11 @@ export interface TabAutocompleteOptions {
disableInFiles?: string[];
useImports?: boolean;
showWhateverWeHaveAtXMs?: number;
// true = enabled, false = disabled, number = enabled with priority
experimental_includeClipboard: boolean | number;
experimental_includeRecentlyVisitedRanges: boolean | number;
experimental_includeRecentlyEditedRanges: boolean | number;
experimental_includeDiff: boolean | number;
}
export interface StdioOptions {
@ -994,6 +1024,7 @@ export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
export interface MCPOptions {
transport: TransportOptions;
faviconUrl?: string;
}
export interface ContinueUIConfig {
@ -1002,6 +1033,7 @@ export interface ContinueUIConfig {
displayRawMarkdown?: boolean;
showChatScrollbar?: boolean;
codeWrap?: boolean;
showSessionTabs?: boolean;
}
export interface ContextMenuConfig {
@ -1012,10 +1044,10 @@ export interface ContextMenuConfig {
fixGrammar?: string;
}
export interface ModelRoles {
export interface ExperimentalModelRoles {
repoMapFileSelection?: string;
inlineEdit?: string;
applyCodeBlock?: string;
repoMapFileSelection?: string;
}
export type EditStatus =
@ -1080,7 +1112,7 @@ export type DefaultContextProvider = ContextProviderWithParams & {
export interface ExperimentalConfig {
contextMenuPrompts?: ContextMenuConfig;
modelRoles?: ModelRoles;
modelRoles?: ExperimentalModelRoles;
defaultContext?: DefaultContextProvider[];
promptPath?: string;
@ -1132,6 +1164,7 @@ export interface SerializedContinueConfig {
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
data?: DataDestination[];
}
export type ConfigMergeType = "merge" | "overwrite";
@ -1184,6 +1217,7 @@ export interface Config {
experimental?: ExperimentalConfig;
/** Analytics configuration */
analytics?: AnalyticsConfig;
data?: DataDestination[];
}
// in the actual Continue source code
@ -1198,15 +1232,15 @@ export interface ContinueConfig {
disableSessionTitles?: boolean;
disableIndexing?: boolean;
userToken?: string;
embeddingsProvider: ILLM;
tabAutocompleteModels?: ILLM[];
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
ui?: ContinueUIConfig;
reranker?: ILLM;
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
modelsByRole: Record<ModelRole, ILLM[]>;
selectedModelByRole: Record<ModelRole, ILLM | null>;
data?: DataDestination[];
}
export interface BrowserSerializedContinueConfig {
@ -1220,15 +1254,15 @@ export interface BrowserSerializedContinueConfig {
disableIndexing?: boolean;
disableSessionTitles?: boolean;
userToken?: string;
embeddingsProvider?: string;
ui?: ContinueUIConfig;
reranker?: RerankerDescription;
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
modelsByRole: Record<ModelRole, ModelDescription[]>;
selectedModelByRole: Record<ModelRole, ModelDescription | null>;
}
// DOCS SUGGESTIONS AND PACKAGE INFO

View file

@ -28,7 +28,12 @@ import type {
IndexTag,
IndexingProgressUpdate,
} from "../";
import { getLastNPathParts, getUriPathBasename } from "../util/uri";
import {
findUriInDirs,
getLastNPathParts,
getLastNUriRelativePathParts,
getUriPathBasename,
} from "../util/uri";
type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
@ -347,14 +352,19 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
}
}
static async getForId(id: number): Promise<ContextItem> {
static async getForId(
id: number,
workspaceDirs: string[],
): Promise<ContextItem> {
const db = await SqliteDb.get();
const row = await db.get("SELECT * FROM code_snippets WHERE id = ?", [id]);
const last2Parts = getLastNUriRelativePathParts(workspaceDirs, row.path, 2);
const { relativePathOrBasename } = findUriInDirs(row.path, workspaceDirs);
return {
name: row.title,
description: getLastNPathParts(row.path, 2),
content: `\`\`\`${getUriPathBasename(row.path)}\n${row.content}\n\`\`\``,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${row.content}\n\`\`\``,
uri: {
type: "file",
value: row.path,

View file

@ -5,8 +5,8 @@ import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
@ -15,6 +15,7 @@ import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import {
CodebaseIndex,
IndexResultType,
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
import { walkDirAsync } from "./walkDir.js";
@ -80,24 +81,66 @@ export class CodebaseIndexer {
return [];
}
const indexes = [
const embeddingsModel = config.selectedModelByRole.embed;
if (!embeddingsModel) {
return [];
}
const indexes: CodebaseIndex[] = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
this.continueServerClient,
config.embeddingsProvider.maxEmbeddingChunkSize,
embeddingsModel.maxEmbeddingChunkSize,
), // Chunking must come first
new LanceDbIndex(
config.embeddingsProvider,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
),
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
];
const lanceDbIndex = await LanceDbIndex.create(
embeddingsModel,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
);
if (lanceDbIndex) {
indexes.push(lanceDbIndex);
}
indexes.push(
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
);
return indexes;
}
private totalIndexOps(results: RefreshIndexResults): number {
return (
results.compute.length +
results.del.length +
results.addTag.length +
results.removeTag.length
);
}
private singleFileIndexOps(
results: RefreshIndexResults,
lastUpdated: PathAndCacheKey[],
filePath: string,
): [RefreshIndexResults, PathAndCacheKey[]] {
const filterFn = (item: PathAndCacheKey) => item.path === filePath;
const compute = results.compute.filter(filterFn);
const del = results.del.filter(filterFn);
const addTag = results.addTag.filter(filterFn);
const removeTag = results.removeTag.filter(filterFn);
const newResults = {
compute,
del,
addTag,
removeTag,
};
const newLastUpdated = lastUpdated.filter(filterFn);
return [newResults, newLastUpdated];
}
public async refreshFile(
file: string,
workspaceDirs: string[],
@ -115,26 +158,28 @@ export class CodebaseIndexer {
const repoName = await this.ide.getRepoName(foundInDir);
const indexesToBuild = await this.getIndexesToBuild();
const stats = await this.ide.getFileStats([file]);
const filePath = Object.keys(stats)[0];
for (const index of indexesToBuild) {
const tag = {
directory: foundInDir,
branch,
artifactId: index.artifactId,
};
const [results, lastUpdated, markComplete] =
const [fullResults, fullLastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
// since this is only a single file update / save we do not want to actualy remove anything, we just want to recompute for our single file
results.removeTag = [];
results.addTag = [];
results.del = [];
const [results, lastUpdated] = this.singleFileIndexOps(
fullResults,
fullLastUpdated,
filePath,
);
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
if (results.compute.length === 0) {
if (this.totalIndexOps(results) + lastUpdated.length === 0) {
continue;
}
@ -415,11 +460,7 @@ export class CodebaseIndexer {
(filepath) => this.ide.readFile(filepath),
repoName,
);
const totalOps =
results.compute.length +
results.del.length +
results.addTag.length +
results.removeTag.length;
const totalOps = this.totalIndexOps(results);
let completedOps = 0;
// Don't update if nothing to update. Some of the indices might do unnecessary setup work

View file

@ -97,13 +97,15 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
await db.run(`
DELETE FROM fts WHERE rowid IN (
SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ?
)
`,[item.path, item.cacheKey]);
await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
item.path,
item.cacheKey,
]);
await db.run("DELETE FROM fts WHERE path = ?", [item.path]);
await markComplete([item], IndexResultType.Delete);
}
}

View file

@ -3,15 +3,15 @@ import lance from "vectordb";
import { testConfigHandler, testIde } from "../test/fixtures";
import { getLanceDbPath } from "../util/paths";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import {
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "./test/indexing";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
jest.useFakeTimers();
@ -30,12 +30,15 @@ describe.skip("ChunkCodebaseIndex", () => {
if (!mockConfig) {
throw new Error("Failed to load config");
}
if (!mockConfig.selectedModelByRole.embed) {
throw new Error("No embeddings model selected");
}
index = new LanceDbIndex(
mockConfig.embeddingsProvider,
index = (await LanceDbIndex.create(
mockConfig.selectedModelByRole.embed,
testIde.readFile.bind(testIde),
testContinueServerClient,
);
))!;
sqliteDb = await SqliteDb.get();
lanceDb = await lance.connect(getLanceDbPath());

View file

@ -1,30 +1,30 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { RunResult } from "sqlite3";
import { v4 as uuidv4 } from "uuid";
import lance, { Table } from "vectordb";
import { IContinueServerClient } from "../continueServer/interface.js";
import { isSupportedLanceDbCpuTargetForLinux } from "../config/util";
import { IContinueServerClient } from "../continueServer/interface";
import {
BranchAndDir,
Chunk,
ILLM,
IndexTag,
IndexingProgressUpdate,
} from "../index.js";
import { getLanceDbPath, migrate } from "../util/paths.js";
} from "../index";
import { getLanceDbPath, migrate } from "../util/paths";
import { getUriPathBasename } from "../util/uri";
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import { chunkDocument, shouldChunk } from "./chunk/chunk";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
CodebaseIndex,
IndexResultType,
MarkCompleteCallback,
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
import { getUriPathBasename } from "../util/uri.js";
} from "./types";
import type * as LanceType from "vectordb";
// LanceDB converts to lowercase, so names must all be lowercase
interface LanceDbRow {
uuid: string;
path: string;
@ -38,16 +38,53 @@ type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] };
type ChunkMap = Map<string, ItemWithChunks>;
export class LanceDbIndex implements CodebaseIndex {
private static lance: typeof LanceType | null = null;
relativeExpectedTime: number = 13;
get artifactId(): string {
return `vectordb::${this.embeddingsProvider.embeddingId}`;
return `vectordb::${this.embeddingsProvider?.embeddingId}`;
}
constructor(
/**
* Factory method for creating LanceDbIndex instances.
*
* We dynamically import LanceDB only when supported to avoid native module loading errors
* on incompatible platforms. LanceDB has CPU-specific native dependencies that can crash
* the application if loaded on unsupported architectures.
*
* See isSupportedLanceDbCpuTargetForLinux() for platform compatibility details.
*/
static async create(
embeddingsProvider: ILLM,
readFile: (filepath: string) => Promise<string>,
continueServerClient?: IContinueServerClient,
): Promise<LanceDbIndex | null> {
if (!isSupportedLanceDbCpuTargetForLinux()) {
return null;
}
try {
this.lance = await import("vectordb");
return new LanceDbIndex(
embeddingsProvider,
readFile,
continueServerClient,
);
} catch (err) {
console.error("Failed to load LanceDB:", err);
return null;
}
}
private constructor(
private readonly embeddingsProvider: ILLM,
private readonly readFile: (filepath: string) => Promise<string>,
private readonly continueServerClient?: IContinueServerClient,
) {}
) {
if (!LanceDbIndex.lance) {
throw new Error("LanceDB not initialized");
}
}
tableNameForTag(tag: IndexTag) {
return tagToString(tag).replace(/[^\w-_.]/g, "");
@ -97,12 +134,10 @@ export class LanceDbIndex implements CodebaseIndex {
);
const embeddings = await this.getEmbeddings(allChunks);
// Remove undefined embeddings and their corresponding chunks
for (let i = embeddings.length - 1; i >= 0; i--) {
if (embeddings[i] === undefined) {
const chunk = allChunks[i];
const chunks = chunkMap.get(chunk.filepath)?.chunks;
if (chunks) {
const index = chunks.findIndex((c) => c === chunk);
if (index !== -1) {
@ -142,6 +177,9 @@ export class LanceDbIndex implements CodebaseIndex {
item: PathAndCacheKey,
content: string,
): Promise<Chunk[]> {
if (!this.embeddingsProvider) {
return [];
}
const chunks: Chunk[] = [];
const chunkParams = {
@ -163,6 +201,9 @@ export class LanceDbIndex implements CodebaseIndex {
}
private async getEmbeddings(chunks: Chunk[]): Promise<number[][]> {
if (!this.embeddingsProvider) {
return [];
}
try {
return await this.embeddingsProvider.embed(chunks.map((c) => c.content));
} catch (err) {
@ -204,6 +245,7 @@ export class LanceDbIndex implements CodebaseIndex {
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const lance = LanceDbIndex.lance!;
const sqliteDb = await SqliteDb.get();
await this.createSqliteCacheTable(sqliteDb);
@ -211,15 +253,13 @@ export class LanceDbIndex implements CodebaseIndex {
const lanceDb = await lance.connect(getLanceDbPath());
const existingLanceTables = await lanceDb.tableNames();
let lanceTable: Table<number[]> | undefined = undefined;
let lanceTable: LanceType.Table<number[]> | undefined = undefined;
let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName);
// Compute
const addComputedLanceDbRows = async (
pathAndCacheKeys: PathAndCacheKey[],
computedRows: LanceDbRow[],
) => {
// Create table if needed, add computed rows
if (lanceTable) {
if (computedRows.length > 0) {
await lanceTable.add(computedRows);
@ -235,11 +275,9 @@ export class LanceDbIndex implements CodebaseIndex {
needToCreateLanceTable = false;
}
// Mark item complete
await markComplete(pathAndCacheKeys, IndexResultType.Compute);
};
// Check remote cache
if (this.continueServerClient?.connected) {
try {
const keys = results.compute.map(({ cacheKey }) => cacheKey);
@ -249,7 +287,6 @@ export class LanceDbIndex implements CodebaseIndex {
repoName,
);
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
// Get path for cacheKey
const path = results.compute.find(
(item) => item.cacheKey === cacheKey,
)?.path;
@ -261,7 +298,6 @@ export class LanceDbIndex implements CodebaseIndex {
continue;
}
// Build LanceDbRow objects
const rows: LanceDbRow[] = [];
for (const chunk of chunks) {
const row = {
@ -288,7 +324,6 @@ export class LanceDbIndex implements CodebaseIndex {
await addComputedLanceDbRows([{ cacheKey, path }], rows);
}
// Remove items that don't need to be recomputed
results.compute = results.compute.filter(
(item) => !resp.files[item.cacheKey],
);
@ -310,12 +345,10 @@ export class LanceDbIndex implements CodebaseIndex {
await addComputedLanceDbRows(results.compute, dbRows);
let accumulatedProgress = 0;
// Add tag - retrieve the computed info from lance sqlite cache
for (const { path, cacheKey } of results.addTag) {
const stmt = await sqliteDb.prepare(
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND artifact_id = ?",
cacheKey,
path,
this.artifactId,
);
const cachedItems = await stmt.all();
@ -354,7 +387,6 @@ export class LanceDbIndex implements CodebaseIndex {
};
}
// Delete or remove tag - remove from lance table)
if (!needToCreateLanceTable) {
const toDel = [...results.removeTag, ...results.del];
@ -363,7 +395,6 @@ export class LanceDbIndex implements CodebaseIndex {
}
for (const { path, cacheKey } of toDel) {
// This is where the aforementioned lowercase conversion problem shows
await lanceTable.delete(
`cachekey = '${cacheKey}' AND path = '${path}'`,
);
@ -379,7 +410,6 @@ export class LanceDbIndex implements CodebaseIndex {
await markComplete(results.removeTag, IndexResultType.RemoveTag);
// Delete - also remove from sqlite cache
for (const { path, cacheKey } of results.del) {
await sqliteDb.run(
"DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
@ -409,7 +439,7 @@ export class LanceDbIndex implements CodebaseIndex {
n: number,
directory: string | undefined,
vector: number[],
db: any, /// lancedb.Connection
db: any,
): Promise<LanceDbRow[]> {
const tableName = this.tableNameForTag(tag);
const tableNames = await db.tableNames();
@ -421,7 +451,6 @@ export class LanceDbIndex implements CodebaseIndex {
const table = await db.openTable(tableName);
let query = table.search(vector);
if (directory) {
// seems like lancedb is only post-filtering, so have to return a bunch of results and slice after
query = query.where(`path LIKE '${directory}%'`).limit(300);
} else {
query = query.limit(n);
@ -436,6 +465,10 @@ export class LanceDbIndex implements CodebaseIndex {
tags: BranchAndDir[],
filterDirectory: string | undefined,
): Promise<Chunk[]> {
const lance = LanceDbIndex.lance!;
if (!this.embeddingsProvider) {
return [];
}
const [vector] = await this.embeddingsProvider.embed([query]);
const db = await lance.connect(getLanceDbPath());

View file

@ -8,6 +8,7 @@ import Gemini from "../llm/llms/Gemini.js";
import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js";
import LMStudio from "../llm/llms/LMStudio.js";
import Mistral from "../llm/llms/Mistral.js";
import NCompass from "../llm/llms/NCompass.js";
import Nebius from "../llm/llms/Nebius.js";
import Nvidia from "../llm/llms/Nvidia.js";
import Ollama from "../llm/llms/Ollama.js";
@ -39,6 +40,7 @@ export const allEmbeddingsProviders: Record<
gemini: Gemini,
"continue-proxy": ContinueProxy,
deepinfra: DeepInfra,
ncompass: NCompass,
nvidia: Nvidia,
voyage: Voyage,
mistral: Mistral,

View file

@ -80,9 +80,9 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
`
INSERT INTO chunk_tags (chunkId, tag)
SELECT id, ? FROM chunks
WHERE cacheKey = ? AND path = ?
WHERE cacheKey = ?
`,
[tagString, item.cacheKey, item.path],
[tagString, item.cacheKey],
);
await markComplete([item], IndexResultType.AddTag);
accumulatedProgress += 1 / results.addTag.length / 4;
@ -158,7 +158,8 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
chunkId INTEGER NOT NULL,
FOREIGN KEY (chunkId) REFERENCES chunks (id)
FOREIGN KEY (chunkId) REFERENCES chunks (id),
UNIQUE (tag, chunkId)
)`);
}

View file

@ -2,7 +2,6 @@
* @jest-environment jsdom
*/
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { SiteIndexingConfig } from "../../index.js";
import FileSystemIde from "../../util/filesystem.js";
import { editConfigJson } from "../../util/paths.js";
@ -50,16 +49,7 @@ describe.skip("DocsService Integration Tests", () => {
ide,
ideSettingsPromise,
async () => {},
new ControlPlaneClient(
Promise.resolve({
accessToken: "",
account: {
id: "",
label: "",
},
}),
ideSettingsPromise,
),
Promise.resolve(undefined),
);
docsService = DocsService.createSingleton(configHandler, ide);

View file

@ -1,6 +1,6 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
import {
Chunk,
@ -13,12 +13,16 @@ import {
SiteIndexingConfig,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { addContextProvider } from "../../config/util";
import {
addContextProvider,
isSupportedLanceDbCpuTargetForLinux,
} from "../../config/util";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { IMessenger } from "../../protocol/messenger";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import { GlobalContext } from "../../util/GlobalContext";
import {
editConfigJson,
getDocsSqlitePath,
@ -40,7 +44,8 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import { ConfigResult } from "@continuedev/config-yaml";
import type * as LanceType from "vectordb";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -80,6 +85,7 @@ export type AddParams = {
- add/index one
*/
export default class DocsService {
private static lance: typeof LanceType | null = null;
static lanceTableName = "docs";
static sqlitebTableName = "docs";
@ -111,6 +117,22 @@ export default class DocsService {
this.githubToken = token;
}
private async initLanceDb() {
if (!isSupportedLanceDbCpuTargetForLinux()) {
return null;
}
try {
if (!DocsService.lance) {
DocsService.lance = await import("vectordb");
}
return DocsService.lance;
} catch (err) {
console.error("Failed to load LanceDB:", err);
return null;
}
}
// Singleton pattern: only one service globally
private static instance?: DocsService;
static createSingleton(
@ -156,19 +178,26 @@ export default class DocsService {
const currentStatus = this.statuses.get(doc.startUrl);
if (currentStatus) {
return currentStatus;
this.handleStatusUpdate(currentStatus);
return;
}
const sharedStatus = {
type: "docs" as IndexingStatus["type"],
const sharedStatus: Omit<
IndexingStatus,
"progress" | "description" | "status"
> = {
type: "docs",
id: doc.startUrl,
embeddingsProviderId: this.config.embeddingsProvider.embeddingId,
isReindexing: false,
title: doc.title,
debugInfo: `max depth: ${doc.maxDepth}`,
icon: doc.faviconUrl,
url: doc.startUrl,
};
if (this.config.selectedModelByRole.embed) {
sharedStatus.embeddingsProviderId =
this.config.selectedModelByRole.embed.embeddingId;
}
const indexedStatus: IndexingStatus = metadata.find(
(meta) => meta.startUrl === doc.startUrl,
)
@ -210,13 +239,11 @@ export default class DocsService {
if (isAborted) {
return true;
}
// Handle indexing disabled change mid-indexing
if (this.config.disableIndexing) {
this.abort(startUrl);
return true;
}
// Handle embeddings provider change mid-indexing
if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) {
if (
this.config.selectedModelByRole.embed?.embeddingId !== startedWithEmbedder
) {
this.abort(startUrl);
return true;
}
@ -236,14 +263,6 @@ export default class DocsService {
return true;
}
async isUsingUnsupportedPreIndexedEmbeddingsProvider() {
const isPreIndexedDocsProvider =
this.config.embeddingsProvider.embeddingId ===
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId;
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
return isPreIndexedDocsProvider && !canUsePreindexedDocs;
}
// Determines if using preIndexed and returns proper embeddings provider
async getEmbeddingsProvider(startUrl: string) {
// Conditions for using a pre-indexed doc
@ -264,7 +283,7 @@ export default class DocsService {
}
}
return {
provider: this.config.embeddingsProvider,
provider: this.config.selectedModelByRole.embed,
isPreindexed: false,
};
}
@ -276,10 +295,6 @@ export default class DocsService {
const oldConfig = this.config;
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
if (this.config.disableIndexing) {
return;
}
// No point in indexing if no docs context provider
const hasDocsContextProvider = this.hasDocsContextProvider();
if (!hasDocsContextProvider) {
@ -288,9 +303,7 @@ export default class DocsService {
// Skip docs indexing if not supported
// No warning message here because would show on ANY config update
const unsupported =
await this.isUsingUnsupportedPreIndexedEmbeddingsProvider();
if (unsupported) {
if (!this.config.selectedModelByRole.embed) {
return;
}
@ -329,18 +342,21 @@ export default class DocsService {
// Returns true if startUrl has been indexed with current embeddingsProvider
async hasMetadata(startUrl: string): Promise<boolean> {
if (!this.config.selectedModelByRole.embed) {
return false;
}
const db = await this.getOrCreateSqliteDb();
const title = await db.get(
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
return !!title;
}
async listMetadata() {
const embeddingsProvider = this.config.embeddingsProvider;
const embeddingsProvider = this.config.selectedModelByRole.embed;
if (!embeddingsProvider) {
return [];
}
@ -365,13 +381,16 @@ export default class DocsService {
async indexAndAdd(
siteIndexingConfig: SiteIndexingConfig,
reIndex: boolean = false,
forceReindex: boolean = false,
): Promise<void> {
if (this.config.disableIndexing) {
console.warn("Attempting to add/index docs when indexing is disabled");
const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
// First, if indexing is already in process, don't attempt
// This queue is necessary because indexAndAdd is invoked circularly by config edits
// TODO shouldn't really be a gap between adding and checking in queue but probably fine
if (this.docsIndexingQueue.has(startUrl)) {
return;
}
const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
@ -379,13 +398,15 @@ export default class DocsService {
console.warn("Attempted to indexAndAdd pre-indexed doc");
return;
}
// Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs
if (this.docsIndexingQueue.has(startUrl)) {
if (!provider) {
console.warn("@docs indexAndAdd: no embeddings provider found");
return;
}
const startedWithEmbedder = provider.embeddingId;
// Check if doc has been successfully indexed with the given embedder
// Note at this point we know it's not a pre-indexed doc
const indexExists = await this.hasMetadata(startUrl);
// Build status update - most of it is fixed values
@ -396,32 +417,82 @@ export default class DocsService {
type: "docs",
id: siteIndexingConfig.startUrl,
embeddingsProviderId: provider.embeddingId,
isReindexing: reIndex && indexExists,
isReindexing: forceReindex && indexExists,
title: siteIndexingConfig.title,
debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
icon: siteIndexingConfig.faviconUrl,
url: siteIndexingConfig.startUrl,
};
// Clear current indexes if reIndexing
if (indexExists) {
if (reIndex) {
await this.deleteIndexes(startUrl);
} else {
// If not force-reindexing and has failed with same config, don't reattempt
if (!forceReindex) {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const hasFailed = failedDocs.find((d) =>
this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
if (hasFailed) {
console.log(
`Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`,
);
this.handleStatusUpdate({
...fixedStatus,
description: "Failed",
status: "failed",
progress: 1,
description: "Complete",
status: "complete",
debugInfo: "Already indexed",
});
return;
}
}
if (indexExists && !forceReindex) {
this.handleStatusUpdate({
...fixedStatus,
progress: 1,
description: "Complete",
status: "complete",
debugInfo: "Already indexed",
});
return;
}
// Do a test run on the embedder
// This particular failure will not mark as a failed config in global context
// Since SiteIndexingConfig is likely to be valid
try {
await provider.embed(["continue-test-run"]);
} catch (e) {
console.error("Failed to test embeddings connection", e);
return;
}
const markFailedInGlobalContext = () => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
newFailedDocs.push(siteIndexingConfig);
globalContext.update("failedDocs", newFailedDocs);
};
const removeFromFailedGlobalContext = () => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
globalContext.update("failedDocs", newFailedDocs);
};
try {
this.docsIndexingQueue.add(startUrl);
// Clear current indexes if reIndexing
if (indexExists && forceReindex) {
await this.deleteIndexes(startUrl);
}
this.addToConfig(siteIndexingConfig);
this.handleStatusUpdate({
@ -523,9 +594,10 @@ export default class DocsService {
});
try {
const subpathEmbeddings = await provider.embed(
article.chunks.map((c) => c.content),
);
const subpathEmbeddings =
article.chunks.length > 0
? await provider.embed(article.chunks.map((c) => c.content))
: [];
chunks.push(...article.chunks);
embeddings.push(...subpathEmbeddings);
const toWait = 100 * this.docsIndexingQueue.size + 50;
@ -551,7 +623,7 @@ export default class DocsService {
});
void this.ide.showToast("info", `Failed to index ${startUrl}`);
this.docsIndexingQueue.delete(startUrl);
markFailedInGlobalContext();
return;
}
@ -569,7 +641,7 @@ export default class DocsService {
});
// Delete indexed docs if re-indexing
if (reIndex && indexExists) {
if (forceReindex && indexExists) {
console.log("Deleting old embeddings");
await this.deleteIndexes(startUrl);
}
@ -593,11 +665,6 @@ export default class DocsService {
favicon,
});
this.docsIndexingQueue.delete(startUrl);
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
...fixedStatus,
description: "Complete",
@ -610,23 +677,29 @@ export default class DocsService {
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
removeFromFailedGlobalContext();
} catch (e) {
let description = `Error getting docs from: ${siteIndexingConfig.startUrl}`;
console.error(
`Error indexing docs at: ${siteIndexingConfig.startUrl}`,
e,
);
let description = `Error indexing docs at: ${siteIndexingConfig.startUrl}`;
if (e instanceof Error) {
if (
e.message.includes("github.com") &&
e.message.includes("rate limit")
) {
description = "Github rate limit exceeded";
description = "Github rate limit exceeded"; // This text is used verbatim elsewhere
}
}
console.error("Error indexing docs", e);
this.handleStatusUpdate({
...fixedStatus,
description,
status: "failed",
progress: 1,
});
markFailedInGlobalContext();
} finally {
this.docsIndexingQueue.delete(startUrl);
}
@ -670,21 +743,18 @@ export default class DocsService {
startUrl: string,
nRetrieve: number,
) {
if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) {
await this.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.embeddingId} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE"
"Please select a different embeddings provider to use the '@docs' " +
"context provider.",
);
return [];
}
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
if (!provider) {
void this.ide.showToast(
"error",
"Set up an embeddings model to use the @docs context provider. See: " +
"https://docs.continue.dev/customize/model-roles/embeddings",
);
return [];
}
if (isPreindexed) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDocs[startUrl]!["title"],
@ -715,8 +785,10 @@ export default class DocsService {
try {
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
if (!provider) {
throw new Error("No embeddings model set");
}
const result = await db.get(
`SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
@ -747,7 +819,7 @@ export default class DocsService {
config: siteIndexingConfig,
indexingStatus: this.statuses.get(startUrl),
chunks: rows.map(this.lanceDBRowToChunk),
isPreIndexedDoc,
isPreIndexedDoc: isPreindexed,
};
} catch (e) {
console.warn("Error getting details", e);
@ -821,7 +893,7 @@ export default class DocsService {
}
async getFavicon(startUrl: string) {
if (!this.config.embeddingsProvider) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
"Attempting to get favicon without embeddings provider specified",
);
@ -831,7 +903,7 @@ export default class DocsService {
const result = await db.get(
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
if (!result) {
@ -871,7 +943,7 @@ export default class DocsService {
// Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
// TODO if only favicon and title change, only update, don't embed
// Otherwise anything found in new config that isn't in sqlite should be added/indexed
const newDocs: SiteIndexingConfig[] = [];
const addedDocs: SiteIndexingConfig[] = [];
const changedDocs: SiteIndexingConfig[] = [];
for (const doc of newConfigDocs) {
const currentIndexedDoc = currentStartUrls.includes(doc.startUrl);
@ -895,7 +967,7 @@ export default class DocsService {
type: "docs",
id: doc.startUrl,
embeddingsProviderId:
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed?.embeddingId,
isReindexing: false,
title: doc.title,
debugInfo: "Config sync: not changed",
@ -908,22 +980,16 @@ export default class DocsService {
}
}
} else {
const currentStatus = this.statuses.get(doc.startUrl);
if (currentStatus?.status !== "failed") {
newDocs.push(doc);
}
addedDocs.push(doc);
void Telemetry.capture("add_docs_config", { url: doc.startUrl });
}
}
await Promise.allSettled([
...changedDocs.map((doc) => this.indexAndAdd(doc, true)),
...newDocs.map((doc) => this.indexAndAdd(doc)),
...addedDocs.map((doc) => this.indexAndAdd(doc)),
]);
for (const doc of newDocs) {
void Telemetry.capture("add_docs_config", { url: doc.startUrl });
}
for (const doc of deletedDocs) {
await this.deleteIndexes(doc.startUrl);
}
@ -943,7 +1009,7 @@ export default class DocsService {
// Lance DB Initialization
private async createLanceDocsTable(
connection: Connection,
connection: LanceType.Connection,
initializationVector: number[],
tableName: string,
) {
@ -990,9 +1056,21 @@ export default class DocsService {
initializationVector: number[];
startUrl: string;
}) {
const conn = await lancedb.connect(getLanceDbPath());
const lance = await this.initLanceDb();
if (!lance) {
throw new Error("LanceDB not available on this platform");
}
const conn = await lance.connect(getLanceDbPath());
const tableNames = await conn.tableNames();
const { provider } = await this.getEmbeddingsProvider(startUrl);
if (!provider) {
throw new Error(
"Could not retrieve @docs Lance Table: no embeddings provider specified",
);
}
const tableNameFromEmbeddingsProvider =
await this.getLanceTableName(provider);
@ -1049,13 +1127,19 @@ export default class DocsService {
siteIndexingConfig: { title, startUrl },
favicon,
}: AddParams) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
`Attempting to add metadata for ${startUrl} without embeddings provider specified`,
);
return;
}
const db = await this.getOrCreateSqliteDb();
await db.run(
`INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`,
title,
startUrl,
favicon,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
}
@ -1099,15 +1183,20 @@ export default class DocsService {
// Delete methods
private async deleteEmbeddingsFromLance(startUrl: string) {
const lance = await this.initLanceDb();
if (!lance) {
return;
}
for (const tableName of this.lanceTableNamesSet) {
const conn = await lancedb.connect(getLanceDbPath());
const conn = await lance.connect(getLanceDbPath());
const table = await conn.openTable(tableName);
await table.delete(`starturl = '${startUrl}'`);
}
}
private async deleteMetadataFromSqlite(startUrl: string) {
if (!this.config.embeddingsProvider) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
`Attempting to delete metadata for ${startUrl} without embeddings provider specified`,
);
@ -1118,7 +1207,7 @@ export default class DocsService {
await db.run(
`DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
}

View file

@ -139,24 +139,35 @@ export async function htmlPageToArticleWithChunks(
return undefined;
}
const title = readability.title || subpath;
const titles = Array.from(dom.window.document.querySelectorAll("h2"));
const article_components = titles.map((titleElement) => {
const title = titleElement.textContent || "";
let body = "";
let nextSibling = titleElement.nextElementSibling;
while (nextSibling && nextSibling.tagName !== "H2") {
body += nextSibling.textContent || "";
nextSibling = nextSibling.nextElementSibling;
}
const article_components =
titles.length > 0
? titles.map((titleElement) => {
const title = titleElement.textContent || "";
let body = "";
let nextSibling = titleElement.nextElementSibling;
return { title, body };
});
while (nextSibling && nextSibling.tagName !== "H2") {
body += nextSibling.textContent || "";
nextSibling = nextSibling.nextElementSibling;
}
return { title, body };
})
: [
{
title: title,
body: readability.textContent,
},
];
const article = {
url,
subpath,
title: readability.title,
title: title,
article_components,
};
return {

View file

@ -1,5 +1,5 @@
import { type Database } from "sqlite";
import { Table } from "vectordb";
import { type Table } from "vectordb";
import { editConfigJson, migrate } from "../../util/paths.js";

View file

@ -353,6 +353,16 @@ const preIndexedDocs: Record<
startUrl: "https://docs.asksage.ai/",
rootUrl: "https://docs.asksage.ai/",
},
"https://angular.dev/": {
title: "Angular",
startUrl: "https://angular.dev/",
rootUrl: "https://angular.dev/",
},
"https://docs.djangoproject.com/": {
title: "Django",
startUrl: "https://docs.djangoproject.com/",
rootUrl: "https://docs.djangoproject.com/",
}
};
export default preIndexedDocs;

View file

@ -157,32 +157,64 @@ async function getAddRemoveForTag(
const remove: PathAndCacheKey[] = [];
const updateLastUpdated: PathAndCacheKey[] = [];
for (const item of saved) {
const { lastUpdated, ...pathAndCacheKey } = item;
// First, group items by path and find latest timestamp for each
const pathGroups = new Map<string, {
latest: { lastUpdated: number, cacheKey: string },
allVersions: Array<{ cacheKey: string }>
}>();
if (files[item.path] === undefined) {
// Was indexed, but no longer exists. Remove
remove.push(pathAndCacheKey);
for (const item of saved) {
const { lastUpdated, path, cacheKey } = item;
if (!pathGroups.has(path)) {
pathGroups.set(path, {
latest: { lastUpdated, cacheKey },
allVersions: [{ cacheKey }]
});
} else {
const group = pathGroups.get(path)!;
group.allVersions.push({ cacheKey });
if (lastUpdated > group.latest.lastUpdated) {
group.latest = { lastUpdated, cacheKey };
}
}
}
// Now process each unique path
for (const [path, group] of pathGroups) {
if (files[path] === undefined) {
// Was indexed, but no longer exists. Remove all versions
for (const version of group.allVersions) {
remove.push({ path, cacheKey: version.cacheKey });
}
} else {
// Exists in old and new, so determine whether it was updated
if (lastUpdated < files[item.path].lastModified) {
if (group.latest.lastUpdated < files[path].lastModified) {
// Change was made after last update
const newHash = calculateHash(await readFile(pathAndCacheKey.path));
if (pathAndCacheKey.cacheKey !== newHash) {
const newHash = calculateHash(await readFile(path));
if (group.latest.cacheKey !== newHash) {
updateNewVersion.push({
path: pathAndCacheKey.path,
path,
cacheKey: newHash,
});
updateOldVersion.push(pathAndCacheKey);
for (const version of group.allVersions) {
updateOldVersion.push({ path, cacheKey: version.cacheKey });
}
} else {
updateLastUpdated.push(pathAndCacheKey);
// File contents did not change
updateLastUpdated.push({ path, cacheKey: group.latest.cacheKey });
for (const version of group.allVersions) {
if (version.cacheKey !== group.latest.cacheKey) {
updateOldVersion.push({ path, cacheKey: version.cacheKey });
}
}
}
} else {
// Already updated, do nothing
}
// Remove so we can check leftovers afterward
delete files[item.path];
// Remove path, so that only newly created paths remain
delete files[path];
}
}

View file

@ -1,4 +1,9 @@
import { ModelCapability, TemplateType } from "../index.js";
import {
ChatMessage,
ModelCapability,
ModelDescription,
TemplateType,
} from "../index.js";
import {
anthropicTemplateMessages,
@ -52,6 +57,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
"sambanova",
"vertexai",
"watsonx",
"nebius",
];
const PROVIDER_SUPPORTS_IMAGES: string[] = [
@ -65,9 +71,11 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"sagemaker",
"continue-proxy",
"openrouter",
"sambanova",
"vertexai",
"azure",
"scaleway",
"nebius",
];
const MODEL_SUPPORTS_IMAGES: string[] = [
@ -85,14 +93,18 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"haiku",
"pixtral",
"llama3.2",
"llama-3.2",
];
function modelSupportsTools(modelName: string, provider: string) {
const providerSupport = PROVIDER_TOOL_SUPPORT[provider];
function modelSupportsTools(modelDescription: ModelDescription) {
if (modelDescription.capabilities?.tools !== undefined) {
return modelDescription.capabilities.tools;
}
const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider];
if (!providerSupport) {
return false;
}
return providerSupport(modelName) ?? false;
return providerSupport(modelDescription.model) ?? false;
}
function modelSupportsImages(
@ -257,7 +269,10 @@ function autodetectTemplateFunction(
const templateType = explicitTemplate ?? autodetectTemplateType(model);
if (templateType) {
const mapping: Record<TemplateType, any> = {
const mapping: Record<
TemplateType,
null | ((msg: ChatMessage[]) => string)
> = {
llama2: llama2TemplateMessages,
alpaca: templateAlpacaMessages,
phi2: phi2TemplateMessages,

View file

@ -1,87 +1,26 @@
import { ChatHistoryItem, ChatMessage, MessagePart } from "../";
import {
ChatHistoryItem,
ChatMessage,
MessagePart,
ModelDescription,
} from "../";
import { normalizeToMessageParts } from "../util/messageContent";
import { modelSupportsTools } from "./autodetect";
const CUSTOM_SYS_MSG_MODEL_FAMILIES = ["sonnet"];
const SYSTEM_MESSAGE = `When generating new code:
1. Always produce a single code block.
2. Never separate the code into multiple code blocks.
3. Only include the code that is being added.
4. Replace existing code with a "lazy" comment like this: "// ... existing code ..."
5. The "lazy" comment must always be a valid comment in the current context (e.g. "<!-- ... existing code ... -->" for HTML, "// ... existing code ..." for JavaScript, "{/* ... existing code */}" for TSX, etc.)
6. You must always provide 1-2 lines of context above and below a "lazy" comment
7. 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.
Example 1:
Input:
\`\`\`test.js
import addition from "addition"
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
}
\`\`\`
User request: Add a subtract method
Output:
\`\`\`javascript test.js
// ... existing code ...
import subtraction from "subtraction"
class Calculator {
// ... existing code ...
subtract(number) {
this.result -= number;
return this;
}
}
\`\`\`
Example 2:
Input:
\`\`\`javascript test.js (6-9)
function helloWorld() {}
\`\`\`
Output:
\`\`\`javascript test.js
function helloWorld() {
// New code here
}
\`\`\`
Always follow these guidelines when generating code responses.`;
const TOOL_USE_RULES = `When using tools, follow the following guidelines:
- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`;
function constructSystemPrompt(
model: string,
provider: string,
modelDescription: ModelDescription,
useTools: boolean,
): string | null {
let systemMessage = "";
if (CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))) {
systemMessage = SYSTEM_MESSAGE;
let systemMessage =
"Always include the language and file name in the info string when you write code blocks, for example '```python file.py'.";
if (useTools && modelSupportsTools(modelDescription)) {
systemMessage += "\n\n" + TOOL_USE_RULES;
}
if (useTools && modelSupportsTools(model, provider)) {
if (systemMessage) {
systemMessage += "\n\n";
}
systemMessage += TOOL_USE_RULES;
}
return systemMessage || null;
return systemMessage;
}
const CANCELED_TOOL_CALL_MESSAGE =
@ -89,8 +28,7 @@ const CANCELED_TOOL_CALL_MESSAGE =
export function constructMessages(
history: ChatHistoryItem[],
model: string,
provider: string,
modelDescription: ModelDescription,
useTools: boolean,
): ChatMessage[] {
const filteredHistory = history.filter(
@ -98,7 +36,7 @@ export function constructMessages(
);
const msgs: ChatMessage[] = [];
const systemMessage = constructSystemPrompt(model, provider, useTools);
const systemMessage = constructSystemPrompt(modelDescription, useTools);
if (systemMessage) {
msgs.push({
role: "system",

View file

@ -1,3 +1,4 @@
import { ModelRole } from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { findLlmInfo } from "@continuedev/llm-info";
import {
@ -7,6 +8,8 @@ import {
} from "@continuedev/openai-adapters";
import Handlebars from "handlebars";
import { DevDataSqliteDb } from "../data/devdataSqlite.js";
import { DataLogger } from "../data/log.js";
import {
CacheBehavior,
ChatMessage,
@ -21,8 +24,6 @@ import {
RequestOptions,
TemplateType,
} from "../index.js";
import { logDevData } from "../util/devdata.js";
import { DevDataSqliteDb } from "../util/devdataSqlite.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
import { isOllamaInstalled } from "../util/ollamaHelper.js";
@ -117,10 +118,17 @@ export abstract class BaseLLM implements ILLM {
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
deployment?: string;
apiVersion?: string;
@ -191,13 +199,20 @@ export abstract class BaseLLM implements ILLM {
options.model,
this.providerName,
options.template,
);
) ??
undefined;
this.writeLog = options.writeLog;
this.llmRequestHook = options.llmRequestHook;
this.apiKey = options.apiKey;
// continueProperties
this.apiKeyLocation = options.apiKeyLocation;
this.aiGatewaySlug = options.aiGatewaySlug;
this.orgScopeId = options.orgScopeId;
this.apiBase = options.apiBase;
this.onPremProxyUrl = options.onPremProxyUrl;
this.aiGatewaySlug = options.aiGatewaySlug;
this.cacheBehavior = options.cacheBehavior;
// watsonx deploymentId
@ -208,6 +223,7 @@ export abstract class BaseLLM implements ILLM {
}
this.accountId = options.accountId;
this.capabilities = options.capabilities;
this.roles = options.roles;
this.deployment = options.deployment;
this.apiVersion = options.apiVersion;
@ -284,7 +300,7 @@ export abstract class BaseLLM implements ILLM {
return this.templateMessages(msgs);
}
private _compileLogMessage(
private _compilePromptForLog(
prompt: string,
completionOptions: CompletionOptions,
): string {
@ -339,11 +355,14 @@ export abstract class BaseLLM implements ILLM {
generatedTokens,
);
logDevData("tokens_generated", {
model: model,
provider: this.providerName,
promptTokens: promptTokens,
generatedTokens: generatedTokens,
void DataLogger.getInstance().logDevData({
name: "tokensGenerated",
data: {
model: model,
provider: this.providerName,
promptTokens: promptTokens,
generatedTokens: generatedTokens,
},
});
}
@ -443,7 +462,7 @@ export abstract class BaseLLM implements ILLM {
options,
);
return { completionOptions, log, raw };
return { completionOptions, logEnabled: log, raw };
}
private _formatChatMessages(messages: ChatMessage[]): string {
@ -496,12 +515,15 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<string> {
const { completionOptions, log } = this._parseCompletionOptions(options);
const { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(fimLog, completionOptions));
await this.writeLog(
this._compilePromptForLog(fimLog, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, fimLog);
@ -537,7 +559,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, fimLog, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
@ -553,7 +575,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
let prompt = pruneRawPromptFromTop(
@ -567,9 +589,11 @@ export abstract class BaseLLM implements ILLM {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -614,7 +638,7 @@ export abstract class BaseLLM implements ILLM {
} finally {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
}
@ -632,7 +656,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
let prompt = pruneRawPromptFromTop(
@ -646,9 +670,11 @@ export abstract class BaseLLM implements ILLM {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -671,7 +697,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
@ -715,7 +741,8 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage, PromptLog> {
let { completionOptions, log } = this._parseCompletionOptions(options);
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
completionOptions = this._modifyCompletionOptions(completionOptions);
@ -724,9 +751,11 @@ export abstract class BaseLLM implements ILLM {
const prompt = this.templateMessages
? this.templateMessages(messages)
: this._formatChatMessages(messages);
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -793,7 +822,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
@ -957,7 +986,9 @@ export abstract class BaseLLM implements ILLM {
this.providerName,
autodetectTemplateType(this.model),
);
return templateMessages(rendered);
if (templateMessages) {
return templateMessages(rendered);
}
}
return rendered;
}

View file

@ -2,12 +2,14 @@ import * as dotenv from "dotenv";
import { AssistantChatMessage, CompletionOptions } from "..";
import { BaseLLM } from ".";
import Anthropic from "./llms/Anthropic";
import Azure from "./llms/Azure";
import Gemini from "./llms/Gemini";
import Mistral from "./llms/Mistral";
import OpenAI from "./llms/OpenAI";
import { BaseLLM } from ".";
dotenv.config();
const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
@ -222,4 +224,25 @@ describe("LLM", () => {
}),
{ testFim: true, skip: false },
);
testLLM(
new Azure({
apiKey: process.env.AZURE_OPENAI_API_KEY,
model: "gpt-4o",
apiVersion: "2024-05-01-preview",
apiBase: "https://continue-azure-openai-instance.openai.azure.com",
deployment: "azure-openai-deployment",
apiType: "azure-openai",
}),
{ testFim: false, skip: false, timeout: 20000 },
);
testLLM(
new Azure({
apiKey: process.env.AZURE_FOUNDRY_API_KEY,
model: "codestral-latest",
apiBase:
"https://codestral-2501-continue-testing.eastus.models.ai.azure.com",
apiType: "azure-foundry",
}),
{ testFim: false, skip: false, timeout: 20000 },
);
});

View file

@ -145,6 +145,12 @@ class Anthropic extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (!this.apiKey || this.apiKey === "") {
throw new Error(
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
);
}
const shouldCacheSystemMessage =
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(

View file

@ -14,7 +14,7 @@ class Azure extends OpenAI {
static defaultOptions: Partial<LLMOptions> = {
apiVersion: "2024-02-15-preview",
apiType: "azure",
apiType: "azure-openai",
};
constructor(options: LLMOptions) {

View file

@ -0,0 +1,375 @@
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import Bedrock from "./Bedrock.js";
import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js";
// Mock AWS SDK
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
BedrockRuntimeClient: jest.fn().mockImplementation(() => ({
send: jest.fn(),
middlewareStack: { add: jest.fn() },
})),
ConverseStreamCommand: jest.fn(),
InvokeModelCommand: jest.fn(),
}));
// Mock credential provider
jest.mock("@aws-sdk/credential-providers", () => ({
fromIni: jest.fn().mockImplementation(() => async () => ({
accessKeyId: "test-access-key",
secretAccessKey: "test-secret-key",
sessionToken: "test-session-token",
})),
}));
// Extend CompletionOptions for testing
interface TestCompletionOptions extends CompletionOptions {
mockError?: string;
mockToolUse?: boolean;
}
// Create a test class that overrides the protected methods
class TestBedrock extends Bedrock {
// Make _streamChat public for testing
public async *streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: TestCompletionOptions
): AsyncGenerator<ChatMessage> {
if (options.mockError) {
throw new Error(options.mockError);
}
if (options.mockToolUse) {
yield {
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}'
}
}],
};
return;
}
yield { role: "assistant", content: "Hello" };
yield { role: "assistant", content: " world" };
}
// Override embed to avoid making real API calls
async embed(chunks: string[]): Promise<number[][]> {
if (chunks[0] === "error") {
throw new Error("Embedding Error");
}
return [[0.1, 0.2, 0.3]];
}
// Override rerank to avoid making real API calls
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
if (!query || !chunks.length) {
throw new Error("Query and chunks must not be empty");
}
if (query === "error") {
throw new Error("Reranking Error");
}
return chunks.map((_, i) => 0.8 - i * 0.3);
}
}
describe("Bedrock", () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe("constructor", () => {
it("should initialize with default options", () => {
const bedrock = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
expect(bedrock.region).toBe("us-east-1");
expect(bedrock.profile).toBe("bedrock");
expect(bedrock.apiBase).toBe("https://bedrock-runtime.us-east-1.amazonaws.com");
});
it("should use custom options when provided", () => {
const bedrock = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-west-2",
profile: "custom-profile",
apiBase: "https://custom-endpoint.amazonaws.com/",
});
expect(bedrock.region).toBe("us-west-2");
expect(bedrock.profile).toBe("custom-profile");
expect(bedrock.apiBase).toBe("https://custom-endpoint.amazonaws.com/");
});
});
describe("streamChat", () => {
let bedrock: TestBedrock;
const mockAbortSignal = new AbortController().signal;
const defaultOptions: TestCompletionOptions = {
model: "anthropic.claude-3-sonnet-20240229-v1:0",
};
beforeEach(() => {
bedrock = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
});
it("should handle text streaming correctly", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Hi"
} as UserChatMessage];
const results = [];
for await (const message of bedrock.streamChat(messages, mockAbortSignal, defaultOptions)) {
results.push(message);
}
expect(results).toEqual([
{ role: "assistant", content: "Hello" },
{ role: "assistant", content: " world" },
]);
});
it("should handle tool use streaming correctly", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Use a tool"
} as UserChatMessage];
const results = [];
const options: TestCompletionOptions = {
...defaultOptions,
mockToolUse: true
};
for await (const message of bedrock.streamChat(messages, mockAbortSignal, options)) {
results.push(message);
}
expect(results).toEqual([
{
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}'
}
}],
},
]);
});
it("should handle API errors", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Hi"
} as UserChatMessage];
const options: TestCompletionOptions = {
...defaultOptions,
mockError: "API Error"
};
await expect(async () => {
for await (const _ of bedrock.streamChat(messages, mockAbortSignal, options)) {
// consume generator
}
}).rejects.toThrow("API Error");
});
});
describe("embed", () => {
let bedrock: TestBedrock;
beforeEach(() => {
bedrock = new TestBedrock({
apiKey: "test-key",
model: "cohere.embed-english-v3",
region: "us-east-1",
});
});
it("should handle embedding requests correctly", async () => {
const result = await bedrock.embed(["test text"]);
expect(result).toEqual([[0.1, 0.2, 0.3]]);
});
it("should handle embedding errors", async () => {
await expect(bedrock.embed(["error"])).rejects.toThrow("Embedding Error");
});
});
describe("rerank", () => {
let bedrock: TestBedrock;
beforeEach(() => {
bedrock = new TestBedrock({
apiKey: "test-key",
model: "cohere.rerank-english-v2.0",
region: "us-east-1",
});
});
it("should handle reranking requests correctly", async () => {
const chunks: Chunk[] = [
{
content: "doc1",
digest: "digest1",
filepath: "file1",
index: 0,
startLine: 1,
endLine: 1
},
{
content: "doc2",
digest: "digest2",
filepath: "file2",
index: 1,
startLine: 1,
endLine: 1
}
];
const result = await bedrock.rerank("query", chunks);
expect(result).toEqual([0.8, 0.5]);
});
it("should handle reranking errors", async () => {
const chunk: Chunk = {
content: "doc1",
digest: "digest1",
filepath: "file1",
index: 0,
startLine: 1,
endLine: 1
};
await expect(
bedrock.rerank("error", [chunk])
).rejects.toThrow("Reranking Error");
});
it("should throw error for empty input", async () => {
await expect(bedrock.rerank("", [])).rejects.toThrow("Query and chunks must not be empty");
});
});
describe("message conversion", () => {
let bedrock: TestBedrock;
beforeEach(() => {
bedrock = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
});
it("should convert text messages correctly", () => {
const message: ChatMessage = {
role: "user",
content: "Hello"
} as UserChatMessage;
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [{ text: "Hello" }],
});
});
it("should convert tool responses correctly", () => {
const message: ChatMessage = {
role: "tool",
content: "Tool result",
toolCallId: "tool-1",
};
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
},
}],
});
});
it("should convert tool calls correctly", () => {
const message: ChatMessage = {
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function" as const,
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
},
}],
};
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "assistant",
content: [{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
},
}],
});
});
it("should handle multimodal content correctly", () => {
const message: ChatMessage = {
role: "user",
content: [
{ type: "text", text: "Look at this image:" },
{
type: "imageUrl",
imageUrl: {
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
},
},
],
} as UserChatMessage;
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [
{ text: "Look at this image:" },
{
image: {
format: "jpeg",
source: {
bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
},
},
},
],
});
});
});
});

View file

@ -10,16 +10,25 @@ import {
Chunk,
CompletionOptions,
LLMOptions,
MessageContent,
} from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
interface ModelConfig {
formatPayload: (text: string) => any;
extractEmbeddings: (responseBody: any) => number[][];
}
/**
* Interface for tool use state tracking
*/
interface ToolUseState {
toolUseId: string;
name: string;
input: string;
}
class Bedrock extends BaseLLM {
static providerName = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
@ -29,6 +38,10 @@ class Bedrock extends BaseLLM {
profile: "bedrock",
};
private _currentToolResponse: Partial<ToolUseState> | null = null;
public requestOptions: { region?: string; credentials?: any; headers?: Record<string, string> };
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
@ -39,6 +52,10 @@ class Bedrock extends BaseLLM {
} else {
this.profile = "bedrock";
}
this.requestOptions = {
region: options.region,
headers: {},
};
}
protected async *_streamComplete(
@ -58,7 +75,6 @@ class Bedrock extends BaseLLM {
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
endpoint: this.apiBase,
@ -70,9 +86,9 @@ class Bedrock extends BaseLLM {
});
let config_headers =
this.requestOptions && this.requestOptions.headers
? this.requestOptions.headers
: {};
this.requestOptions && this.requestOptions.headers
? this.requestOptions.headers
: {};
// AWS SigV4 requires strict canonicalization of headers.
// DO NOT USE "_" in your header name. It will return an error like below.
// "The request signature we calculated does not match the signature you provided."
@ -90,32 +106,116 @@ class Bedrock extends BaseLLM {
},
);
const input = this._generateConverseInput(messages, options);
const input = this._generateConverseInput(messages, { ...options, stream: true });
const command = new ConverseStreamCommand(input);
const response = await client.send(command, { abortSignal: signal });
if (response.stream) {
let response;
try {
response = await client.send(command, { abortSignal: signal });
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown error";
throw new Error(`Failed to communicate with Bedrock API: ${message}`);
}
if (!response?.stream) {
throw new Error("No stream received from Bedrock API");
}
try {
for await (const chunk of response.stream) {
if (chunk.contentBlockDelta?.delta?.text) {
yield {
role: "assistant",
content: chunk.contentBlockDelta.delta.text,
};
console.log(chunk);
if (chunk.contentBlockDelta?.delta) {
// Handle text content
if (chunk.contentBlockDelta.delta.text) {
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
continue;
}
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
// Append the new input to the existing string
if (this._currentToolResponse.input === undefined) {
this._currentToolResponse.input = "";
}
this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input;
continue;
}
}
if (chunk.contentBlockStart?.start) {
const toolUse = chunk.contentBlockStart.start.toolUse;
if (toolUse?.toolUseId && toolUse?.name) {
this._currentToolResponse = {
toolUseId: toolUse.toolUseId,
name: toolUse.name,
input: ""
};
}
continue;
}
if (chunk.contentBlockStop) {
if (this._currentToolResponse) {
yield {
role: "assistant",
content: "",
toolCalls: [{
id: this._currentToolResponse.toolUseId,
type: "function",
function: {
name: this._currentToolResponse.name,
arguments: this._currentToolResponse.input
}
}],
};
this._currentToolResponse = null;
}
continue;
}
}
} catch (error: unknown) {
this._currentToolResponse = null;
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`);
}
throw new Error(`Error processing Bedrock stream: ${error.message}`);
}
throw new Error("Error processing Bedrock stream: Unknown error occurred");
}
}
/**
* Generates the input payload for the Bedrock Converse API
* @param messages - Array of chat messages
* @param options - Completion options
* @returns Formatted input payload for the API
*/
private _generateConverseInput(
messages: ChatMessage[],
options: CompletionOptions,
): any {
const convertedMessages = this._convertMessages(messages);
const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
return {
modelId: options.model,
messages: convertedMessages,
system: this.systemMessage ? [{ text: this.systemMessage }] : undefined,
toolConfig: supportsTools && options.tools ? {
tools: options.tools.map(tool => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters
}
}
}))
} : undefined,
inferenceConfig: {
maxTokens: options.maxTokens,
temperature: options.temperature,
@ -135,35 +235,93 @@ class Bedrock extends BaseLLM {
};
}
private _convertMessages(messages: ChatMessage[]): any[] {
return messages
.filter((message) => message.role !== "system")
.map((message) => ({
private _convertMessage(message: ChatMessage): any {
// Handle system messages explicitly
if (message.role === "system") {
return;
}
// Tool response handling
if (message.role === "tool") {
return {
role: "user",
content: [
{
toolResult: {
toolUseId: message.toolCallId,
content: [
{
text: message.content || ""
}
]
}
}
]
};
}
// Tool calls handling
if (message.role === "assistant" && message.toolCalls) {
return {
role: "assistant",
content: message.toolCalls.map((toolCall) => ({
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function?.name,
input: JSON.parse(toolCall.function?.arguments || "{}"),
}
}))
};
}
// Standard text message
if (typeof message.content === "string") {
return {
role: message.role,
content: this._convertMessageContent(message.content),
}));
content: [{ text: message.content }]
};
}
// Improved multimodal content handling
if (Array.isArray(message.content)) {
return {
role: message.role,
content: message.content.map(part => {
if (part.type === "text") {
return { text: part.text };
}
if (part.type === "imageUrl" && part.imageUrl) {
try {
const [mimeType, base64Data] = part.imageUrl.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
return {
image: {
format,
source: {
bytes: Buffer.from(base64Data, "base64")
}
}
};
} catch (error) {
console.warn(`Failed to process image: ${error}`);
return null;
}
}
return null;
}).filter(Boolean)
};
}
}
private _convertMessageContent(messageContent: MessageContent): any[] {
if (typeof messageContent === "string") {
return [{ text: messageContent }];
}
return messageContent
.map((part) => {
if (part.type === "text") {
return { text: part.text };
private _convertMessages(messages: ChatMessage[]): any[] {
return messages
.map((message) => {
try {
return this._convertMessage(message);
} catch (error) {
console.error(`Failed to convert message: ${error}`);
return null;
}
if (part.type === "imageUrl" && part.imageUrl) {
return {
image: {
format: "jpeg",
source: {
bytes: Buffer.from(part.imageUrl.url.split(",")[1], "base64"),
},
},
};
}
return null;
})
.filter(Boolean);
}
@ -229,6 +387,7 @@ class Bedrock extends BaseLLM {
return modelConfig.extractEmbeddings(responseBody);
}
private _getModelConfig() {
const modelConfigs: { [key: string]: ModelConfig } = {
cohere: {
@ -301,9 +460,15 @@ class Bedrock extends BaseLLM {
return responseBody.results
.sort((a: any, b: any) => a.index - b.index)
.map((result: any) => result.relevance_score);
} catch (error) {
console.error("Error in BedrockReranker.rerank:", error);
throw error;
} catch (error: unknown) {
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`);
}
throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
}
throw new Error("Error in BedrockReranker.rerank: Unknown error occurred");
}
}
}

View file

@ -215,7 +215,7 @@ class FreeTrial extends BaseLLM {
"llama3.1-70b",
"gpt-4o",
"gpt-3.5-turbo",
"claude-3-haiku-20240307",
"claude-3-5-haiku-latest",
"gemini-1.5-pro-latest",
];
}

View file

@ -1,4 +1,3 @@
import { r } from "tar";
import {
AssistantChatMessage,
ChatMessage,
@ -7,6 +6,7 @@ import {
MessagePart,
ToolCallDelta,
} from "../../index.js";
import { findLast } from "../../util/findLast.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
@ -17,7 +17,6 @@ import {
GeminiGenerationConfig,
GeminiToolFunctionDeclaration,
} from "./gemini-types.js";
import { findLast } from "../../util/findLast.js";
class Gemini extends BaseLLM {
static providerName = "gemini";
@ -253,7 +252,7 @@ class Gemini extends BaseLLM {
}
// Helper function to recursively clean JSON Schema objects
const cleanJsonSchema = (schema: any): any => {
if (!schema || typeof schema !== 'object') return schema;
if (!schema || typeof schema !== "object") return schema;
if (Array.isArray(schema)) {
return schema.map(cleanJsonSchema);
@ -273,7 +272,7 @@ class Gemini extends BaseLLM {
...acc,
[key]: cleanJsonSchema(value),
}),
{}
{},
);
}
@ -349,8 +348,8 @@ class Gemini extends BaseLLM {
// Process all parts first to maintain order
const processedParts: Array<{
type: 'content' | 'tool' | 'toolCall',
data: any
type: "content" | "tool" | "toolCall";
data: any;
}> = [];
for (const part of content.parts) {
@ -366,7 +365,7 @@ class Gemini extends BaseLLM {
} else if ("functionCall" in part) {
// Queue function call
processedParts.push({
type: 'toolCall',
type: "toolCall",
data: {
type: "function",
id: "", // Not supported by gemini
@ -377,17 +376,17 @@ class Gemini extends BaseLLM {
? part.functionCall.args
: JSON.stringify(part.functionCall.args),
},
}
},
});
} else if ("functionResponse" in part) {
// Queue function response
processedParts.push({
type: 'tool',
type: "tool",
data: {
role: "tool",
content: part.functionResponse.response.output as string,
toolCallId: part.functionResponse.name,
}
},
});
} else {
console.warn("Unsupported gemini part type received", part);
@ -404,13 +403,13 @@ class Gemini extends BaseLLM {
// Then process tool calls and responses in order
for (const part of processedParts) {
if (part.type === 'toolCall') {
if (part.type === "toolCall") {
yield {
role: "assistant",
content: "",
toolCalls: [part.data],
};
} else if (part.type === 'tool') {
} else if (part.type === "tool") {
yield part.data;
}
}

62
core/llm/llms/NCompass.ts Normal file
View file

@ -0,0 +1,62 @@
import { ChatCompletionCreateParams } from "openai/resources/index";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import OpenAI from "./OpenAI.js";
class NCompass extends OpenAI {
static providerName = "ncompass";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.ncompass.tech/v1"
};
static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings"
private static modelConversion: { [key: string]: string } = {
"qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
"qwen2.5-coder:7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
"qwen2.5-coder-32b": "Qwen/Qwen2.5-Coder-32B-Instruct",
"qwen2.5-coder:32b": "Qwen/Qwen2.5-Coder-32B-Instruct",
};
protected _convertModelName(model: string): string {
return NCompass.modelConversion[model] ?? model;
}
protected _convertArgs(
options: CompletionOptions,
messages: ChatMessage[],
): ChatCompletionCreateParams {
const finalOptions = super._convertArgs(options, messages);
finalOptions.model = this._convertModelName(options.model);
return finalOptions;
}
protected _getHeaders() {
const headers = super._getHeaders() as { "Content-Type": string; Authorization: string; "api-key": string; Accept?: string };
headers["Accept"] = "text/event-stream";
return headers;
}
protected async _embed(chunks: string[]): Promise<number[][]> {
const resp = await this.fetch(NCompass.embeddingsApiEndpoint, {
method: "POST",
body: JSON.stringify({
input: chunks,
model: this.model,
...this.extraBodyProperties(),
}),
headers: {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const data = (await resp.json()) as any;
return data.data.map((result: { embedding: number[] }) => result.embedding);
}
}
export default NCompass;

View file

@ -10,6 +10,10 @@ class Nebius extends OpenAI {
};
private static MODEL_IDS: { [name: string]: string } = {
"deepseek/deepseek_v3": "deepseek-ai/DeepSeek-V3",
"deepseek/deepseek-r1": "deepseek-ai/DeepSeek-R1",
"qwen2.5-coder-32b": "Qwen/Qwen2.5-Coder-32B-Instruct-fast",
"Qwen/QwQ-32B-Preview": "Qwen/QwQ-32B-Preview",
"llama3.1-70b-nemotron": "nvidia/Llama-3.1-Nemotron-70B-Instruct-HF-fast",
"llama3.1-8b": "meta-llama/Meta-Llama-3.1-70B-Instruct-fast",
"llama3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct-fast",

View file

@ -9,6 +9,8 @@ class Novita extends OpenAI {
};
private static MODEL_IDS: { [name: string]: string } = {
"deepseek-r1": "deepseek/deepseek-r1",
"deepseek_v3": "deepseek/deepseek_v3",
"llama3-8b": "meta-llama/llama-3-8b-instruct",
"llama3-70b": "meta-llama/llama-3-70b-instruct",
"llama3.1-8b": "meta-llama/llama-3.1-8b-instruct",

View file

@ -139,12 +139,17 @@ class Ollama extends BaseLLM {
if (options.model === "AUTODETECT") {
return;
}
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers.Authorization = `Bearer ${this.apiKey}`;
}
this.fetch(this.getEndpoint("api/show"), {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
headers: headers,
body: JSON.stringify({ name: this._getModel() }),
})
.then(async (response) => {
@ -323,12 +328,16 @@ class Ollama extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers.Authorization = `Bearer ${this.apiKey}`;
}
const response = await this.fetch(this.getEndpoint("api/generate"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
headers: headers,
body: JSON.stringify(this._getGenerateOptions(options, prompt)),
signal,
});
@ -384,13 +393,16 @@ class Ollama extends BaseLLM {
}));
chatOptions.stream = false; // Cannot set stream = true for tools calls
}
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers.Authorization = `Bearer ${this.apiKey}`;
}
const response = await this.fetch(this.getEndpoint("api/chat"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
headers: headers,
body: JSON.stringify(chatOptions),
signal,
});
@ -467,12 +479,16 @@ class Ollama extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers.Authorization = `Bearer ${this.apiKey}`;
}
const response = await this.fetch(this.getEndpoint("api/generate"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
headers: headers,
body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)),
signal,
});
@ -504,11 +520,19 @@ class Ollama extends BaseLLM {
}
async listModels(): Promise<string[]> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers.Authorization = `Bearer ${this.apiKey}`;
}
const response = await this.fetch(
// localhost was causing fetch failed in pkg binary only for this Ollama endpoint
this.getEndpoint("api/tags"),
{
method: "GET",
headers: headers,
},
);
const data = await response.json();
@ -522,16 +546,20 @@ class Ollama extends BaseLLM {
}
protected async _embed(chunks: string[]): Promise<number[][]> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers.Authorization = `Bearer ${this.apiKey}`;
}
const resp = await this.fetch(new URL("api/embed", this.apiBase), {
method: "POST",
body: JSON.stringify({
model: this.model,
input: chunks,
}),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
headers: headers
});
if (!resp.ok) {

View file

@ -49,7 +49,7 @@ const CHAT_ONLY_MODELS = [
"gpt-4o-mini",
"o1-preview",
"o1-mini",
"o3-mini"
"o3-mini",
];
const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => {
@ -206,18 +206,25 @@ class OpenAI extends BaseLLM {
protected _getEndpoint(
endpoint: "chat/completions" | "completions" | "models",
) {
if (this.apiType === "azure") {
return new URL(
`openai/deployments/${this.deployment}/${endpoint}?api-version=${this.apiVersion}`,
this.apiBase,
);
}
if (!this.apiBase) {
throw new Error(
"No API base URL provided. Please set the 'apiBase' option in config.json",
);
}
if (this.apiType?.includes("azure")) {
// Default is `azure-openai`, but previously was `azure`
const isAzureOpenAI =
this.apiType === "azure-openai" || this.apiType === "azure";
const path = isAzureOpenAI
? `openai/deployments/${this.deployment}/${endpoint}`
: endpoint;
const version = this.apiVersion ? `?api-version=${this.apiVersion}` : "";
return new URL(`${path}${version}`, this.apiBase);
}
return new URL(endpoint, this.apiBase);
}
@ -267,7 +274,7 @@ class OpenAI extends BaseLLM {
body.max_completion_tokens = undefined;
}
if (body.tools?.length) {
if (body.tools?.length && !body.model?.startsWith("o3")) {
// To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs
// In practice, setting this to true and asking for multiple tool calls
// leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}'

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