Merge tag 'refs/tags/v0.9.269-vscode' into fix_recently_edited_tracker_2

This commit is contained in:
ferenci84 2025-02-21 18:10:16 +01:00
commit 03ead03015
354 changed files with 11164 additions and 6848 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

@ -4,22 +4,10 @@ on:
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:
install-root:
@ -290,6 +278,8 @@ jobs:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest

View file

@ -4,6 +4,13 @@ on:
release:
types: [prereleased]
workflow_dispatch:
inputs:
publish_build:
description: "Whether or not to publish the built extension to the VS Code marketplace"
required: true
default: false
jobs:
check_release_name:
runs-on: ubuntu-latest
@ -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:

63
.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
@ -186,6 +184,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

@ -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.23",
"@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

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

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

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

@ -27,7 +27,7 @@ import { localPathToUri } from "../util/pathToUri.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
ONBOARDING_LOCAL_MODEL_TITLE,
LOCAL_ONBOARDING_PROVIDER_TITLE,
} from "./onboarding.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@ -47,55 +47,83 @@ 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);
});
});
}
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,
);
}
@ -112,74 +140,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.iconUrl,
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;
@ -204,78 +245,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);
@ -312,16 +356,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);
}
}
@ -338,33 +391,54 @@ export class ConfigHandler {
this.updateListeners.push(listener);
}
async reloadConfig(additionalContextProviders: IContextProvider[] = []) {
// TODO: this isn't right, there are two different senses in which you want to "reload"
// TODO: this isn't right, there are two different senses in which you want to "reload"
async reloadConfig() {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
const { config, errors, configLoadInterrupted } =
await this.currentProfile.reloadConfig(additionalContextProviders);
await this.currentProfile.reloadConfig(this.additionalContextProviders);
if (config) {
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
}
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
return { config, errors };
return { config, errors, configLoadInterrupted };
}
getSerializedConfig(): Promise<
async getSerializedConfig(): Promise<
ConfigResult<BrowserSerializedContinueConfig>
> {
return this.currentProfile.getSerializedConfig(
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
return await this.currentProfile.getSerializedConfig(
this.additionalContextProviders,
);
}
listProfiles(): ProfileDescription[] {
return this.profiles.map((p) => p.profileDescription);
listProfiles(): ProfileDescription[] | null {
return this.profiles?.map((p) => p.profileDescription) ?? null;
}
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
return await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
@ -374,7 +448,7 @@ export class ConfigHandler {
const { config } = await this.loadConfig();
const model = config?.models.find((m) => m.title === title);
if (!model) {
if (title === ONBOARDING_LOCAL_MODEL_TITLE) {
if (title === LOCAL_ONBOARDING_PROVIDER_TITLE) {
// Special case, make calls to Ollama before we have it in the config
const ollama = new Ollama({
model: LOCAL_ONBOARDING_CHAT_MODEL,
@ -392,6 +466,6 @@ export class ConfigHandler {
registerCustomContextProvider(contextProvider: IContextProvider) {
this.additionalContextProviders.push(contextProvider);
void this.reloadConfig(this.additionalContextProviders);
void this.reloadConfig();
}
}

View file

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

View file

@ -5,20 +5,6 @@ import {
SlashCommandDescription,
} from "../";
export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = {
model: "claude-3-5-sonnet-latest",
provider: "anthropic",
apiKey: "",
title: "Claude 3.5 Sonnet",
};
export const DEFAULT_AUTOCOMPLETE_MODEL_CONFIG: ModelDescription = {
title: "Codestral",
provider: "mistral",
model: "codestral-latest",
apiKey: "",
};
export const FREE_TRIAL_MODELS: ModelDescription[] = [
{
title: "Claude 3.5 Sonnet (Free Trial)",
@ -93,15 +79,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,5 +1,4 @@
import { ConfigResult } from "@continuedev/config-yaml";
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";

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,

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

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

@ -104,7 +104,7 @@ export class ControlPlaneClient {
}
}
public async listAssistants(organizationId?: string): Promise<
public async listAssistants(organizationId: string | null): Promise<
{
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
@ -132,38 +132,37 @@ export class ControlPlaneClient {
}
public async listOrganizations(): Promise<Array<OrganizationDescription>> {
return [
{
id: "1",
iconUrl:
"https://cdn.prod.website-files.com/663e06c56841363663ffbbcf/663e1b9fb023f0b622ad3608_log-text.svg",
name: "Continue",
},
];
// const userId = await this.userId;
// if (!userId) {
// return [];
// }
const userId = await this.userId;
// try {
// const resp = await this.request("ide/list-organizations", {
// method: "GET",
// });
// const { organizations } = (await resp.json()) as any;
// return organizations;
// } catch (e) {
// return [];
// }
if (!userId) {
return [];
}
try {
const resp = await this.request("ide/list-organizations", {
method: "GET",
});
const { organizations } = (await resp.json()) as any;
return organizations;
} catch (e) {
return [];
}
}
public async listAssistantFullSlugs(): Promise<FullSlug[] | null> {
public async listAssistantFullSlugs(
organizationId: string | null,
): Promise<FullSlug[] | null> {
const userId = await this.userId;
if (!userId) {
return null;
}
const url = organizationId
? `ide/list-assistant-full-slugs?organizationId=${organizationId}`
: "ide/list-assistant-full-slugs";
try {
const resp = await this.request("ide/list-assistant-full-slugs", {
const resp = await this.request(url, {
method: "GET",
});
const { fullSlugs } = (await resp.json()) as any;

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,12 @@ 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";
@ -53,17 +51,17 @@ import {
type IndexingProgressUpdate,
} from ".";
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,17 @@ 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,
});
});
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 +203,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 +275,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 +298,7 @@ export class Core {
});
on("config/addContextProvider", async (msg) => {
addContextProvider(msg.data);
addContextProvider(msg.data, this.configHandler);
});
on("config/updateSharedConfig", async (msg) => {
@ -305,11 +308,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.controlPlaneClient.listOrganizations();
return await this.configHandler.listOrganizations();
});
// Context providers
@ -326,7 +333,7 @@ export class Core {
});
on("context/loadSubmenuItems", async (msg) => {
const config = await this.config();
const { config } = await this.configHandler.loadConfig();
if (!config) {
return [];
}
@ -343,17 +350,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 [];
}
@ -389,10 +405,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 [];
}
});
@ -405,7 +447,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,
};
});
@ -693,6 +736,8 @@ export class Core {
llm,
data.input,
data.language,
false,
undefined,
)) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
@ -724,10 +769,6 @@ export class Core {
editConfigJsonCallback = setupQuickstartConfig;
break;
case "LocalAfterFreeTrial":
editConfigJsonCallback = setupLocalConfigAfterFreeTrial;
break;
case "Best":
editConfigJsonCallback = setupBestConfig;
break;
@ -831,12 +872,18 @@ export class Core {
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
}
});
on("files/deleted", async ({ data }) => {
if (data?.uris?.length) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
}
});
@ -882,11 +929,23 @@ export class Core {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
});
on("didChangeSelectedOrg", (msg) => {
void this.configHandler.setSelectedOrgId(msg.data.id);
void this.configHandler.reloadConfig();
void this.configHandler.loadAssistantsForSelectedOrg();
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
await this.configHandler.updateControlPlaneSessionInfo(
msg.data.sessionInfo,
);
});
on("auth/getAuthUrl", async (msg) => {
const url = await getAuthUrlForTokenPage(ideSettingsPromise);
const url = await getAuthUrlForTokenPage(
ideSettingsPromise,
msg.data.useOnboarding,
);
return { url };
});
@ -924,16 +983,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 = {

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

@ -353,6 +353,11 @@ 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/",
},
};
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> = {
@ -222,4 +224,25 @@ describe("LLM", () => {
}),
{ testFim: true, skip: false },
);
testLLM(
new Azure({
apiKey: process.env.AZURE_OPENAI_API_KEY,
model: "gpt-4o",
apiVersion: "2024-05-01-preview",
apiBase: "https://continue-azure-openai-instance.openai.azure.com",
deployment: "azure-openai-deployment",
apiType: "azure-openai",
}),
{ testFim: false, skip: false, timeout: 20000 },
);
testLLM(
new Azure({
apiKey: process.env.AZURE_FOUNDRY_API_KEY,
model: "codestral-latest",
apiBase:
"https://codestral-2501-continue-testing.eastus.models.ai.azure.com",
apiType: "azure-foundry",
}),
{ testFim: false, skip: false, timeout: 20000 },
);
});

View file

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

@ -14,11 +14,11 @@ import type {
ContextSubmenuItem,
DiffLine,
DocsIndexingDetails,
ExperimentalModelRoles,
FileSymbolMap,
IdeSettings,
LLMFullCompletionOptions,
ModelDescription,
ModelRoles,
PromptLog,
RangeInFile,
SerializedContinueConfig,
@ -28,12 +28,7 @@ import type {
ToolCall,
} from "../";
export type OnboardingModes =
| "Local"
| "Best"
| "Custom"
| "Quickstart"
| "LocalAfterFreeTrial";
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
export interface ListHistoryOptions {
offset?: number;
@ -57,7 +52,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"config/addModel": [
{
model: SerializedContinueConfig["models"][number];
role?: keyof ModelRoles;
role?: keyof ExperimentalModelRoles;
},
void,
];
@ -67,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": [
@ -189,14 +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,8 +57,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
//
"completeOnboarding",
"addAutocompleteModel",
"profiles/switch",
"didChangeSelectedProfile",
"didChangeSelectedOrg",
"tools/call",
"controlPlane/openUrl",
"controlPlane/listOrganizations",
@ -81,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

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

View file

@ -7,7 +7,7 @@ sidebar_position: 5
## Built-in slash commands
Continue has a large library of built-in slash commands, but when you first install we only display the most commonly used ones, like “/edit”, “/comment”, and “/share”. To add more actions, you can open [config.json](../reference.md) and add them to the `slashCommands` array.
Continue has a large library of built-in slash commands, but when you first install we only display the most commonly used ones, like “/edit”, “/comment”, and “/share”. To add more actions, you can open [config.json](../json-reference.md) and add them to the `slashCommands` array.
## Custom slash commands
@ -18,11 +18,6 @@ There are two ways to add custom slash commands:
### Custom Slash Commands with `config.ts`
<!-- TODO: We need a config.ts reference -->
<!-- :::tip[config.ts]
Before adding a custom slash command, we recommend reading the [introduction to `config.ts`](../customize/deep-dives/ways-to-configure.md).
::: -->
If you want to go a step further than writing custom commands with natural language, you can write a custom function that returns the response. This requires using `config.ts` instead of `config.json`.
To do this, push a new `SlashCommand` object to the `slashCommands` list. This object contains "name", the name that you will type to invoke the slash command, "description", the description seen in the dropdown menu, and "run". The `run` function is any async generator that should yield strings as you want them to be streamed to the UI. As an argument to the function, you have access to a `ContinueSDK` object with utilities such as access to certain information/actions within the IDE, the current language model, and a few other utilities. For example, here is a slash command that generates a commit message:
@ -51,9 +46,6 @@ export function modifyConfig(config: Config): Config {
}
```
<!-- TODO: We need a config.ts reference -->
<!-- For full `config.ts` reference, see [here](reference/config-ts.md). -->
## Other custom actions
Currently the other action triggers are not open for configuration, but we plan to allow this via .prompt files in the future.

View file

@ -18,7 +18,7 @@ The most common way to invoke an action is with a slash command. These are short
![slash-commands](/img/slash-commands.png)
A few of the most useful slash commands are available by default, like “/edit”, “/comment”, and “/share”, but Continue has a large built-in library of other options. To enable these, learn more [here](../customize/slash-commands.md).
A few of the most useful slash commands are available by default, like “/edit”, “/comment”, and “/share”, but Continue has a large built-in library of other options. To enable these, learn more [here](../customize/slash-commands.mdx).
### Prompt files
@ -36,7 +36,7 @@ Below is a quick example of setting up a prompt file to write unit tests using J
2. Add a file called `test.prompt` to this folder. The name of this file will be the name of the slash command you will use to generate your prompt.
3. Write the following contents to `test.prompt` and save.
```
```.prompt
{{{ input }}}
Write unit tests for the above selected code, following each of these instructions:

View file

@ -16,7 +16,7 @@ In order to display suggestions quickly, without sending too many requests, we d
## Context
As explained on the [context selection](context-selection.md) page, Continue uses a number of retrieval methods to find relevant snippets from your codebase to include in the prompt.
As explained on the [context selection](./context-selection.md) page, Continue uses a number of retrieval methods to find relevant snippets from your codebase to include in the prompt.
## Filtering
@ -28,4 +28,4 @@ Language models aren't perfect, but can be made much closer by adjusting their o
We will also occasionally entirely filter out responses if they are bad. This is often due to extreme repetition.
You can learn more about how it works in the [Autocomplete deep dive](../customize/deep-dives/autocomplete.md).
You can learn more about how it works in the [Autocomplete deep dive](../customize/deep-dives/autocomplete.mdx).

View file

@ -5,18 +5,20 @@ keywords: [customize]
sidebar_position: 5
---
Continue offers a handful of parameters in [`config.json`](../reference.md) that can be tuned to find the perfect balance between suggestion quality and system performance for your specific needs and hardware capabilities:
Continue offers a handful of parameters in [`config.json`](../json-reference.md) that can be tuned to find the perfect balance between suggestion quality and system performance for your specific needs and hardware capabilities:
```json title="config.json"
"tabAutocompleteOptions": {
"maxPromptTokens": 400,
"prefixPercentage": 0.5,
"multilineCompletions": "always"
}
{
"tabAutocompleteOptions": {
"maxPromptTokens": 400,
"prefixPercentage": 0.5,
"multilineCompletions": "always"
}
}
```
- `maxPromptTokens`: Sets the maximum number of tokens for the prompt, balancing context and speed.
- `prefixPercentage`: Defines the proportion of the prompt dedicated to the code before the cursor.
- `multilineCompletions`: Controls whether suggestions can span multiple lines ("always", "never", or "auto").
For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](../customize/deep-dives/autocomplete.md).
For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](../customize/deep-dives/autocomplete.mdx).

View file

@ -1,68 +0,0 @@
---
title: Model setup
description: Autocomplete \-model setup
keywords: [model, autocomplete]
sidebar_position: 2
---
:::info
This page recommends models and providers for Autocomplete. Read more about how to set up your `config.json` [here](../reference.md).
:::
## Best overall experience
For the best Autocomplete experience, we recommend using Codestral through the [Mistral API](https://console.mistral.ai/). This model offers high-quality completions with an excellent understanding of code context:
```json title="config.json""
{
"tabAutocompleteModel": {
"title": "Codestral",
"provider": "mistral",
"model": "codestral-latest",
"apiKey": "YOUR_API_KEY"
}
}
```
:::tip[Codestral API Key]
The API keys for Codestral and the general Mistral APIs are different. If you are using Codestral, you probably want a Codestral API key, but if you are sharing the key as a team or otherwise want to use `api.mistral.ai`, then make sure to set `"apiBase": "https://api.mistral.ai/v1"` in your `tabAutocompleteModel`.
:::
## Local, offline / self-hosted experience
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)).
```json title="config.json""
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama"
}
}
```
Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality suggestions.
:::note
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration.
:::
### Using a remote instance
When using a remote instance you need to set the `"apiBase"` value in the configuration:
```json title="config.json""
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama"
"apiBase": "http://<my endpoint>:11434"
}
}
```
## Other experiences
There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). You can also see more examples of Autocomplete configuration [here](../customize/deep-dives/autocomplete.md)

View file

@ -0,0 +1,115 @@
---
title: Model setup
description: Autocomplete \-model setup
keywords: [model, autocomplete]
sidebar_position: 2
---
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
:::info
This page recommends models and providers for Autocomplete. Read more about how to set up your `config.yaml` [here](../reference.md).
:::
## Best overall experience
For the best Autocomplete experience, we recommend using Codestral through the [Mistral API](https://console.mistral.ai/). This model offers high-quality completions with an excellent understanding of code context:
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: Codestral
provider: mistral
model: codestral-latest
apiKey: <YOUR_CODESTRAL_API_KEY>
roles:
- autocomplete
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Codestral",
"provider": "mistral",
"model": "codestral-latest",
"apiKey": "<YOUR_API_KEY>"
}
}
```
</TabItem>
</Tabs>
:::tip[Codestral API Key]
The API keys for Codestral and the general Mistral APIs are different. If you are using Codestral, you probably want a Codestral API key, but if you are sharing the key as a team or otherwise want to use `api.mistral.ai`, then make sure to set `"apiBase": "https://api.mistral.ai/v1"` in your `tabAutocompleteModel`.
:::
## Local, offline / self-hosted experience
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users (e.g. using [Ollama](../customize/model-providers/top-level/ollama.mdx) or [LM Studio](../customize/model-providers/more/lmstudio.mdx)).
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: Qwen2.5-Coder 1.5B
model: qwen2.5-coder:1.5b-base
provider: ollama
roles:
- autocomplete
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama"
}
}
```
</TabItem>
</Tabs>
Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality suggestions.
:::note
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration.
:::
### Using a remote instance
When using a remote instance you need to set the `"apiBase"` value in the configuration:
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: Qwen2.5-Coder 1.5B
model: qwen2.5-coder:1.5b-base
provider: ollama
apiBase: http://<my endpoint>:11434
roles:
- autocomplete
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama",
"apiBase": "http://<my endpoint>:11434"
}
}
```
</TabItem>
</Tabs>
## Other experiences
There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). You can also see more examples of Autocomplete configuration [here](../customize/deep-dives/autocomplete.mdx)

View file

@ -19,28 +19,28 @@ You can include the currently open file as context by pressing <kbd>opt</kbd> +
## Specific file
You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.md#file) and selecting the file.
You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.mdx#file) and selecting the file.
## Specific folder
You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folder) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder.
You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.mdx#folder) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.mdx) but only includes the files in the selected folder.
## Codebase search
You can automatically include relevant files from your codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md).
You can automatically include relevant files from your codebase as context by typing [`@Codebase`](../customize/context-providers.mdx#codebase). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.mdx).
## Documentation site
You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.md#docs) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.md).
You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.mdx#docs) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.mdx).
## Terminal contents
You can include the contents of the terminal in your IDE as context by typing [`@Terminal`](../customize/context-providers.md#terminal).
You can include the contents of the terminal in your IDE as context by typing [`@Terminal`](../customize/context-providers.mdx#terminal).
## Git diff
You can include all of the changes you've made to your current branch by typing [`@Git Diff`](../customize/context-providers.md#git-diff).
You can include all of the changes you've made to your current branch by typing [`@Git Diff`](../customize/context-providers.mdx#git-diff).
## Other context
You can see a full list of built-in context providers [here](../customize/context-providers.md) and how to create your own custom context provider [here](../customize/tutorials/build-your-own-context-provider.md).
You can see a full list of built-in context providers [here](../customize/context-providers.mdx) and how to create your own custom context provider [here](../customize/tutorials/build-your-own-context-provider.md).

View file

@ -9,6 +9,6 @@ Using any selected code sections, all context that you have selected with @, and
The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task.
If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.md#llm-prompt-logs).
If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.mdx#llm-prompt-logs).
You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.md) and `@Docs` [here](../customize/deep-dives/docs.md).
You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.mdx) and `@Docs` [here](../customize/deep-dives/docs.mdx).

View file

@ -8,8 +8,8 @@ sidebar_position: 5
There are a number of different ways to customize Chat
- You can add a [`.continuerules`](../customize/deep-dives/rules.md) file to the root of your project to customize the system prompt
- You can configure [`@Codebase`](../customize/deep-dives/codebase.md)
- You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.md)
- You can configure [`@Docs`](../customize/deep-dives/docs.md)
- You can configure [`@Codebase`](../customize/deep-dives/codebase.mdx)
- You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.mdx)
- You can configure [`@Docs`](../customize/deep-dives/docs.mdx)
- You can [build your own context provider](../customize/tutorials/build-your-own-context-provider.md)
- You can configure and create custom [tools](../customize/tools.md)
- You can configure and create custom [tools](../customize/tools.mdx)

View file

@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
:::info
This page recommends models and providers for Chat. Read more about how to set up your `config.json` [here](../reference.md).
This page recommends models and providers for Chat. Read more about how to set up your config [here](../reference.md).
:::
## Best overall experience
@ -18,116 +18,226 @@ For the best overall Chat experience, you will want to use a 400B+ parameter mod
### Claude Sonnet 3.5 from Anthropic
Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customize/model-providers/top-level/anthropic.md).
Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customize/model-providers/top-level/anthropic.mdx).
```json title="config.json"
"models": [
{
"title": "Claude 3.5 Sonnet",
"provider": "anthropic",
"model": "claude-3-5-sonnet-latest",
"apiKey": "[ANTHROPIC_API_KEY]"
}
]
```
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="Package or config.yaml"
models:
- name: Claude 3.5 Sonnet
provider: anthropic
model: claude-3-5-sonnet-latest
apiKey: <YOUR_ANTHROPIC_API_KEY>
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"provider": "anthropic",
"model": "claude-3-5-sonnet-latest",
"apiKey": "<YOUR_ANTHROPIC_API_KEY>"
}
]
}
```
</TabItem>
</Tabs>
### Llama 3.1 405B from Meta
If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)).
If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.mdx) or [Groq](../customize/model-providers/more/groq.mdx)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.mdx) or [Ollama](../customize/model-providers/top-level/ollama.mdx)).
<Tabs groupId="providers">
<TabItem value="Together">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "together",
"model": "llama3.1-405b",
"apiKey": "[TOGETHER_API_KEY]"
}
]
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
<Tabs groupId="providers">
<TabItem value="Together">
```yaml title="Package or config.yaml"
models:
- name: "Llama 3.1 405B"
provider: "together"
model: "llama3.1-405b"
apiKey: <YOUR_TOGETHER_API_KEY>
```
</TabItem>
<TabItem value="Groq">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "groq",
"model": "llama3.1-405b",
"apiKey": "[GROQ_API_KEY]"
}
]
</TabItem>
<TabItem value="Groq">
```yaml title="Package or config.yaml"
models:
- name: "Llama 3.1 405B"
provider: "groq"
model: "llama3.1-405b"
apiKey: <YOUR_GROQ_API_KEY>
```
</TabItem>
<TabItem value="vLLM">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "vllm",
"model": "llama3.1-405b"
}
]
</TabItem>
<TabItem value="vLLM">
```yaml title="Package or config.yaml"
models:
- name: "Llama 3.1 405B"
provider: "vllm"
model: "llama3.1-405b"
```
</TabItem>
<TabItem value="Ollama">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "ollama",
"model": "llama3.1:405b"
}
]
</TabItem>
<TabItem value="Ollama">
```yaml title="Package or config.yaml"
models:
- name: "Llama 3.1 405B"
provider: "ollama"
model: "llama3.1:405b"
```
</TabItem>
</TabItem>
</Tabs>
</TabItem>
<TabItem value="json" label="JSON">
<Tabs groupId="providers">
<TabItem value="Together">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 405B",
"provider": "together",
"model": "llama3.1-405b",
"apiKey": "<YOUR_TOGETHER_API_KEY>"
}
]
}
```
</TabItem>
<TabItem value="Groq">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 405B",
"provider": "groq",
"model": "llama3.1-405b",
"apiKey": "<YOUR_GROQ_API_KEY>"
}
]
}
```
</TabItem>
<TabItem value="vLLM">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 405B",
"provider": "vllm",
"model": "llama3.1-405b"
}
]
}
```
</TabItem>
<TabItem value="Ollama">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 405B",
"provider": "ollama",
"model": "llama3.1:405b"
}
]
}
```
</TabItem>
</Tabs>
</TabItem>
</Tabs>
### GPT-4o from OpenAI
If you prefer to use a model from [OpenAI](../customize/model-providers/top-level/openai.md), then we recommend GPT-4o.
If you prefer to use a model from [OpenAI](../customize/model-providers/top-level/openai.mdx), then we recommend GPT-4o.
```json title="config.json"
"models": [
{
"title": "GPT-4o",
"provider": "openai",
"model": "",
"apiKey": "[OPENAI_API_KEY]"
}
]
```
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="Package or config.yaml"
models:
- name: GPT-4o
provider: openai
model: ''
apiKey: <YOUR_OPENAI_API_KEY>
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"models": [
{
"title": "GPT-4o",
"provider": "openai",
"model": "",
"apiKey": "<YOUR_OPENAI_API_KEY>"
}
]
}
```
</TabItem>
</Tabs>
### Grok-2 from xAI
If you prefer to use a model from [xAI](../customize/model-providers/top-level/xAI.md), then we recommend Grok-2.
If you prefer to use a model from [xAI](../customize/model-providers/top-level/xAI.mdx), then we recommend Grok-2.
```json title="config.json"
"models": [
{
"title": "Grok-2",
"provider": "xAI",
"model": "grok-2-latest",
"apiKey": "[XAI_API_KEY]"
}
]
```
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="Package or config.yaml"
models:
- name: Grok-2
provider: xAI
model: grok-2-latest
apiKey: <YOUR_XAI_API_KEY>
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"models": [
{
"title": "Grok-2",
"provider": "xAI",
"model": "grok-2-latest",
"apiKey": "<YOUR_XAI_API_KEY>"
}
]
}
```
</TabItem>
</Tabs>
### Gemini 1.5 Pro from Google
If you prefer to use a model from [Google](../customize/model-providers/top-level/gemini.md), then we recommend Gemini 1.5 Pro.
If you prefer to use a model from [Google](../customize/model-providers/top-level/gemini.mdx), then we recommend Gemini 1.5 Pro.
```json title="config.json"
"models": [
{
"title": "Gemini 1.5 Pro",
"provider": "gemini",
"model": "gemini-1.5-pro-latest",
"apiKey": "[GEMINI_API_KEY]"
}
]
```
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="Package or config.yaml"
models:
- name: Gemini 1.5 Pro
provider: gemini
model: gemini-1.5-pro-latest
apiKey: <YOUR_GEMINI_API_KEY>
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"models": [
{
"title": "Gemini 1.5 Pro",
"provider": "gemini",
"model": "gemini-1.5-pro-latest",
"apiKey": "<YOUR_GEMINI_API_KEY>"
}
]
}
```
</TabItem>
</Tabs>
## Local, offline experience
@ -135,65 +245,117 @@ For the best local, offline Chat experience, you will want to use a model that i
### Llama 3.1 8B
If your local machine can run an 8B parameter model, then we recommend running Llama 3.1 8B on your machine (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)).
If your local machine can run an 8B parameter model, then we recommend running Llama 3.1 8B on your machine (e.g. using [Ollama](../customize/model-providers/top-level/ollama.mdx) or [LM Studio](../customize/model-providers/more/lmstudio.mdx)).
<Tabs groupId="providers">
<TabItem value="Ollama">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 8B",
"provider": "ollama",
"model": "llama3.1:8b",
"apiBase": "http://localhost:11434"
}
]
```
</TabItem>
<TabItem value="LM Studio">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 8B",
"provider": "lmstudio",
"model": "llama3.1-8b"
}
]
```
</TabItem>
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
<Tabs groupId="providers">
<TabItem value="Ollama">
```yaml title="Package or config.yaml"
models:
- name: Llama 3.1 8B
provider: ollama
model: llama3.1:8b
```
</TabItem>
<TabItem value="LM Studio">
```yaml title="Package or config.yaml"
models:
- name: Llama 3.1 8B
provider: lmstudio
model: llama3.1:8b
```
</TabItem>
</Tabs>
</TabItem>
<TabItem value="json" label="JSON">
<Tabs groupId="providers">
<TabItem value="Ollama">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8B",
"provider": "ollama",
"model": "llama3.1:8b"
}
]
}
```
</TabItem>
<TabItem value="LM Studio">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8B",
"provider": "lmstudio",
"model": "llama3.1-8b"
}
]
}
```
</TabItem>
</Tabs>
</TabItem>
</Tabs>
### DeepSeek Coder 2 16B
If your local machine can run a 16B parameter model, then we recommend running DeepSeek Coder 2 16B (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)).
If your local machine can run a 16B parameter model, then we recommend running DeepSeek Coder 2 16B (e.g. using [Ollama](../customize/model-providers/top-level/ollama.mdx) or [LM Studio](../customize/model-providers/more/lmstudio.mdx)).
<Tabs groupId="providers">
<TabItem value="Ollama">
```json title="config.json"
"models": [
{
"title": "DeepSeek Coder 2 16B",
"provider": "ollama",
"model": "deepseek-coder-v2:16b",
"apiBase": "http://localhost:11434"
}
]
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
<Tabs groupId="providers">
<TabItem value="Ollama">
```yaml title="Package or config.yaml"
models:
- name: DeepSeek Coder 2 16B
provider: ollama
model: deepseek-coder-v2:16b
```
</TabItem>
<TabItem value="LM Studio">
```json title="config.json"
"models": [
{
"title": "DeepSeek Coder 2 16B",
"provider": "lmstudio",
"model": "deepseek-coder-v2:16b"
}
]
</TabItem>
<TabItem value="LM Studio">
```yaml title="Package or config.yaml"
models:
- name: DeepSeek Coder 2 16B
provider: lmstudio
model: deepseek-coder-v2:16b
```
</TabItem>
</TabItem>
</Tabs>
</TabItem>
<TabItem value="json" label="JSON">
<Tabs groupId="providers">
<TabItem value="Ollama">
```json title="config.json"
{
"models": [
{
"title": "DeepSeek Coder 2 16B",
"provider": "ollama",
"model": "deepseek-coder-v2:16b",
"apiBase": "http://localhost:11434"
}
]
}
```
</TabItem>
<TabItem value="LM Studio">
```json title="config.json"
{
"models": [
{
"title": "DeepSeek Coder 2 16B",
"provider": "lmstudio",
"model": "deepseek-coder-v2:16b"
}
]
}
```
</TabItem>
</Tabs>
</TabItem>
</Tabs>
## Other experiences

View file

@ -1,676 +0,0 @@
---
title: Context providers
description: Type '@' to select content to the LLM as context
keywords: [context, "@", provider, LLM]
---
Context Providers allow you to type '@' and see a dropdown of content that can all be fed to the LLM as context. Every context provider is a plugin, which means if you want to reference some source of information that you don't see here, you can request (or build!) a new context provider.
As an example, say you are working on solving a new GitHub Issue. You type '@Issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input.
![Context Items](/img/context-provider-example.png)
## Built-in Context Providers
To use any of the built-in context providers, open `config.json` and add it to the `contextProviders` list.
### `@File`
Reference any file in your current workspace.
```json title="config.json"
{
"contextProviders": [
{
"name": "file"
}
]
}
```
### `@Code`
Reference specific functions or classes from throughout your project.
```json title="config.json"
{
"contextProviders": [
{
"name": "code"
}
]
}
```
### `@Git Diff`
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
```json title="config.json"
{
"contextProviders": [
{
"name": "diff"
}
]
}
```
### `@Current File`
Reference the currently open file.
```json title="config.json"
{
"contextProviders": [
{
"name": "currentFile"
}
]
}
```
### `@Terminal`
Reference the last command you ran in your IDE's terminal and its output.
```json title="config.json"
{
"contextProviders": [
{
"name": "terminal"
}
]
}
```
### `@Docs`
Reference the contents from any documentation site.
```json title="config.json"
{
"contextProviders": [
{
"name": "docs"
}
]
}
```
Note that this will only enable the `@Docs` context provider.
To use it, you need to add a documentation site to your `config.json`. See the [docs](../customize/deep-dives/docs.md) page for more information.
### `@Open`
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
```json title="config.json"
{
"contextProviders": [
{
"name": "open",
"params": {
"onlyPinned": true
}
}
]
}
```
### `@Web`
Reference relevant pages from across the web, automatically determined from your input.
Optionally, set "n" to limit the number of results returned (default 6).
```json title="config.json"
{
"contextProviders": [
{
"name": "web",
"params": {
"n": 5
}
}
]
}
```
### `@Codebase`
Reference the most relevant snippets from your codebase.
```json title="config.json"
{
"contextProviders": [
{
"name": "codebase"
}
]
}
```
Read more about indexing and retrieval [here](../customize/deep-dives/codebase.md).
### `@Folder`
Uses the same retrieval mechanism as `@Codebase`, but only on a single folder.
```json title="config.json"
{
"contextProviders": [
{
"name": "folder"
}
]
}
```
### `@Search`
Reference the results of codebase search, just like the results you would get from VS Code search.
```json title="config.json"
{
"contextProviders": [
{
"name": "search"
}
]
}
```
This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
### `@Url`
Reference the markdown converted contents of a given URL.
```json title="config.json"
{
"contextProviders": [
{
"name": "url"
}
]
}
```
### `@Clipboard`
Reference recent clipboard items
```json title="config.json"
{
"contextProviders": [
{
"name": "clipboard"
}
]
}
```
### `@Tree`
Reference the structure of your current workspace.
```json title="config.json"
{
"contextProviders": [
{
"name": "tree"
}
]
}
```
### `@Problems`
Get Problems from the current file.
```json title="config.json"
{
"contextProviders": [
{
"name": "problems"
}
]
}
```
### `@Debugger`
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
```json title="config.json"
{
"contextProviders": [
{
"name": "debugger",
"params": {
"stackDepth": 3
}
}
]
}
```
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
### `@Repository Map`
Reference the outline of your codebase. By default, signatures are included along with file in the repo map.
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
```json title="config.json"
{
"contextProviders": [
{
"name": "repo-map",
"params": {
"includeSignatures": false // default true
}
}
]
}
```
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from.
This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
### `@Operating System`
Reference the architecture and platform of your current operating system.
```json title="config.json"
{
"contextProviders": [
{
"name": "os"
}
]
}
```
### Model Context Protocol
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this:
```json
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
}
]
}
}
```
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
### Prompt Files
See [Prompt Files](/customize/deep-dives/prompt-files). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers.
### `@Issue`
Reference the conversation in a GitHub issue.
```json title="config.json"
{
"contextProviders": [
{
"name": "issue",
"params": {
"repos": [
{
"owner": "continuedev",
"repo": "continue"
}
],
"githubToken": "ghp_xxx"
}
}
]
}
```
Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited.
### `@Database`
Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
```json title="config.json"
{
"contextProviders": [
{
"name": "database",
"params": {
"connections": [
{
"name": "examplePostgres",
"connection_type": "postgres",
"connection": {
"user": "username",
"host": "localhost",
"database": "exampleDB",
"password": "yourPassword",
"port": 5432
}
},
{
"name": "exampleMssql",
"connection_type": "mssql",
"connection": {
"user": "username",
"server": "localhost",
"database": "exampleDB",
"password": "yourPassword"
}
},
{
"name": "exampleSqlite",
"connection_type": "sqlite",
"connection": {
"filename": "/path/to/your/sqlite/database.db"
}
}
]
}
}
]
}
```
Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type.
Available connection types:
- `postgres`
- `mysql`
- `sqlite`
### `@Postgres`
Reference the schema of a table, and some sample rows
```json title="config.json"
{
"contextProviders": [
{
"name": "postgres",
"params": {
"host": "localhost",
"port": 5436,
"user": "myuser",
"password": "catsarecool",
"database": "animals",
"schema": "public",
"sampleRows": 3
}
}
]
}
```
The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`.
By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas.
[Here is a short demo.](https://github.com/continuedev/continue/pull/859)
### `@Google`
Reference the results of a Google search.
```json title="config.json"
{
"contextProviders": [
{
"name": "google",
"params": {
"serperApiKey": "<your serper.dev api key>"
}
}
]
}
```
For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python.
Note: You can get an API key for free at [serper.dev](https://serper.dev).
### `@Gitlab Merge Request`
Reference an open MR for this branch on GitLab.
```json title="config.json"
{
"contextProviders": [
{
"name": "gitlab-mr",
"params": {
"token": "..."
}
}
]
}
```
You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope.
#### Using Self-Hosted GitLab
You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`.
```json title="config.json"
{
"contextProviders": [
{
"name": "gitlab-mr",
"params": {
"token": "...",
"domain": "gitlab.example.com"
}
}
]
}
```
#### Filtering Comments
If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`.
### `@Jira`
Reference the conversation in a Jira issue.
```json title="config.json"
{
"contextProviders": [
{
"name": "jira",
"params": {
"domain": "company.atlassian.net",
"token": "ATATT..."
}
}
]
}
```
Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email.
#### Jira Datacenter Support
This context provider supports both Jira API version 2 and 3. It will use version 3 by default since
that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need
to set the API Version to 2 using the `apiVersion` property.
```json title="config.json"
{
"contextProviders": [
{
"name": "jira",
"params": {
"apiVersion": "2"
}
}
]
}
```
#### Issue Query
By default, the following query will be used to find issues:
```jql
assignee = currentUser() AND resolution = Unresolved order by updated DESC
```
You can override this query by setting the `issueQuery` parameter.
### `@Discord`
Reference the messages in a Discord channel.
```json title="config.json"
{
"contextProviders": [
{
"name": "discord",
"params": {
"discordKey": "bot token",
"guildId": "1234567890",
"channels": [
{
"id": "123456",
"name": "example-channel"
},
{
"id": "678901",
"name": "example-channel-2"
}
]
}
}
]
}
```
Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels.
### `@HTTP`
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
```json title="config.json"
{
"contextProviders": [
{
"name": "http",
"params": {
"url": "https://api.example.com/v1/users"
}
}
]
}
```
The receiving URL should expect to receive the following parameters:
```js title="POST parameters"
{
query: string,
fullInput: string
}
```
The response 200 OK should be a JSON object with the following structure:
```json title="Response"
[
{
"name": "",
"description": "",
"content": ""
}
]
// OR
{
"name": "",
"description": "",
"content": ""
}
```
### `@Commits`
Reference specific git commit metadata and diff or all of the recent commits.
```json title="config.json"
{
"contextProviders": [
{
"name": "commit",
"params": {
"Depth": 50,
"LastXCommitsDepth": 10
}
}
]
}
```
The depth is how many commits will be loaded into the submenu, defaults to 50.
The LastXCommitsDepth is how many recent commits will be included, defaults to 10.
### `@Clipboard`
Reference recent clipboard items
```json title="config.json"
{
"contextProviders": [
{
"name": "clipboard"
}
]
}
```
### `@Greptile`
Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
```json title="config.json"
{
"contextProviders": [
{
"name": "greptile",
"params": {
"GreptileToken": "...",
"GithubToken": "..."
}
}
]
}
```
### Requesting Context Providers
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider.

File diff suppressed because it is too large Load diff

View file

@ -3,20 +3,38 @@ title: Autocomplete
keywords: [autocomplete]
---
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
### Setting up with Codestral (recommended)
If you want to have the best autocomplete experience, we recommend using Codestral, which is available through the [Mistral API](https://console.mistral.ai/). To do this, obtain an API key and add it to your `config.json`:
If you want to have the best autocomplete experience, we recommend using Codestral, which is available through the [Mistral API](https://console.mistral.ai/). To do this, obtain an API key and add it to your config:
```json
{
"tabAutocompleteModel": {
"title": "Codestral",
"provider": "mistral",
"model": "codestral-latest",
"apiKey": "YOUR_API_KEY"
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: Codestral
provider: mistral
model: codestral-latest
apiKey: <YOUR_CODESTRAL_API_KEY>
roles:
- autocomplete
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Codestral",
"provider": "mistral",
"model": "codestral-latest",
"apiKey": "<YOUR_CODESTRAL_API_KEY>"
}
}
}
```
```
</TabItem>
</Tabs>
### Setting up with Ollama (default)
@ -32,17 +50,31 @@ Once it has been downloaded, you should begin to see completions in VS Code.
All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote Ollama instance you would edit your `config.json` like this (note that it is not inside the models array):
```json title="config.json"
{
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: Tab Autocomplete Model
provider: ollama
model: qwen2.5-coder:1.5b-base
apiBase: https://<my endpoint>
roles:
- autocomplete
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
...
}
```
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
}
}
```
</TabItem>
</Tabs>
If you aren't yet familiar with the available options, you can find the full reference [here](./configuration.md).
@ -70,21 +102,36 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
### Full example
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
"debounceDelay": 500,
"maxPromptTokens": 1500,
"disableInFiles": ["*.md"]
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: Tab Autocomplete Model
provider: ollama
model: qwen2.5-coder:1.5b-base
apiBase: https://<my endpoint>
roles:
- autocomplete
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
"debounceDelay": 500,
"maxPromptTokens": 1500,
"disableInFiles": ["*.md"]
}
}
}
```
```
</TabItem>
</Tabs>
## FAQs

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