Merge branch 'main' into fix-menu-readonly-editor

This commit is contained in:
Nate 2025-02-21 10:18:24 -08:00
commit ce0f0ec25c
381 changed files with 11891 additions and 7222 deletions

View file

@ -27,14 +27,15 @@ body:
- **Continue version**: v0.9.4
- **IDE version**: VSCode 1.85.1
- Model: Claude Sonnet 3.5
- config.json: `{ "models": ... }`
- config.yaml: `models: ...`
- OR config.json: `{ "models": ... }`
value: |
- OS:
- Continue version:
- IDE version:
- Model:
- config.json:
```json
- config:
```yaml
```
render: Markdown

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
@ -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

@ -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

@ -1,42 +1,19 @@
name: PR checks
on:
pull_request_target:
pull_request:
branches:
- main
paths:
- "extensions/intellij/**"
- "extensions/vscode/**"
- "core/**"
- "gui/**"
- ".github/workflows/**"
push:
branches:
- main
paths:
- "extensions/intellij/**"
- "extensions/vscode/**"
- "core/**"
- "gui/**"
- ".github/workflows/**"
jobs:
validate-pr:
runs-on: ubuntu-latest
environment: tests-requiring-secrets
steps:
- uses: actions/checkout@v4
install-root:
needs: validate-pr
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
# This is important - it switches from the base repo to the fork
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -57,9 +34,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -86,12 +60,8 @@ jobs:
core-checks:
needs: install-core
runs-on: ubuntu-latest
environment: tests-requiring-secrets
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -122,9 +92,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -157,9 +124,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -191,9 +155,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -231,9 +192,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -268,9 +226,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -303,9 +258,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -321,10 +273,13 @@ jobs:
cd core
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
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
@ -333,9 +288,6 @@ jobs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- name: Cache node modules
uses: actions/cache@v3
@ -363,9 +315,6 @@ jobs:
needs: [install-vscode, install-core]
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -399,9 +348,6 @@ jobs:
needs: [install-vscode, install-core]
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -443,7 +389,6 @@ jobs:
]
runs-on: ubuntu-latest
# Tests requiring secrets need approval from maintainers
environment: tests-requiring-secrets
strategy:
fail-fast: false
matrix:
@ -451,9 +396,6 @@ jobs:
command: ["e2e:ci:run", "e2e:ci:run-yaml"]
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -492,6 +434,7 @@ jobs:
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts
echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config
if: ${{ github.event.pull_request.head.repo.fork == false }}
- name: Set up Xvfb
run: |
@ -501,7 +444,7 @@ jobs:
- name: Run e2e tests
run: |
cd extensions/vscode
TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
env:
DISPLAY: :99
@ -517,9 +460,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/setup-node@v4
with:
@ -552,10 +492,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
- uses: actions/cache@v4
with:
path: core/node_modules

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
@ -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:

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

16
SECURITY.md Normal file
View file

@ -0,0 +1,16 @@
# Security Policy
## Reporting a Vulnerability
If you discover a security vulnerability, please do not open a public issue. Instead, please report it by emailing security@continue.dev. We will be highly responsive to all security concerns and ask that you give us sufficient time to investigate and address the vulnerability before disclosing it publicly.
Please include the following details in your report:
- A description of the vulnerability
- Steps to reproduce the issue
- Your assessment of the potential impact
- Any possible mitigations
## Contact
For any other questions or concerns related to security, please contact us at security@continue.dev.

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`);

View file

@ -48,11 +48,11 @@
"@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.16",
"@continuedev/config-yaml": "^1.0.28",
"@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",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@ -128,7 +128,7 @@
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"esbuild": "0.24.0",
"eslint": "^8",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
@ -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": {

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

@ -246,6 +246,7 @@ export class CompletionProvider {
completionOptions,
cacheHit,
filepath: helper.filepath,
numLines: completion.split("\n").length,
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),

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

@ -113,6 +113,7 @@ export class AutocompleteLoggingService {
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
},
true,
);

View file

@ -1,10 +1,4 @@
import {
Position,
Range,
RangeInFile,
RangeInFileWithContents,
TabAutocompleteOptions,
} from "../..";
import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../..";
import { AutocompleteCodeSnippet } from "../snippets/types";
export type RecentlyEditedRange = RangeInFile & {
@ -42,6 +36,7 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
modelName: string;
completionOptions: any;
cacheHit: boolean;
numLines: number;
filepath: string;
gitRepo?: string;
completionId: string;

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,9 +1,17 @@
import * as fs from "node:fs";
import {
AssistantUnrolled,
ConfigResult,
FullSlug,
} from "@continuedev/config-yaml";
import * as YAML from "yaml";
import {
ControlPlaneClient,
ControlPlaneSessionInfo,
} from "../control-plane/client.js";
import { getControlPlaneEnv, useHub } from "../control-plane/env.js";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@ -15,18 +23,11 @@ import {
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js";
import { localPathToUri } from "../util/pathToUri.js";
import {
AssistantUnrolled,
ConfigResult,
FullSlug,
} from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { getControlPlaneEnv, useHub } from "../control-plane/env.js";
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";
@ -46,55 +47,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;
private 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: ", 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,
);
}
@ -111,73 +151,87 @@ 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.configResult.config?.version ?? "latest",
this.controlPlaneClient,
let profiles: ProfileLifecycleManager[] | null = null;
if (!userId) {
// Not logged in
profiles = [this.localProfileManager];
} else {
// Logged in
const assistants =
await this.controlPlaneClient.listAssistants(selectedOrgId);
const hubProfiles = await Promise.all(
assistants.map(async (assistant) => {
let renderedConfig: AssistantUnrolled | undefined = undefined;
if (assistant.configResult.config) {
renderedConfig = await clientRenderHelper(
{
ownerSlug: assistant.ownerSlug,
packageSlug: assistant.packageSlug,
},
YAML.stringify(assistant.configResult.config),
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
this.controlPlaneClient,
);
}
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
);
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,
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),
);
}
})
.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();
const selectedProfileId =
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;
@ -202,78 +256,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);
@ -310,16 +367,25 @@ export class ConfigHandler {
});
}
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);
}
}
@ -336,33 +402,54 @@ export class ConfigHandler {
this.updateListeners.push(listener);
}
// TODO: this isn't right, there are two different senses in which you want to "reload"
async reloadConfig() {
// TODO: this isn't right, there are two different senses in which you want to "reload"
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
const { config, errors, configLoadInterrupted } =
await this.currentProfile.reloadConfig();
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,
);
@ -372,7 +459,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,

View file

@ -3,6 +3,7 @@ import {
ConfigValidationError,
FullSlug,
} from "@continuedev/config-yaml";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@ -18,9 +19,17 @@ export interface ProfileDescription {
profileType: "control-plane" | "local" | "platform";
title: string;
id: string;
iconUrl: string;
errors: ConfigValidationError[] | undefined;
}
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 {
private savedConfigResult: ConfigResult<ContinueConfig> | undefined;
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;
@ -42,12 +51,14 @@ export class ProfileLifecycleManager {
}
// Clear saved config and reload
async reloadConfig(): Promise<ConfigResult<ContinueConfig>> {
async reloadConfig(
additionalContextProviders: IContextProvider[] = [],
): Promise<ConfigResult<ContinueConfig>> {
this.savedConfigResult = undefined;
this.savedBrowserConfigResult = undefined;
this.pendingConfigPromise = undefined;
return this.loadConfig([], true);
return this.loadConfig(additionalContextProviders, true);
}
async loadConfig(
@ -65,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,13 @@ export const defaultSlashCommandsJetBrains = [
];
export const defaultConfig: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
models: [],
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
};
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
models: [],
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
};

View file

@ -63,6 +63,8 @@ import {
} from "../util/paths";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import { useHub } from "../control-plane/env";
import { localPathToUri } from "../util/pathToUri";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -70,8 +72,6 @@ import {
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { useHub } from "../control-plane/env";
import { localPathToUri } from "../util/pathToUri";
import { modifyContinueConfigWithSharedConfig } from "./sharedConfig";
import { validateConfig } from "./validation.js";
@ -326,6 +326,7 @@ async function intermediateToFinalConfig(
...model.requestOptions,
...config.requestOptions,
};
model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified
}
if (allowFreeTrial) {
@ -517,6 +518,8 @@ async function intermediateToFinalConfig(
continueConfig,
mcpId,
abortController.signal,
"MCP Server",
server.faviconUrl,
);
if (mcpError) {
errors.push(mcpError);
@ -557,6 +560,7 @@ async function finalToBrowserConfig(
requestOptions: m.requestOptions,
promptTemplates: m.promptTemplates as any,
capabilities: m.capabilities,
roles: m.roles,
})),
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,

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

@ -1,4 +1,5 @@
import { ConfigJson } from "@continuedev/config-types";
import { ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import {
@ -7,9 +8,8 @@ import {
IdeSettings,
SerializedContinueConfig,
} from "../../index.js";
import { ConfigResult } from "@continuedev/config-yaml";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
@ -32,6 +32,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
this.description = {
id: workspaceId,
profileType: "control-plane",
iconUrl: "",
fullSlug: {
ownerSlug: "",
packageSlug: "",

View file

@ -1,8 +1,9 @@
import { 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";
import { IProfileLoader } from "./IProfileLoader.js";
@ -16,6 +17,7 @@ export default class LocalProfileLoader implements IProfileLoader {
packageSlug: "",
versionSlug: "",
},
iconUrl: "",
title: "Local Config",
errors: undefined,
};

View file

@ -1,10 +1,9 @@
import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas/index.js";
import { ConfigResult, AssistantUnrolled } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ConfigResult } from "@continuedev/config-yaml";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
@ -27,6 +26,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
private configResult: ConfigResult<AssistantUnrolled>,
private readonly ownerSlug: string,
private readonly packageSlug: string,
private readonly iconUrl: string,
versionSlug: string,
private readonly controlPlaneClient: ControlPlaneClient,
private readonly ide: IDE,
@ -44,6 +44,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
},
title: `${ownerSlug}/${packageSlug}@${versionSlug}`,
errors: configResult.errors,
iconUrl: this.iconUrl,
};
}

View file

@ -21,9 +21,9 @@ 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";
export default async function doLoadConfig(
ide: IDE,
@ -124,12 +124,14 @@ export default async function doLoadConfig(
if (newConfig.analytics) {
await TeamAnalytics.setup(
newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all
newConfig.analytics,
uniqueId,
ideInfo.extensionVersion,
controlPlaneClient,
controlPlaneProxyInfo,
);
} else {
await TeamAnalytics.shutdown();
}
newConfig = await injectControlPlaneProxyInfo(

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

@ -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 {

View file

@ -1,5 +1,6 @@
import {
clientRender,
PackageSlug,
PlatformClient,
SecretStore,
} from "@continuedev/config-yaml";
@ -8,6 +9,7 @@ import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
export async function clientRenderHelper(
packageSlug: PackageSlug,
unrolledAssistant: string,
ide: IDE,
controlPlaneClient: ControlPlaneClient,
@ -33,6 +35,7 @@ export async function clientRenderHelper(
const userId = await controlPlaneClient.userId;
return await clientRender(
packageSlug,
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 "../..";

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,12 +3,14 @@ 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,
@ -16,9 +18,11 @@ import {
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,17 +32,15 @@ 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 { slashFromCustomCommand } from "../../commands";
import { allTools } from "../../tools";
import { clientRenderHelper } from "./clientRender";
import { llmsFromModelConfig } from "./models";
import { GlobalContext } from "../../util/GlobalContext";
import { modifyContinueConfigWithSharedConfig } from "../sharedConfig";
import { llmsFromModelConfig } from "./models";
async function loadConfigYaml(
workspaceConfigs: string[],
rawYaml: 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)) {
@ -96,7 +103,8 @@ async function configYamlToContinueConfig(
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)),
@ -127,12 +135,10 @@ async function configYamlToContinueConfig(
};
// 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),
)
) {
model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
// Main model array
const llms = await llmsFromModelConfig(
model,
@ -159,6 +165,24 @@ async function configYamlToContinueConfig(
);
continueConfig.tabAutocompleteModels?.push(...llms);
}
if (
model.roles?.includes("apply") &&
!continueConfig.experimental?.modelRoles?.applyCodeBlock
) {
continueConfig.experimental ??= {};
continueConfig.experimental!.modelRoles ??= {};
continueConfig.experimental!.modelRoles!.applyCodeBlock = model.name;
}
if (
model.roles?.includes("edit") &&
!continueConfig.experimental?.modelRoles?.inlineEdit
) {
continueConfig.experimental ??= {};
continueConfig.experimental!.modelRoles ??= {};
continueConfig.experimental!.modelRoles!.inlineEdit = model.name;
}
}
if (allowFreeTrial) {
@ -210,7 +234,17 @@ async function configYamlToContinueConfig(
.filter((p) => !!p) ?? []) as IContextProvider[];
continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
if (
continueConfig.docs?.length &&
!continueConfig.contextProviders?.some(
(cp) => cp.description.title === "docs",
)
) {
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
// Embeddings Provider
// IMPORTANT this currently will grab the first model found with an embed role
const embedConfig = config.models?.find((model) =>
model.roles?.includes("embed"),
);
@ -235,6 +269,7 @@ async function configYamlToContinueConfig(
}
// Reranker
// IMPORTANT this currently will grab the first model found with a rerank role
const rerankConfig = config.models?.find((model) =>
model.roles?.includes("rerank"),
);
@ -255,40 +290,51 @@ async function configYamlToContinueConfig(
// 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(
@ -324,7 +370,7 @@ export async function loadContinueConfigFromYaml(
};
}
const continueConfig = await configYamlToContinueConfig(
const { config: continueConfig, errors } = await configYamlToContinueConfig(
configYamlResult.config,
ide,
ideSettings,
@ -353,9 +399,7 @@ export async function loadContinueConfigFromYaml(
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,8 +47,8 @@ async function modelConfigToBaseLLM(
writeLog,
uniqueId,
title: model.name,
model: modelName,
systemMessage,
promptTemplates: model.promptTemplates,
};
const llm = new cls(options);

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

@ -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");

View file

@ -1,6 +1,6 @@
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";
@ -111,18 +111,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

@ -1,7 +1,5 @@
import os from "node:os";
import { Analytics } from "@continuedev/config-types";
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js";
import {
ControlPlaneProxyInfo,
@ -10,9 +8,10 @@ import {
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js";
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js";
import { ControlPlaneClient } from "./client.js";
import { AnalyticsConfig } from "../index.js";
function createAnalyticsProvider(
config: Analytics,
config: AnalyticsConfig,
): IAnalyticsProvider | undefined {
// @ts-ignore
switch (config.provider) {
@ -42,7 +41,7 @@ export class TeamAnalytics {
}
static async setup(
config: Analytics,
config: AnalyticsConfig,
uniqueId: string,
extensionVersion: string,
controlPlaneClient: ControlPlaneClient,
@ -52,22 +51,27 @@ export class TeamAnalytics {
TeamAnalytics.os = os.platform();
TeamAnalytics.extensionVersion = extensionVersion;
if (!config) {
await TeamAnalytics.provider?.shutdown();
TeamAnalytics.provider = undefined;
} else {
TeamAnalytics.provider = createAnalyticsProvider(config);
await TeamAnalytics.provider?.setup(
config,
uniqueId,
controlPlaneProxyInfo,
);
TeamAnalytics.provider = createAnalyticsProvider(config);
await TeamAnalytics.provider?.setup(
config,
uniqueId,
controlPlaneProxyInfo,
);
if (config.provider === "continue-proxy") {
(
TeamAnalytics.provider as ContinueProxyAnalyticsProvider
).controlPlaneClient = controlPlaneClient;
}
if (config.provider === "continue-proxy") {
(
TeamAnalytics.provider as ContinueProxyAnalyticsProvider
).controlPlaneClient = controlPlaneClient;
}
}
static async shutdown() {
if (TeamAnalytics.provider) {
await TeamAnalytics.provider.shutdown();
TeamAnalytics.provider = undefined;
TeamAnalytics.os = undefined;
TeamAnalytics.extensionVersion = undefined;
TeamAnalytics.uniqueId = "NOT_UNIQUE";
}
}
}

View file

@ -1,4 +1,4 @@
import { Analytics } from "@continuedev/config-types";
import { AnalyticsConfig } from "../..";
export interface AnalyticsMetadata {
extensionVersion: string;
@ -13,7 +13,7 @@ export interface ControlPlaneProxyInfo {
export interface IAnalyticsProvider {
capture(event: string, properties: { [key: string]: any }): Promise<void>;
setup(
config: Analytics,
config: AnalyticsConfig,
uniqueId: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void>;

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

@ -1,8 +1,4 @@
import { ConfigJson } from "@continuedev/config-types";
import fetch, { RequestInit, Response } from "node-fetch";
import { IdeSettings, ModelDescription } from "../index.js";
import {
AssistantUnrolled,
ConfigResult,
@ -10,6 +6,11 @@ import {
FullSlug,
SecretResult,
} from "@continuedev/config-yaml";
import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeSettings, ModelDescription } from "../index.js";
import { getControlPlaneEnv } from "./env.js";
export interface ControlPlaneSessionInfo {
@ -32,10 +33,6 @@ export const TRIAL_PROXY_URL =
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
export class ControlPlaneClient {
private static ACCESS_TOKEN_VALID_FOR_MS = 1000 * 60 * 5; // 5 minutes
private lastAccessTokenRefresh = 0;
constructor(
private readonly sessionInfoPromise: Promise<
ControlPlaneSessionInfo | undefined
@ -107,7 +104,7 @@ export class ControlPlaneClient {
}
}
public async listAssistants(): Promise<
public async listAssistants(organizationId: string | null): Promise<
{
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
@ -121,7 +118,11 @@ export class ControlPlaneClient {
}
try {
const resp = await this.request("ide/list-assistants", {
const url = organizationId
? `ide/list-assistants?organizationId=${organizationId}`
: "ide/list-assistants";
const resp = await this.request(url, {
method: "GET",
});
return (await resp.json()) as any;
@ -130,14 +131,38 @@ export class ControlPlaneClient {
}
}
public async listAssistantFullSlugs(): Promise<FullSlug[] | null> {
public async listOrganizations(): Promise<Array<OrganizationDescription>> {
const userId = await this.userId;
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(
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;

View file

@ -1,4 +1,7 @@
import fetch from "node-fetch";
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 +38,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,6 +61,17 @@ const LOCAL_ENV: ControlPlaneEnv = {
APP_URL: "http://localhost:3000/",
};
export async function enableHubContinueDev() {
try {
const resp = await fetch("https://api.continue.dev/features/hub");
const data = (await resp.json()) as any;
if ("enabled" in data && data.enabled === true) {
return true;
}
} catch (e: any) {}
return false;
}
export async function getControlPlaneEnv(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<ControlPlaneEnv> {
@ -70,11 +82,15 @@ export async function getControlPlaneEnv(
export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
): ControlPlaneEnv {
if (fs.existsSync(getStagingEnvironmentDotFilePath())) {
return STAGING_ENV;
}
const env =
ideTestEnvironment === "production"
? "hub"
: ideTestEnvironment === "test"
? "test"
: ideTestEnvironment === "staging"
? "staging"
: ideTestEnvironment === "local"
? "local"
: process.env.CONTROL_PLANE_ENV;

View file

@ -11,14 +11,13 @@ import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import {
setupBestConfig,
setupLocalConfig,
setupLocalConfigAfterFreeTrial,
setupQuickstartConfig,
} from "./config/onboarding";
import { addContextProvider, addModel, deleteModel } from "./config/util";
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 { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
@ -52,18 +51,17 @@ import {
type IndexingProgressUpdate,
} from ".";
import { getControlPlaneEnv } from "./control-plane/env";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
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],
@ -114,16 +108,11 @@ export class Core {
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,12 +125,25 @@ 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,
}),
);
// Codebase Indexer and ContinueServerClient depend on IdeSettings
@ -209,13 +211,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);
// 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);
}
});
on("update/selectTabAutocompleteModel", async (msg) => {
@ -270,10 +283,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();
});
@ -295,7 +306,7 @@ export class Core {
});
on("config/addContextProvider", async (msg) => {
addContextProvider(msg.data);
addContextProvider(msg.data, this.configHandler);
});
on("config/updateSharedConfig", async (msg) => {
@ -305,7 +316,15 @@ export class Core {
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.configHandler.listOrganizations();
});
// Context providers
@ -322,7 +341,7 @@ export class Core {
});
on("context/loadSubmenuItems", async (msg) => {
const config = await this.config();
const { config } = await this.configHandler.loadConfig();
if (!config) {
return [];
}
@ -339,17 +358,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 [];
}
@ -385,10 +413,36 @@ 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) {
// A specific error where we're forcing the presence of embeddings provider on the config
// But Jetbrains doesn't support transformers JS
// So if a context provider needs it it will throw this error when the file isn't found
if (e.message.includes("all-MiniLM-L6-v2")) {
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-types/embeddings",
);
}
});
}
}
if (!knownError) {
void this.ide.showToast(
"error",
`Error getting context items from ${name}: ${e}`,
);
}
return [];
}
});
@ -401,7 +455,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,
};
});
@ -689,6 +744,8 @@ export class Core {
llm,
data.input,
data.language,
false,
undefined,
)) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
@ -720,10 +777,6 @@ export class Core {
editConfigJsonCallback = setupQuickstartConfig;
break;
case "LocalAfterFreeTrial":
editConfigJsonCallback = setupLocalConfigAfterFreeTrial;
break;
case "Best":
editConfigJsonCallback = setupBestConfig;
break;
@ -827,12 +880,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);
}
});
@ -878,11 +937,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 };
});
@ -920,16 +991,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 };
});
}

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 = {

77
core/index.d.ts vendored
View file

@ -1,6 +1,6 @@
import { ModelRole } from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
interface Window {
ide?: "vscode";
@ -43,13 +43,13 @@ export interface IndexingProgressUpdate {
desc: string;
shouldClearIndexes?: boolean;
status:
| "loading"
| "indexing"
| "done"
| "failed"
| "paused"
| "disabled"
| "cancelled";
| "loading"
| "indexing"
| "done"
| "failed"
| "paused"
| "disabled"
| "cancelled";
debugInfo?: string;
}
@ -94,6 +94,8 @@ export interface ILLM extends LLMOptions {
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
deployment?: string;
apiVersion?: string;
@ -480,6 +482,8 @@ export interface LLMOptions {
aiGatewaySlug?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
useLegacyCompletionsEndpoint?: boolean;
@ -503,9 +507,6 @@ export interface LLMOptions {
// AWS and GCP Options
region?: string;
// GCP Options
capabilities?: ModelCapability;
// GCP and Watsonx Options
projectId?: string;
@ -599,7 +600,7 @@ export interface IdeSettings {
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
continueTestEnvironment: "none" | "production" | "test" | "local";
continueTestEnvironment: "none" | "production" | "staging" | "local";
pauseCodebaseIndexOnStart: boolean;
}
@ -666,12 +667,16 @@ export interface IDE {
getCurrentFile(): Promise<
| undefined
| {
isUntitled: boolean;
path: string;
contents: string;
}
isUntitled: boolean;
path: string;
contents: string;
}
>;
getLastFileSaveTimestamp?(): number;
updateLastFileSaveTimestamp?(): void;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
@ -848,17 +853,18 @@ export interface CustomCommand {
export interface Prediction {
type: "content";
content:
| string
| {
type: "text";
text: string;
}[];
| string
| {
type: "text";
text: string;
}[];
}
export interface ToolExtras {
ide: IDE;
llm: ILLM;
fetch: FetchFunction;
tool: Tool;
}
export interface Tool {
@ -874,6 +880,7 @@ export interface Tool {
wouldLikeTo: string;
readonly: boolean;
uri?: string;
faviconUrl?: string;
}
interface ToolChoice {
@ -905,6 +912,7 @@ export interface BaseCompletionOptions {
export interface ModelCapability {
uploadImage?: boolean;
tools?: boolean;
}
export interface ModelDescription {
@ -921,8 +929,9 @@ export interface ModelDescription {
systemMessage?: string;
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
}
export interface EmbedOptions {
@ -971,6 +980,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 +1008,7 @@ export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
export interface MCPOptions {
transport: TransportOptions;
faviconUrl?: string;
}
export interface ContinueUIConfig {
@ -1012,7 +1027,7 @@ export interface ContextMenuConfig {
fixGrammar?: string;
}
export interface ModelRoles {
export interface ExperimentalModelRoles {
inlineEdit?: string;
applyCodeBlock?: string;
repoMapFileSelection?: string;
@ -1080,7 +1095,7 @@ export type DefaultContextProvider = ContextProviderWithParams & {
export interface ExperimentalConfig {
contextMenuPrompts?: ContextMenuConfig;
modelRoles?: ModelRoles;
modelRoles?: ExperimentalModelRoles;
defaultContext?: DefaultContextProvider[];
promptPath?: string;
@ -1105,7 +1120,7 @@ export interface ExperimentalConfig {
}
export interface AnalyticsConfig {
type: string;
provider: string;
url?: string;
clientKey?: string;
}
@ -1171,9 +1186,9 @@ export interface Config {
embeddingsProvider?: EmbeddingsProviderDescription | ILLM;
/** The model that Continue will use for tab autocompletions. */
tabAutocompleteModel?:
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
/** Options for tab autocomplete */
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
/** UI styles customization */
@ -1264,9 +1279,9 @@ export type PackageDetailsSuccess = PackageDetails & {
export type PackageDocsResult = {
packageInfo: ParsedPackageInfo;
} & (
| { error: string; details?: never }
| { details: PackageDetailsSuccess; error?: never }
);
| { error: string; details?: never }
| { details: PackageDetailsSuccess; error?: never }
);
export interface TerminalOptions {
reuseTerminal?: boolean;

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

@ -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

@ -26,6 +26,8 @@ import {
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import { ConfigResult } from "@continuedev/config-yaml";
import { GlobalContext } from "../../util/GlobalContext";
import {
ArticleWithChunks,
htmlPageToArticleWithChunks,
@ -40,7 +42,6 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import { ConfigResult } from "@continuedev/config-yaml";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -156,7 +157,8 @@ export default class DocsService {
const currentStatus = this.statuses.get(doc.startUrl);
if (currentStatus) {
return currentStatus;
this.handleStatusUpdate(currentStatus);
return;
}
const sharedStatus = {
@ -210,11 +212,7 @@ 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) {
this.abort(startUrl);
@ -276,10 +274,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) {
@ -365,13 +359,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 +376,10 @@ 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)) {
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 +390,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 +567,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 +596,7 @@ export default class DocsService {
});
void this.ide.showToast("info", `Failed to index ${startUrl}`);
this.docsIndexingQueue.delete(startUrl);
markFailedInGlobalContext();
return;
}
@ -569,7 +614,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 +638,6 @@ export default class DocsService {
favicon,
});
this.docsIndexingQueue.delete(startUrl);
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
...fixedStatus,
description: "Complete",
@ -610,23 +650,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);
}
@ -871,7 +917,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);
@ -908,22 +954,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);
}

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

@ -26,7 +26,7 @@ export class DefaultCrawler {
});
if (!resp.ok) {
const text = await resp.text();
throw new Error(`Failed to crawl site: ${text}`);
throw new Error(`Failed to crawl site (${resp.status}): ${text}`);
}
const json = (await resp.json()) as PageData[];
return json;

View file

@ -152,11 +152,15 @@ describe("DocsCrawler", () => {
);
commonDocsSites.forEach((url) => {
test(`Default crawler common site: ${url}`, async () => {
const { pages, crawler } = await runCrawl(url);
expect(pages.length).toBeGreaterThanOrEqual(1);
expect(crawler).toEqual("default");
});
test(
`Default crawler common site: ${url}`,
async () => {
const { pages, crawler } = await runCrawl(url);
expect(pages.length).toBeGreaterThanOrEqual(1);
expect(crawler).toEqual("default");
},
TIMEOUT_MS,
);
});
});

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

@ -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[] = [
@ -68,6 +74,7 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"vertexai",
"azure",
"scaleway",
"nebius",
];
const MODEL_SUPPORTS_IMAGES: string[] = [
@ -87,12 +94,15 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"llama3.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 +267,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,4 +1,9 @@
import { ChatHistoryItem, ChatMessage, MessagePart } from "../";
import {
ChatHistoryItem,
ChatMessage,
MessagePart,
ModelDescription,
} from "../";
import { normalizeToMessageParts } from "../util/messageContent";
import { modelSupportsTools } from "./autodetect";
@ -67,15 +72,18 @@ 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))) {
if (
CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) =>
modelDescription.model.includes(family),
)
) {
systemMessage = SYSTEM_MESSAGE;
}
if (useTools && modelSupportsTools(model, provider)) {
if (useTools && modelSupportsTools(modelDescription)) {
if (systemMessage) {
systemMessage += "\n\n";
}
@ -89,8 +97,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 +105,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

@ -56,6 +56,7 @@ import {
toCompleteBody,
toFimBody,
} from "./openaiTypeConverters.js";
import { ModelRole } from "@continuedev/config-yaml";
export abstract class BaseLLM implements ILLM {
static providerName: string;
@ -121,6 +122,7 @@ export abstract class BaseLLM implements ILLM {
apiBase?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
deployment?: string;
apiVersion?: string;
@ -191,7 +193,8 @@ 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;
@ -208,6 +211,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;
@ -957,7 +961,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> = {
@ -178,6 +180,15 @@ function testLLM(
}
describe("LLM", () => {
if (process.env.IGNORE_API_KEY_TESTS === "true") {
test("Skipping API key tests", () => {
console.log(
"Skipping API key tests due to IGNORE_API_KEY_TESTS being set",
);
});
return;
}
testLLM(
new Anthropic({
model: "claude-3-5-sonnet-latest",
@ -213,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

@ -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

@ -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;
}
}

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

@ -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"}'

View file

@ -57,30 +57,34 @@ export function toChatMessage(
}
return msg;
} else {
if (typeof message.content === "string") {
return {
role: "user",
content: message.content ?? " ", // LM Studio (and other providers) don't accept empty content
};
}
// If no multi-media is in the message, just send as text
// for compatibility with OpenAI-"compatible" servers
// that don't support multi-media format
return {
role: "user",
content:
typeof message.content === "string"
? message.content || " " // LM Studio (and other providers) don't accept empty content
: // If no multi-media is in the message, just send as text
// for compatibility with OpenAI-"compatible" servers
// that don't support multi-media format
message.content.some((item) => item.type !== "text")
? message.content
.map((item) => (item as TextMessagePart).text)
.join("") || " "
: message.content.map((part) => {
if (part.type === "imageUrl") {
return {
type: "image_url" as const,
image_url: {
url: part.imageUrl.url,
detail: "auto" as const,
},
};
}
return part;
}),
content: !message.content.some((item) => item.type !== "text")
? message.content
.map((item) => (item as TextMessagePart).text)
.join("") || " "
: message.content.map((part) => {
if (part.type === "imageUrl") {
return {
type: "image_url" as const,
image_url: {
url: part.imageUrl.url,
detail: "auto" as const,
},
};
}
return part;
}),
};
}
}

View file

@ -175,7 +175,7 @@ describe.skip("Chat Templates", () => {
];
const prompt = deepseekTemplateMessages(messages);
const expectedPrompt =
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n### Instruction:\nWhat is polymorphism in OOP?\n### Response:\nExplanation of polymorphism.<|EOT|>\n";
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and your role is to assist with questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will not answer.\n### Instruction:\nWhat is polymorphism in OOP?\n### Response:\nExplanation of polymorphism.<|EOT|>\n";
expect(prompt).toBe(expectedPrompt);
});
});

View file

@ -156,7 +156,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
let system: string | null = null;
prompt +=
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n";
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and your role is to assist with questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will not answer.\n";
if (msgs[0].role === "system") {
system = renderChatMessage(msgs.shift()!);
}

View file

@ -129,7 +129,7 @@ Sure! Here's the code you requested:
`;
const deepseekEditPrompt = `### System Prompt
You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.
You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and your role is to assist with questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will not answer.
### Instruction:
Rewrite the code to satisfy this request: "{{{userInput}}}"

View file

@ -2,6 +2,11 @@ export const PROVIDER_TOOL_SUPPORT: Record<
string,
(model: string) => boolean | undefined
> = {
"continue-proxy": (model) => {
return ["claude-3-5", "claude-3.5", "gpt-4", "o3", "gemini"].some((part) =>
model.toLowerCase().startsWith(part),
);
},
anthropic: (model) => {
if (
["claude-3-5", "claude-3.5"].some((part) =>
@ -13,7 +18,10 @@ export const PROVIDER_TOOL_SUPPORT: Record<
},
openai: (model) => {
// https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
if (model.toLowerCase().startsWith("gpt-4")) {
if (
model.toLowerCase().startsWith("gpt-4") ||
model.toLowerCase().startsWith("o3")
) {
return true;
}
},

65
core/package-lock.json generated
View file

@ -13,11 +13,11 @@
"@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.31",
"@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",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@ -3038,9 +3038,9 @@
}
},
"node_modules/@continuedev/config-yaml": {
"version": "1.0.23",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.23.tgz",
"integrity": "sha512-F2Hwc85iCwAHJuwJALOsmZIBeHdF+87mS0YT7dlC6QiE+zAhZKUHcLQ/nTt9bJuhyVyufpb9LApkp40UdGsaWw==",
"version": "1.0.31",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.31.tgz",
"integrity": "sha512-HNj+z7UTTARgsJTI0A1buM09fS4HoWVnn6Hbl6kJ2tZmOOm1OgogbcKP68AzHb4fy5H18MWnKS7XuseZpHFzHQ==",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
@ -4218,13 +4218,34 @@
]
},
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.0.3.tgz",
"integrity": "sha512-2as3cX/VJ0YBHGmdv3GFyTpoM8q2gqE98zh3Vf1NwnsSY0h3mvoO07MUzfygCKkWsFjcZm4otIiqD6Xh7kiSBQ==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.5.0.tgz",
"integrity": "sha512-IJ+5iVVs8FCumIHxWqpwgkwOzyhtHVKy45s6Ug7Dv0MfRpaYisH8QQ87rIWeWdOzlk8sfhitZ7HCyQZk7d6b8w==",
"dependencies": {
"content-type": "^1.0.5",
"eventsource": "^3.0.2",
"raw-body": "^3.0.0",
"zod": "^3.23.8"
"zod": "^3.23.8",
"zod-to-json-schema": "^3.24.1"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@modelcontextprotocol/sdk/node_modules/zod": {
"version": "3.24.1",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz",
"integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema": {
"version": "3.24.1",
"resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.1.tgz",
"integrity": "sha512-3h08nf3Vw3Wl3PK+q3ow/lIil81IT2Oa7YpQyUUDsEWbXveMesdfK1xBd2RhCkynwZndAxixji/7SYJJowr62w==",
"peerDependencies": {
"zod": "^3.24.1"
}
},
"node_modules/@mozilla/readability": {
@ -8313,6 +8334,25 @@
"node": ">=0.8.x"
}
},
"node_modules/eventsource": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.5.tgz",
"integrity": "sha512-LT/5J605bx5SNyE+ITBDiM3FxffBiq9un7Vx0EwMDM3vg8sWKx/tO2zC+LMqZ+smAM0F2hblaDZUVZF0te2pSw==",
"dependencies": {
"eventsource-parser": "^3.0.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/eventsource-parser": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.0.tgz",
"integrity": "sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/execa": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",
@ -15520,9 +15560,10 @@
}
},
"node_modules/undici": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.0.tgz",
"integrity": "sha512-BUgJXc752Kou3oOIuU1i+yZZypyZRqNPW0vqoMPl8VaoalSfeR0D8/t4iAS3yirs79SSMTxTag+ZC86uswv+Cw==",
"version": "6.21.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
"integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}

View file

@ -46,11 +46,11 @@
"@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.31",
"@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",
"@typescript-eslint/eslint-plugin": "^7.8.0",

View file

@ -25,15 +25,20 @@ async function renderPromptV1(
) {
const helpers = getContextProviderHelpers(context);
// A few context providers that don't need to be in config.json to work in .prompt files
const diff = await context.ide.getDiff(true);
const currentFile = await context.ide.getCurrentFile();
const inputData: Record<string, string> = {
diff: diff.join("\n"),
input: userInput,
};
if (currentFile) {
inputData.currentFile = currentFile.path;
// A few context providers that don't need to be in config.json to work in .prompt files
if (helpers?.find((helper) => helper[0] === "diff")) {
const diff = await context.ide.getDiff(true);
inputData.diff = diff.join("\n");
}
if (helpers?.find((helper) => helper[0] === "currentFile")) {
const currentFile = await context.ide.getCurrentFile();
if (currentFile) {
inputData.currentFile = currentFile.path;
}
}
return renderTemplatedString(

View file

@ -1,4 +1,10 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { AutocompleteInput } from "../autocomplete/util/types";
import { ProfileDescription } from "../config/ConfigHandler";
import { OrganizationDescription } from "../config/ProfileLifecycleManager";
import { SharedConfigSchema } from "../config/sharedConfig";
import type {
BrowserSerializedContinueConfig,
ChatMessage,
@ -8,11 +14,11 @@ import type {
ContextSubmenuItem,
DiffLine,
DocsIndexingDetails,
ExperimentalModelRoles,
FileSymbolMap,
IdeSettings,
LLMFullCompletionOptions,
ModelDescription,
ModelRoles,
PromptLog,
RangeInFile,
SerializedContinueConfig,
@ -21,16 +27,8 @@ import type {
SiteIndexingConfig,
ToolCall,
} from "../";
import { AutocompleteInput } from "../autocomplete/util/types";
import { ProfileDescription } from "../config/ConfigHandler";
import { SharedConfigSchema } from "../config/sharedConfig";
export type OnboardingModes =
| "Local"
| "Best"
| "Custom"
| "Quickstart"
| "LocalAfterFreeTrial";
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
export interface ListHistoryOptions {
offset?: number;
@ -54,7 +52,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"config/addModel": [
{
model: SerializedContinueConfig["models"][number];
role?: keyof ModelRoles;
role?: keyof ExperimentalModelRoles;
},
void,
];
@ -64,13 +62,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
undefined,
{
result: ConfigResult<BrowserSerializedContinueConfig>;
profileId: string;
profileId: string | null;
},
];
"config/deleteModel": [{ title: string }, void];
"config/addContextProvider": [ContextProviderWithParams, void];
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
"config/listProfiles": [undefined, ProfileDescription[]];
"config/listProfiles": [undefined, ProfileDescription[] | null];
"config/openProfile": [{ profileId: string | undefined }, void];
"config/updateSharedConfig": [SharedConfigSchema, void];
"context/getContextItems": [
@ -186,13 +184,12 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"docs/getDetails": [{ startUrl: string }, DocsIndexingDetails];
addAutocompleteModel: [{ model: ModelDescription }, void];
"profiles/switch": [{ id: string }, undefined];
"auth/getAuthUrl": [undefined, { url: string }];
"auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }];
"tools/call": [
{ toolCall: ToolCall; selectedModelTitle: string },
{ contextItems: ContextItem[] },
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
"controlPlane/listOrganizations": [undefined, OrganizationDescription[]];
};

View file

@ -4,8 +4,12 @@ import { ToCoreFromIdeOrWebviewProtocol } from "./core.js";
import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & {
didChangeSelectedProfile: [{ id: string }, void];
didChangeSelectedProfile: [{ id: string | null }, void];
didChangeSelectedOrg: [{ id: string | null }, void];
};
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & {
didChangeAvailableProfiles: [{ profiles: ProfileDescription[] }, void];
didChangeAvailableProfiles: [
{ profiles: ProfileDescription[]; selectedProfileId: string | null },
void,
];
};

View file

@ -79,10 +79,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];
/**
* @deprecated Use navigateTo with a path instead.
*/
viewHistory: [undefined, void];
focusContinueSessionId: [{ sessionId: string | undefined }, void];
newSession: [undefined, void];
setTheme: [{ theme: any }, void];

View file

@ -21,7 +21,7 @@ export interface IMessenger<
ToProtocol extends IProtocol,
FromProtocol extends IProtocol,
> {
onError(handler: (error: Error) => void): void;
onError(handler: (message: Message, error: Error) => void): void;
send<T extends keyof FromProtocol>(
messageType: T,
data: FromProtocol[T][0],
@ -64,9 +64,9 @@ export class InProcessMessenger<
(message: Message) => any
>();
protected _onErrorHandlers: ((error: Error) => void)[] = [];
protected _onErrorHandlers: ((message: Message, error: Error) => void)[] = [];
onError(handler: (error: Error) => void) {
onError(handler: (message: Message, error: Error) => void) {
this._onErrorHandlers.push(handler);
}

View file

@ -57,10 +57,11 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
//
"completeOnboarding",
"addAutocompleteModel",
"profiles/switch",
"didChangeSelectedProfile",
"didChangeSelectedOrg",
"tools/call",
"controlPlane/openUrl",
"controlPlane/listOrganizations",
];
// Message types to pass through from core to webview
@ -80,7 +81,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"setTTSActive",
"getWebviewHistoryLength",
"getCurrentSessionId",
"signInToControlPlane",
"openDialogMessage",
"docs/suggestions",
];

View file

@ -12,7 +12,7 @@ export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [
{
result: ConfigResult<BrowserSerializedContinueConfig>;
profileId: string;
profileId: string | null;
},
void,
];
@ -37,7 +37,6 @@ export type ToWebviewFromIdeOrCoreProtocol = {
setTTSActive: [boolean, void];
getWebviewHistoryLength: [undefined, number];
getCurrentSessionId: [undefined, string];
signInToControlPlane: [undefined, void];
openDialogMessage: ["account", void];
"docs/suggestions": [PackageDocsResult[], void];
"jetbrains/setColors": [Record<string, string>, void];
};

View file

@ -18,7 +18,7 @@ export const testConfigHandler = new ConfigHandler(
testIde,
ideSettingsPromise,
async (text) => {},
testControlPlaneClient,
Promise.resolve(undefined),
);
export const testLLM = new Mock({

View file

@ -1,4 +1,4 @@
import { ContextItem, ToolExtras } from "..";
import { ContextItem, Tool, ToolExtras } from "..";
import { MCPManagerSingleton } from "../context/mcp";
import { BuiltInToolNames } from "./builtIn";
@ -86,13 +86,18 @@ async function callToolFromUri(
throw new Error(`Failed to call tool: ${toolName}`);
}
return (response.content as any).map((item: any) => {
return (response.content as any).map((item: any): ContextItem => {
if (item.type !== "text") {
throw new Error(
`Continue received item of type "${item.type}" from MCP tool, but currently only supports "text".`,
);
}
return { name: toolName, description: toolName, content: item.text };
return {
name: extras.tool.displayTitle,
description: "Tool output",
content: item.text,
icon: extras.tool.faviconUrl,
};
});
default:
@ -101,10 +106,12 @@ async function callToolFromUri(
}
export async function callTool(
uri: string,
tool: Tool,
args: any,
extras: ToolExtras,
): Promise<ContextItem[]> {
const uri = tool.uri ?? tool.function.name;
switch (uri) {
case BuiltInToolNames.ReadFile:
return await readFileImpl(args, extras);

View file

@ -1,4 +1,4 @@
import { getUriPathBasename } from "../../util/uri";
import { getUriDescription } from "../../util/uri";
import { ToolImpl } from ".";
@ -9,13 +9,16 @@ export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
return [];
}
const basename = getUriPathBasename(result.path);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
result.path,
await extras.ide.getWorkspaceDirs(),
);
return [
{
name: "Current file",
description: basename,
content: `\`\`\`${basename}\n${result.contents}\n\`\`\``,
name: `Current file: ${baseName}`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``,
uri: {
type: "file",
value: result.path,

View file

@ -5,7 +5,7 @@ import { ToolImpl } from ".";
export const viewRepoMapImpl: ToolImpl = async (args, extras) => {
const repoMap = await generateRepoMap(extras.llm, extras.ide, {
outputRelativeUriPaths: true,
includeSignatures: false,
includeSignatures: true,
});
return [
{

View file

@ -7,11 +7,18 @@ import {
} from "../config/sharedConfig";
import { getGlobalContextFilePath } from "./paths";
import { SiteIndexingConfig } from "..";
export type GlobalContextType = {
indexingPaused: boolean;
selectedTabAutocompleteModel: string;
lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string };
lastSelectedProfileForWorkspace: {
[workspaceIdentifier: string]: string | null;
};
lastSelectedOrgIdForWorkspace: {
[workspaceIdentifier: string]: string | null;
};
/**
* This is needed to handle the case where a JetBrains user has created
* docs embeddings using one provider, and then updates to a new provider.
@ -23,6 +30,7 @@ export type GlobalContextType = {
showConfigUpdateToast: boolean;
isSupportedLanceDbCpuTarget: boolean;
sharedConfig: SharedConfigSchema;
failedDocs: SiteIndexingConfig[];
};
/**

View file

@ -34,10 +34,11 @@ export async function resolveRelativePathInDir(
If no meaninful path match just concatenates to first dir's uri
*/
export async function inferResolvedUriFromRelativePath(
relativePath: string,
_relativePath: string,
ide: IDE,
dirCandidates?: string[],
): Promise<string> {
const relativePath = _relativePath.trim().replaceAll("\\", "/");
const dirs = dirCandidates ?? (await ide.getWorkspaceDirs());
if (dirs.length === 0) {
@ -51,7 +52,7 @@ export async function inferResolvedUriFromRelativePath(
suffixes.push(segments.slice(i).join("/"));
}
// For each suffix, try to find a unique matching directory
// For each suffix, try to find a unique matching dir/file
for (const suffix of suffixes) {
const uris = dirs.map((dir) => ({
dir,
@ -78,6 +79,13 @@ export async function inferResolvedUriFromRelativePath(
}
}
// Sometimes the model will decide to only output the base name or small number of path parts
// in which case we shouldn't create a new file if it matches the current file
const activeFile = await ide.getCurrentFile();
if (activeFile && activeFile.path.endsWith(relativePath)) {
return activeFile.path;
}
// If no unique match found, use the first directory
return joinPathsToUri(dirs[0], relativePath);
}

View file

@ -207,7 +207,7 @@ World
it("should handle strings with only whitespace", () => {
const result = dedent`
`;
expect(result).toBe("");
});
@ -249,9 +249,9 @@ World
it("should handle a string with only one non-empty line", () => {
const result = dedent`
Hello World!
`;
expect(result).toBe("Hello World!");
});
@ -373,11 +373,16 @@ describe("getMarkdownLanguageTagForFile", () => {
expect(getMarkdownLanguageTagForFile("test.py")).toBe("python");
expect(getMarkdownLanguageTagForFile("test.tsx")).toBe("tsx");
expect(getMarkdownLanguageTagForFile("test.java")).toBe("java");
expect(getMarkdownLanguageTagForFile("test.class")).toBe("java");
expect(getMarkdownLanguageTagForFile("test.md")).toBe("markdown");
expect(getMarkdownLanguageTagForFile("test.sh")).toBe("shell");
expect(getMarkdownLanguageTagForFile("test.sql")).toBe("sql");
});
it("should sanitize ranges from the extension", () => {
expect(getMarkdownLanguageTagForFile("test.java (1-5)")).toBe("java");
});
it("should return the extension if not in the known list", () => {
expect(getMarkdownLanguageTagForFile("file.unknownext")).toBe("unknownext");
});

View file

@ -74,6 +74,7 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
tsx: "tsx",
ts: "typescript",
java: "java",
class:"java", //.class files decompile to Java
go: "go",
rb: "ruby",
rs: "rust",
@ -96,17 +97,28 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
ps1: "powershell",
};
const ext = filepath.split(".").pop();
const ext = sanitizeExtension(filepath.split(".").pop());
return ext ? (extToLangMap[ext] ?? ext) : "";
}
function sanitizeExtension(ext?: string): string|undefined {
if (ext) {
//ignore ranges in extension eg. "java (11-23)"
const match = ext.match(/^(\S+)\s*(\(.*\))?$/);
if (match) {
ext = match[1];
}
}
return ext;
}
export function copyOf(obj: any): any {
if (obj === null || obj === undefined) {
return obj;
}
return JSON.parse(JSON.stringify(obj));
}
``;
export function deduplicateArray<T>(
array: T[],

View file

@ -11,7 +11,7 @@ export async function isOllamaInstalled(): Promise<boolean> {
});
}
export async function startLocalOllama(ide: IDE): Promise<void> {
export async function startLocalOllama(ide: IDE): Promise<any> {
let startCommand: string | undefined;
switch (process.platform) {
@ -20,16 +20,16 @@ export async function startLocalOllama(ide: IDE): Promise<void> {
break;
case "win32"://Windows
startCommand = `& "ollama app.exe"\n`;
startCommand = "& \"ollama app.exe\"\n";
break;
default: //Linux...
const start_script_path = path.resolve(__dirname, './start_ollama.sh');
const start_script_path = path.resolve(__dirname, "./start_ollama.sh");
if (await ide.fileExists(`file:/${start_script_path}`)) {
startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
console.log(`Ollama Linux startup script at : ${start_script_path}`);
} else {
ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`)
return ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`)
}
}
if (startCommand) {

View file

@ -18,6 +18,10 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
useImports: true,
transform: true,
showWhateverWeHaveAtXMs: 300,
experimental_includeClipboard: true,
experimental_includeRecentlyVisitedRanges: true,
experimental_includeRecentlyEditedRanges: true,
experimental_includeDiff: true,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;

View file

@ -377,6 +377,10 @@ export function getEsbuildBinaryPath(): string {
return path.join(getContinueUtilsPath(), "esbuild");
}
export function getStagingEnvironmentDotFilePath(): string {
return path.join(getContinueGlobalPath(), ".staging");
}
export function setupInitialDotContinueDirectory() {
const devDataTypes = [
"chat",

View file

@ -93,6 +93,7 @@ export const supportedLanguages: { [key: string]: LanguageName } = {
htm: LanguageName.HTML,
java: LanguageName.JAVA,
lua: LanguageName.LUA,
luau: LanguageName.LUA,
ocaml: LanguageName.OCAML,
ml: LanguageName.OCAML,
mli: LanguageName.OCAML,

View file

@ -177,3 +177,19 @@ export function getLastNPathParts(filepath: string, n: number): string {
}
return filepath.split(/[\\/]/).slice(-n).join("/");
}
export function getUriDescription(uri: string, dirUriCandidates: string[]) {
const { relativePathOrBasename, foundInDir } = findUriInDirs(
uri,
dirUriCandidates,
);
const baseName = getUriPathBasename(uri);
const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2);
return {
uri,
relativePathOrBasename,
foundInDir,
last2Parts,
baseName,
};
}

View file

@ -7,7 +7,7 @@ sidebar_position: 3
## Slash commands
Slash commands can be combined with additional instructions, including [context providers](chat/context-selection.md) or [highlighted code](chat/context-selection.md).
Slash commands can be combined with additional instructions, including [context providers](../customize/context-providers.mdx) or [highlighted code](../edit/context-selection#highlighted-code).
For example, with the “/edit” slash command you should describe the edit that you want the LLM to perform.

View file

@ -7,6 +7,6 @@ sidebar_position: 4
While many Actions are based on templated prompts and can be customized with .prompt files, there are a number that execute more complex code under the hood.
Actions that generate inline diffs, like “/edit”, “/comment”, or right click actions, use the same prompt and response processing logic as [Edit](edit/how-it-works.md).
Actions that generate inline diffs, like “/edit”, “/comment”, or right click actions, use the same prompt and response processing logic as [Edit](../edit/how-it-works.md).
To learn how other slash commands work, see the full reference [here](../customize/slash-commands.md).
To learn how other slash commands work, see the full reference [here](../customize/slash-commands.mdx).

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