Merge branch 'main' into pr/4771

This commit is contained in:
tomasz-io 2025-04-29 12:08:04 -07:00
commit fab05904d5
201 changed files with 4939 additions and 2143 deletions

View file

@ -481,7 +481,7 @@ jobs:
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2024.3.2
uses: JetBrains/qodana-action@v2025.1.0
with:
cache-default-branch-only: true

View file

@ -1,5 +1,6 @@
name: PR checks
# PR Checks run on all PRs to the main branch and must pass before merging.
on:
pull_request:
branches:
@ -415,6 +416,30 @@ jobs:
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
package-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Install dependencies
run: |
cd packages/config-yaml
npm ci
- name: Run config-yaml tests
run: |
cd packages/config-yaml
npm test
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode, install-config-yaml]
@ -551,7 +576,7 @@ jobs:
path: extensions/vscode/e2e/storage
vscode-e2e-tests:
name: ${{ matrix.test_file }} (${{ matrix.command }})
name: ${{ matrix.test_file || 'unknown' }} (${{ matrix.command }})
needs:
[
vscode-download-e2e-dependencies,
@ -652,6 +677,27 @@ jobs:
name: e2e-failure-screenshots
path: extensions/vscode/e2e/storage/screenshots
- name: Sanitize test file name
id: sanitize_filename
if: always()
run: |
FILENAME="${{ matrix.test_file }}"
SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion
echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT
- name: Find e2e log file
if: always()
run: |
echo "Searching for e2e.log file..."
find $GITHUB_WORKSPACE -name "e2e.log" -type f
- name: Upload e2e logs
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
path: extensions/vscode/e2e.log
gui-tests:
needs: [install-gui, install-core, install-config-yaml]
runs-on: ubuntu-latest
@ -820,6 +866,7 @@ jobs:
- install-vscode
- vscode-checks
- core-tests
- package-tests
- vscode-get-test-file-matrix
- vscode-package-extension
- vscode-download-e2e-dependencies

10
.gitignore vendored
View file

@ -83,16 +83,6 @@ ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid

3
.idea/compiler.xml generated
View file

@ -3,4 +3,7 @@
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="17" />
</component>
<component name="TypeScriptCompiler">
<option name="useTypesFromServer" value="true" />
</component>
</project>

View file

@ -1,3 +1,3 @@
<component name="DependencyValidationManager">
<scope name="Continue" pattern="file[continue-intellij-extension]:*/&amp;&amp;!file[continue-intellij-extension]:binary/bin//*&amp;&amp;!file[continue-intellij-extension]:binary/build//*&amp;&amp;!file[continue-intellij-extension]:binary/out//*&amp;&amp;!file[continue-intellij-extension]:gui/dist//*&amp;&amp;!file[continue-intellij-extension]:extensions/intellij/build//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/bin//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/build//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/out//*" />
<scope name="Continue" pattern="file:*/&amp;&amp;!file:binary/bin//*&amp;&amp;!file:binary/build//*&amp;&amp;!file:binary/out//*&amp;&amp;!file:gui/dist//*&amp;&amp;!file:extensions/intellij/build//*&amp;&amp;!file:extensions/vscode/bin//*&amp;&amp;!file:extensions/vscode/build//*&amp;&amp;!file:extensions/vscode/out//*&amp;&amp;!file:**/*.coverage&amp;&amp;!file:**/*.coveragedata&amp;&amp;!file:**/coverage//*&amp;&amp;!file:**/.coverage//*&amp;&amp;!file:**/assets//**" />
</component>

View file

@ -51,7 +51,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.18",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -106,6 +106,7 @@
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"winston": "^3.17.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.24.2"
@ -2086,9 +2087,10 @@
}
},
"node_modules/@octokit/endpoint": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.5.tgz",
"integrity": "sha512-ekqR4/+PCLkEBF6qgj8WqJfvDq65RH85OAgrtnVp1mSxaXF03u2xW/hUdweGS5654IlC0wkNYC18Z50tSYTAFw==",
"version": "9.0.6",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz",
"integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==",
"license": "MIT",
"dependencies": {
"@octokit/types": "^13.1.0",
"universal-user-agent": "^6.0.0"
@ -2155,12 +2157,13 @@
}
},
"node_modules/@octokit/request": {
"version": "8.4.0",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.0.tgz",
"integrity": "sha512-9Bb014e+m2TgBeEJGEbdplMVWwPmL1FPtggHQRkV+WVsMggPtEkLKPlcVYm/o8xKLkpJ7B+6N8WfQMtDLX2Dpw==",
"version": "8.4.1",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz",
"integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==",
"license": "MIT",
"dependencies": {
"@octokit/endpoint": "^9.0.1",
"@octokit/request-error": "^5.1.0",
"@octokit/endpoint": "^9.0.6",
"@octokit/request-error": "^5.1.1",
"@octokit/types": "^13.1.0",
"universal-user-agent": "^6.0.0"
},
@ -2169,9 +2172,10 @@
}
},
"node_modules/@octokit/request-error": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.0.tgz",
"integrity": "sha512-GETXfE05J0+7H2STzekpKObFe765O5dlAKUTLNGeH+x47z7JjXHfsHKo5z21D/o/IOZTUEI6nyWyR+bZVP/n5Q==",
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz",
"integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==",
"license": "MIT",
"dependencies": {
"@octokit/types": "^13.1.0",
"deprecation": "^2.0.0",

View file

@ -13,7 +13,7 @@
"@typescript-eslint/semi": "off",
"eqeqeq": "error",
"complexity": ["error", { "max": 36 }],
"max-lines-per-function": ["error", { "max": 472 }],
"max-lines-per-function": ["error", { "max": 500 }],
"max-statements": ["error", { "max": 108 }],
"max-depth": ["error", { "max": 6 }],
"max-nested-callbacks": ["error", { "max": 4 }],

View file

@ -103,7 +103,7 @@ export function postprocessCompletion({
}
}
if (llm.model.includes("granite")) {
if (llm.model.includes("mercury") || llm.model.includes("granite")) {
// Granite tends to repeat the start of the line in the completion output
let prefixEnd = prefix.split("\n").pop();
if (prefixEnd) {
@ -123,13 +123,14 @@ export function postprocessCompletion({
// // If completion starts with multiple whitespaces, but the cursor is at the end of the line
// // then it should probably be on a new line
// if (
// (completion.startsWith(" ") || completion.startsWith("\t")) &&
// !prefix.endsWith("\n") &&
// (suffix.startsWith("\n") || suffix.trim().length === 0)
// ) {
// completion = "\n" + completion;
// }
if (
llm.model.includes("mercury") &&
(completion.startsWith(" ") || completion.startsWith("\t")) &&
!prefix.endsWith("\n") &&
(suffix.startsWith("\n") || suffix.trim().length === 0)
) {
completion = "\n" + completion;
}
// If prefix ends with space and so does completion, then remove the space from completion

View file

@ -87,9 +87,10 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
snippets,
workspaceUris,
): [string, string] => {
function getFileName(snippet: { uri: string, uniquePath: string }) {
return snippet.uri.startsWith("file://") ? snippet.uniquePath : snippet.uri
function getFileName(snippet: { uri: string; uniquePath: string }) {
return snippet.uri.startsWith("file://")
? snippet.uniquePath
: snippet.uri;
}
if (snippets.length === 0) {
@ -135,6 +136,64 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
},
};
const mercuryMultifileFimTemplate: AutocompleteTemplate = {
compilePrefixSuffix: (
prefix,
suffix,
filepath,
reponame,
snippets,
workspaceUris,
): [string, string] => {
function getFileName(snippet: { uri: string; uniquePath: string }) {
return snippet.uri.startsWith("file://")
? snippet.uniquePath
: snippet.uri;
}
// Our current snippet format doesn't work well with mercury. We need to clean this up
snippets = [];
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
return [
`<|file_sep|>${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n${prefix}`,
suffix,
];
}
return [prefix, suffix];
}
const relativePaths = getShortestUniqueRelativeUriPaths(
[
...snippets.map((snippet) =>
"filepath" in snippet ? snippet.filepath : "file:///Untitled.txt",
),
filepath,
],
workspaceUris,
);
const otherFiles = snippets
.map((snippet, i) => {
if (snippet.type === AutocompleteSnippetType.Diff) {
return snippet.content;
}
return `<|file_sep|>${getFileName(relativePaths[i])} \n${snippet.content}`;
})
.join("\n\n");
return [
`${otherFiles}${otherFiles ? "\n\n" : ""}<|file_sep|>${getFileName(relativePaths[relativePaths.length - 1])}\n<|fim_prefix|>${prefix}`,
suffix,
];
},
template: (prefix: string, suffix: string): string => {
return `${prefix}<|fim_suffix|>${suffix}<|fim_middle|>`;
},
};
const codegemmaFimTemplate: AutocompleteTemplate = {
template:
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
@ -223,8 +282,9 @@ 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`;
}
@ -358,6 +418,9 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
// if (lowerCaseModel.includes("starcoder2")) {
// return starcoder2FimTemplate;
// }
if (lowerCaseModel.includes("mercury")) {
return mercuryMultifileFimTemplate;
}
if (lowerCaseModel.includes("qwen") && lowerCaseModel.includes("coder")) {
return qwenCoderFimTemplate;

View file

@ -15,7 +15,12 @@ import {
} from "../index.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getAllAssistantFiles } from "./loadLocalAssistants.js";
import { logger } from "../util/logger.js";
import {
ASSISTANTS,
getAllDotContinueYamlFiles,
LoadAssistantFilesOptions,
} from "./loadLocalAssistants.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
import {
@ -185,7 +190,11 @@ export class ConfigHandler {
private async getNonPersonalHubOrg(
org: OrganizationDescription,
): Promise<OrgWithProfiles> {
const profiles = await this.getHubProfiles(org.id);
const localProfiles = await this.getLocalProfiles({
includeGlobal: false,
includeWorkspace: true,
});
const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
return this.rectifyProfilesForOrg(org, profiles);
}
@ -196,15 +205,21 @@ export class ConfigHandler {
slug: undefined,
};
private async getPersonalHubOrg() {
const allLocalProfiles = await this.getAllLocalProfiles();
const localProfiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
const hubProfiles = await this.getHubProfiles(null);
const profiles = [...hubProfiles, ...allLocalProfiles];
const profiles = [...hubProfiles, ...localProfiles];
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
}
private async getLocalOrg() {
const allLocalProfiles = await this.getAllLocalProfiles();
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles);
const localProfiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
}
private async rectifyProfilesForOrg(
@ -251,24 +266,41 @@ export class ConfigHandler {
};
}
async getAllLocalProfiles() {
async getLocalProfiles(options: LoadAssistantFilesOptions) {
/**
* Users can define as many local assistants as they want in a `.continue/assistants` folder
*/
const assistantFiles = await getAllAssistantFiles(this.ide);
const profiles = assistantFiles.map((assistant) => {
return new LocalProfileLoader(
const localProfiles: ProfileLifecycleManager[] = [];
if (options.includeGlobal) {
localProfiles.push(this.globalLocalProfileManager);
}
if (options.includeWorkspace) {
const assistantFiles = await getAllDotContinueYamlFiles(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.llmLogger,
assistant,
{
...options,
includeGlobal: false, // Because the global comes from above
},
ASSISTANTS,
);
});
const localAssistantProfiles = profiles.map(
(profile) => new ProfileLifecycleManager(profile, this.ide),
);
return [this.globalLocalProfileManager, ...localAssistantProfiles];
const profiles = assistantFiles.map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.llmLogger,
assistant,
);
});
const localAssistantProfiles = profiles.map(
(profile) => new ProfileLifecycleManager(profile, this.ide),
);
localProfiles.push(...localAssistantProfiles);
}
return localProfiles;
}
//////////////////
@ -421,9 +453,14 @@ export class ConfigHandler {
configLoadInterrupted: true,
};
}
return await this.currentProfile.loadConfig(
const config = await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
if (config.errors?.length) {
logger.warn("Errors loading config: ", config.errors);
}
return config;
}
async openConfigProfile(profileId?: string) {

View file

@ -95,7 +95,10 @@ export class ProfileLifecycleManager {
try {
result = await this.profileLoader.doLoadConfig();
} catch (e) {
const message = e instanceof Error ? e.message : "Error loading config";
const message =
e instanceof Error
? `${e.message}\n${e.stack ? e.stack : ""}`
: "Error loading config";
result = {
errors: [
{

View file

@ -486,7 +486,7 @@ async function intermediateToFinalConfig({
const cls = LLMClasses.find((c) => c.providerName === name);
if (cls) {
const llmOptions: LLMOptions = {
model: params?.model,
model: params?.model ?? "UNSPECIFIED",
...params,
};
return new cls(llmOptions);

View file

@ -5,11 +5,12 @@ import {
DEFAULT_IGNORE_FILETYPES,
} from "../indexing/ignore";
import { walkDir } from "../indexing/walkDir";
import { getGlobalAssistantsPath } from "../util/paths";
import { getGlobalFolderWithName } from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { joinPathsToUri } from "../util/uri";
export const ASSISTANTS_FOLDER = ".continue/assistants";
export const ASSISTANTS = "assistants";
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
export function isLocalAssistantFile(uri: string): boolean {
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
@ -20,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean {
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
}
export async function getAssistantFilesFromDir(
export async function listYamlFilesInDir(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
@ -53,21 +54,56 @@ export async function getAssistantFilesFromDir(
}
}
export async function getAllAssistantFiles(
export interface LoadAssistantFilesOptions {
includeGlobal: boolean;
includeWorkspace: boolean;
}
export function getDotContinueSubDirs(
ide: IDE,
options: LoadAssistantFilesOptions,
workspaceDirs: string[],
subDirName: string,
): string[] {
let fullDirs: string[] = [];
// Workspace .continue/<subDirName>
if (options.includeWorkspace) {
fullDirs = workspaceDirs.map((dir) =>
joinPathsToUri(dir, ".continue", subDirName),
);
}
// ~/.continue/<subDirName>
if (options.includeGlobal) {
fullDirs.push(localPathToUri(getGlobalFolderWithName(subDirName)));
}
return fullDirs;
}
/**
* This method searches in both ~/.continue and workspace .continue
* for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
*/
export async function getAllDotContinueYamlFiles(
ide: IDE,
options: LoadAssistantFilesOptions,
subDirName: string,
): Promise<{ path: string; content: string }[]> {
const workspaceDirs = await ide.getWorkspaceDirs();
let assistantFiles: { path: string; content: string }[] = [];
let dirsToCheck = [ASSISTANTS_FOLDER];
const fullDirs = workspaceDirs
.map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
.flat();
// Get all directories to check for assistant files
const fullDirs = getDotContinueSubDirs(
ide,
options,
workspaceDirs,
subDirName,
);
fullDirs.push(localPathToUri(getGlobalAssistantsPath()));
assistantFiles = (
await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir)))
// Get all assistant files from the directories
const assistantFiles = (
await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
).flat();
return await Promise.all(

View file

@ -60,12 +60,14 @@ export default class LocalProfileLoader implements IProfileLoader {
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigJson: undefined,
overrideConfigYaml: undefined,
platformConfigMetadata: undefined,
profileId: this.description.id,
overrideConfigYamlByPath: this.overrideAssistantFile?.path,
orgScopeId: null,
packageIdentifier: {
uriType: "file",
filePath:
this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
},
});
this.description.errors = result.errors;

View file

@ -142,15 +142,17 @@ export default class PlatformProfileLoader implements IProfileLoader {
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigJson: undefined,
overrideConfigYaml: this.configResult.config,
platformConfigMetadata: {
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
},
profileId: this.description.id,
overrideConfigYamlByPath: undefined,
orgScopeId: this.orgScopeId,
packageIdentifier: {
uriType: "slug",
fullSlug: {
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
versionSlug: this.versionSlug,
},
},
});
return {

View file

@ -5,6 +5,7 @@ import {
ConfigResult,
ConfigValidationError,
ModelRole,
PackageIdentifier,
} from "@continuedev/config-yaml";
import {
@ -29,37 +30,37 @@ import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
export default async function doLoadConfig({
ide,
ideSettingsPromise,
controlPlaneClient,
llmLogger,
overrideConfigJson,
overrideConfigYaml,
platformConfigMetadata,
profileId,
overrideConfigYamlByPath,
orgScopeId,
}: {
export default async function doLoadConfig(options: {
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
controlPlaneClient: ControlPlaneClient;
llmLogger: ILLMLogger;
overrideConfigJson: SerializedContinueConfig | undefined;
overrideConfigYaml: AssistantUnrolled | undefined;
platformConfigMetadata: PlatformConfigMetadata | undefined;
overrideConfigJson?: SerializedContinueConfig;
overrideConfigYaml?: AssistantUnrolled;
profileId: string;
overrideConfigYamlByPath: string | undefined;
overrideConfigYamlByPath?: string;
orgScopeId: string | null;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<ContinueConfig>> {
const {
ide,
ideSettingsPromise,
controlPlaneClient,
llmLogger,
overrideConfigJson,
overrideConfigYaml,
profileId,
overrideConfigYamlByPath,
orgScopeId,
packageIdentifier,
} = options;
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
const uniqueId = await ide.getUniqueId();
@ -89,10 +90,10 @@ export default async function doLoadConfig({
uniqueId,
llmLogger,
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
configYamlPath,
orgScopeId,
packageIdentifier,
workOsAccessToken,
});
newConfig = result.config;
errors = result.errors;
@ -236,13 +237,13 @@ export default async function doLoadConfig({
};
if (newConfig.analytics) {
await TeamAnalytics.setup(
newConfig.analytics,
uniqueId,
ideInfo.extensionVersion,
controlPlaneClient,
controlPlaneProxyInfo,
);
// await TeamAnalytics.setup(
// newConfig.analytics,
// uniqueId,
// ideInfo.extensionVersion,
// controlPlaneClient,
// controlPlaneProxyInfo,
// );
} else {
await TeamAnalytics.shutdown();
}

View file

@ -403,6 +403,7 @@ declare global {
| "generated"
| "calling"
| "done"
| "errored"
| "canceled";
// Will exist only on "assistant" messages with tool calls

View file

@ -0,0 +1,106 @@
import {
FQSN,
PlatformClient,
SecretResult,
SecretType,
} from "@continuedev/config-yaml";
import * as dotenv from "dotenv";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { getContinueDotEnv } from "../../util/paths";
import { joinPathsToUri } from "../../util/uri";
export class LocalPlatformClient implements PlatformClient {
constructor(
private orgScopeId: string | null,
private readonly client: ControlPlaneClient,
private readonly ide: IDE,
) {}
private async findSecretInEnvFiles(
fqsn: FQSN,
): Promise<SecretResult | undefined> {
const secretValue =
this.findSecretInLocalEnvFile(fqsn) ??
(await this.findSecretInWorkspaceEnvFiles(fqsn));
if (secretValue) {
return {
found: true,
fqsn,
value: secretValue,
secretLocation: {
secretName: fqsn.secretName,
secretType: SecretType.LocalEnv,
},
};
}
return undefined;
}
private findSecretInLocalEnvFile(fqsn: FQSN): string | undefined {
try {
const dotEnv = getContinueDotEnv();
return dotEnv[fqsn.secretName];
} catch (error) {
console.warn(
`Error reading ~/.continue/.env file: ${error instanceof Error ? error.message : String(error)}`,
);
return undefined;
}
}
private async findSecretInWorkspaceEnvFiles(
fqsn: FQSN,
): Promise<string | undefined> {
try {
const workspaceDirs = await this.ide.getWorkspaceDirs();
for (const folder of workspaceDirs) {
const envFilePath = joinPathsToUri(folder, ".env");
try {
const fileExists = await this.ide.fileExists(envFilePath);
if (fileExists) {
const envContent = await this.ide.readFile(envFilePath);
const env = dotenv.parse(envContent);
if (fqsn.secretName in env) {
return env[fqsn.secretName];
}
}
} catch (error) {
console.warn(
`Error reading workspace .env file at ${envFilePath}: ${error instanceof Error ? error.message : String(error)}`,
);
// Continue to next workspace folder
}
}
return undefined;
} catch (error) {
console.warn(
`Error searching workspace .env files: ${error instanceof Error ? error.message : String(error)}`,
);
return undefined;
}
}
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
if (fqsns.length === 0) {
return [];
}
const results = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
// For any secret that isn't found, look in .env files
for (let i = 0; i < results.length; i++) {
if (!results[i]?.found) {
const secretFromEnv = await this.findSecretInEnvFiles(fqsns[i]);
if (secretFromEnv?.found) {
results[i] = secretFromEnv;
}
}
}
return results;
}
}

View file

@ -1,20 +1,18 @@
import fs from "node:fs";
import {
AssistantUnrolled,
BLOCK_TYPES,
ConfigResult,
ConfigValidationError,
FQSN,
isAssistantUnrolledNonNullable,
MCPServer,
ModelRole,
PlatformClient,
PackageIdentifier,
RegistryClient,
Rule,
SecretResult,
unrollAssistantFromContent,
unrollAssistant,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { dirname } from "node:path";
import {
ContinueConfig,
@ -39,29 +37,15 @@ import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandF
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { allTools } from "../../tools";
import { GlobalContext } from "../../util/GlobalContext";
import { getConfigYamlPath } from "../../util/paths";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { logger } from "../../util/logger";
import { getCleanUriPath } from "../../util/uri";
import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
export class LocalPlatformClient implements PlatformClient {
constructor(
private orgScopeId: string | null,
private readonly client: ControlPlaneClient,
) {}
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
if (fqsns.length === 0) {
return [];
}
const response = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
return response;
}
}
function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
if (typeof rule === "string") {
return {
@ -72,7 +56,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
return {
source: "rules-block",
rule: rule.rule,
if: rule.if,
globs: rule.globs,
name: rule.name,
};
}
@ -91,35 +75,70 @@ function convertYamlMcpToContinueMcp(
};
}
async function loadConfigYaml(
rawYaml: string,
overrideConfigYaml: AssistantUnrolled | undefined,
controlPlaneClient: ControlPlaneClient,
orgScopeId: string | null,
ideSettings: IdeSettings,
): Promise<ConfigResult<AssistantUnrolled>> {
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
controlPlaneClient: ControlPlaneClient;
orgScopeId: string | null;
ideSettings: IdeSettings;
ide: IDE;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<AssistantUnrolled>> {
const {
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
ideSettings,
ide,
packageIdentifier,
} = options;
// Add local .continue blocks
const allLocalBlocks: PackageIdentifier[] = [];
for (const blockType of BLOCK_TYPES) {
const localBlocks = await getAllDotContinueYamlFiles(
ide,
{ includeGlobal: true, includeWorkspace: true },
blockType,
);
allLocalBlocks.push(
...localBlocks.map((b) => ({
uriType: "file" as const,
filePath: b.path,
})),
);
}
const rootPath =
packageIdentifier.uriType === "file"
? dirname(getCleanUriPath(packageIdentifier.filePath))
: undefined;
logger.info(
`Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
);
let config =
overrideConfigYaml ??
// This is how we allow use of blocks locally
(await unrollAssistantFromContent(
{
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
rawYaml,
new RegistryClient(
await controlPlaneClient.getAccessToken(),
getControlPlaneEnvSync(
ideSettings.continueTestEnvironment,
).CONTROL_PLANE_URL,
),
(await unrollAssistant(
packageIdentifier,
new RegistryClient({
accessToken: await controlPlaneClient.getAccessToken(),
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
.CONTROL_PLANE_URL,
rootPath,
}),
{
currentUserSlug: "",
onPremProxyUrl: null,
orgScopeId,
platformClient: new LocalPlatformClient(orgScopeId, controlPlaneClient),
platformClient: new LocalPlatformClient(
orgScopeId,
controlPlaneClient,
ide,
),
renderSecrets: true,
injectBlocks: allLocalBlocks,
},
));
@ -148,25 +167,27 @@ async function loadConfigYaml(
};
}
async function configYamlToContinueConfig({
config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
platformConfigMetadata,
allowFreeTrial = true,
}: {
async function configYamlToContinueConfig(options: {
config: AssistantUnrolled;
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
allowFreeTrial: boolean;
workOsAccessToken: string | undefined;
allowFreeTrial?: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let {
config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
allowFreeTrial,
} = options;
allowFreeTrial = allowFreeTrial ?? true;
const localErrors: ConfigValidationError[] = [];
const continueConfig: ContinueConfig = {
@ -275,7 +296,6 @@ async function configYamlToContinueConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config: continueConfig,
});
@ -431,44 +451,39 @@ async function configYamlToContinueConfig({
return { config: continueConfig, errors: localErrors };
}
export async function loadContinueConfigFromYaml({
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
configYamlPath,
orgScopeId,
}: {
export async function loadContinueConfigFromYaml(options: {
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
overrideConfigYaml: AssistantUnrolled | undefined;
platformConfigMetadata: PlatformConfigMetadata | undefined;
controlPlaneClient: ControlPlaneClient;
configYamlPath: string | undefined;
orgScopeId: string | null;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<ContinueConfig>> {
const rawYaml =
overrideConfigYaml === undefined
? fs.readFileSync(
configYamlPath ?? getConfigYamlPath(ideInfo.ideType),
"utf-8",
)
: "";
const {
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
packageIdentifier,
} = options;
const configYamlResult = await loadConfigYaml(
rawYaml,
const configYamlResult = await loadConfigYaml({
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
ideSettings,
);
ide,
packageIdentifier,
});
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
return {
@ -486,8 +501,7 @@ export async function loadContinueConfigFromYaml({
ideInfo,
uniqueId,
llmLogger,
platformConfigMetadata,
allowFreeTrial: true,
workOsAccessToken,
});
// Apply shared config

View file

@ -9,7 +9,6 @@ import {
} from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
const AUTODETECT = "AUTODETECT";
@ -32,14 +31,12 @@ async function modelConfigToBaseLLM({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM | undefined> {
const cls = getModelClass(model);
@ -63,6 +60,7 @@ async function modelConfigToBaseLLM({
logger: llmLogger,
uniqueId,
title: model.name,
template: model.promptTemplates?.chatTemplate,
promptTemplates: model.promptTemplates,
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
capabilities: {
@ -147,7 +145,6 @@ async function autodetectModels({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
}: {
llm: BaseLLM;
@ -156,7 +153,6 @@ async function autodetectModels({
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
try {
@ -177,7 +173,6 @@ async function autodetectModels({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
});
}),
@ -195,7 +190,6 @@ export async function llmsFromModelConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
@ -203,7 +197,6 @@ export async function llmsFromModelConfig({
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM({
@ -211,7 +204,6 @@ export async function llmsFromModelConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
});
if (!baseLlm) {
@ -226,7 +218,6 @@ export async function llmsFromModelConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
});
return models;

View file

@ -14,7 +14,7 @@ import {
MCPTool,
} from "../..";
const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds
export const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds
class MCPConnection {
public client: Client;
@ -30,7 +30,7 @@ class MCPConnection {
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
constructor(private readonly options: MCPOptions) {
constructor(public options: MCPOptions) {
this.transport = this.constructTransport(options);
this.client = new Client(
@ -139,7 +139,6 @@ class MCPConnection {
this.transport = this.constructTransport(this.options);
try {
await this.client.connect(this.transport);
await this.client.close();
} catch (error) {
// Allow the case where for whatever reason is already connected
if (

View file

@ -1,6 +1,11 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { MCPOptions, MCPServerStatus } from "../..";
import {
MCPOptions,
MCPServerStatus,
StdioOptions,
TransportOptions,
} from "../..";
import MCPConnection from "./MCPConnection";
export class MCPManagerSingleton {
@ -48,7 +53,17 @@ export class MCPManagerSingleton {
// Remove any connections that are no longer in config
Array.from(this.connections.entries()).forEach(([id, connection]) => {
if (!servers.find((s) => s.id === id)) {
if (
!servers.find(
// Refresh the connection if TransportOptions changed
(s) =>
s.id === id &&
this.compareTransportOptions(
connection.options.transport,
s.transport,
),
)
) {
refresh = true;
connection.abortController.abort();
void connection.client.close();
@ -61,6 +76,12 @@ export class MCPManagerSingleton {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
} else {
const conn = this.connections.get(server.id);
if (conn) {
// We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
conn.options = server;
}
}
});
@ -70,6 +91,37 @@ export class MCPManagerSingleton {
}
}
private compareTransportOptions(
a: TransportOptions,
b: TransportOptions,
): boolean {
if (a.type !== b.type) {
return false;
}
if (a.type === "stdio" && b.type === "stdio") {
return (
a.command === b.command &&
JSON.stringify(a.args) === JSON.stringify(b.args) &&
this.compareEnv(a, b)
);
} else if (a.type !== "stdio" && b.type !== "stdio") {
return a.url === b.url;
}
return false;
}
private compareEnv(a: StdioOptions, b: StdioOptions): boolean {
const aEnv = a.env ?? {};
const bEnv = b.env ?? {};
const aKeys = Object.keys(aEnv);
const bKeys = Object.keys(bEnv);
return (
aKeys.length === bKeys.length &&
aKeys.every((key) => aEnv[key] === bEnv[key])
);
}
async refreshConnection(serverId: string) {
const connection = this.connections.get(serverId);
if (!connection) {

View file

@ -1,7 +1,9 @@
import isLocalhost from "is-localhost-ip";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
IDE,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
@ -14,6 +16,19 @@ class HttpContextProvider extends BaseContextProvider {
renderInlineAs: "",
};
private async getWorkspacePath(ide: IDE, url: URL) {
try {
const currentFile = await ide.getCurrentFile();
// `isLocalhost` actually also returns true for other local addresses, not just localhost
return await isLocalhost(url.hostname) ?
(await ide.getWorkspaceDirs()).find(workspaceDirectory => {
return currentFile?.path.startsWith(workspaceDirectory)
}) : undefined
} catch (e) {
return undefined;
}
}
override get description(): ContextProviderDescription {
return {
title: this.options.title || HttpContextProvider.description.title,
@ -34,7 +49,8 @@ class HttpContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const response = await extras.fetch(new URL(this.options.url), {
const parsedUrl = new URL(this.options.url)
const response = await extras.fetch(parsedUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -44,6 +60,7 @@ class HttpContextProvider extends BaseContextProvider {
query: query || "",
fullInput: extras.fullInput,
options: this.options.options,
workspacePath: await this.getWorkspacePath(extras.ide, parsedUrl),
}),
});

View file

@ -68,7 +68,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
const cleanedTokens = [...tokens].join(" ");
const trigrams = nlp.string.ngram(cleanedTokens, 3);
return trigrams;
return trigrams.map(this.escapeFtsQueryString);
}
private escapeFtsQueryString(query: string): string {
@ -84,9 +84,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
return [];
}
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
const tokens = this.escapeFtsQueryString(tokensRaw);
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
return await this.ftsIndex.retrieve({
n,
text: tokens,

View file

@ -57,6 +57,7 @@ import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { LLMError } from "./llm";
import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
@ -682,59 +683,44 @@ export class Core {
}
});
on(
"tools/call",
async ({ data: { toolCall, selectedModelTitle }, messageId }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
on("tools/call", async ({ data: { toolCall } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config.tools.find(
(t) => t.function.name === toolCall.function.name,
);
const tool = config.tools.find(
(t) => t.function.name === toolCall.function.name,
);
if (!tool) {
throw new Error(`Tool ${toolCall.function.name} not found`);
}
if (!tool) {
throw new Error(`Tool ${toolCall.function.name} not found`);
}
if (!config.selectedModelByRole.chat) {
throw new Error("No chat model selected");
}
if (!config.selectedModelByRole.chat) {
throw new Error("No chat model selected");
}
// Define a callback for streaming output updates
const onPartialOutput = (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => {
this.messenger.send("toolCallPartialOutput", params);
};
// Define a callback for streaming output updates
const onPartialOutput = (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => {
this.messenger.send("toolCallPartialOutput", params);
};
const contextItems = await callTool(
tool,
JSON.parse(toolCall.function.arguments || "{}"),
{
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
toolCallId: toolCall.id,
onPartialOutput,
},
);
return await callTool(tool, toolCall.function.arguments, {
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
toolCallId: toolCall.id,
onPartialOutput,
});
});
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;
});
}
return { contextItems };
},
);
on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => {
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
});
@ -754,19 +740,16 @@ export class Core {
private async isItemTooBig(item: ContextItemWithId) {
const { config } = await this.configHandler.loadConfig();
if (!config) {
return false;
}
const llm = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
const llm = config?.selectedModelByRole.chat;
if (!llm) {
throw new Error("No chat model selected");
}
const tokens = countTokens(item.content);
const tokens = countTokens(item.content, llm.model);
if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
return true;
@ -838,7 +821,8 @@ export class Core {
if (
uri.endsWith(".continuerc.json") ||
uri.endsWith(".prompt") ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE)
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") && uri.endsWith(".yaml"))
) {
await this.configHandler.reloadConfig();
} else if (
@ -932,7 +916,6 @@ export class Core {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
selectedModelTitle: string;
}>,
) => {
const { config } = await this.configHandler.loadConfig();
@ -1050,25 +1033,23 @@ export class Core {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
for await (const update of (await this.codebaseIndexerPromise).refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
let updateToSend = { ...update };
// TODO reconsider this status overwrite?
// original goal was to not concern users with edge noncritical errors
if (update.status === "failed") {
updateToSend.status = "done";
updateToSend.desc = "Indexing complete";
updateToSend.progress = 1.0;
}
try {
for await (const update of (await this.codebaseIndexerPromise).refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index directories : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
@ -1086,22 +1067,22 @@ export class Core {
return;
}
this.indexingCancellationController = new AbortController();
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
files,
)) {
let updateToSend = { ...update };
if (update.status === "failed") {
updateToSend.status = "done";
updateToSend.desc = "Indexing complete";
updateToSend.progress = 1.0;
}
try{
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
files,
)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index files : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
@ -1111,4 +1092,19 @@ export class Core {
}
// private
handleIndexingError(e: any) {
if (e instanceof LLMError) {
// Need to report this specific error to the IDE for special handling
this.messenger.request("reportError", e);
}
// broadcast indexing error
let updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.sendIndexingErrorTelemetry(updateToSend);
}
}

View file

@ -4,6 +4,7 @@ import {
ILLM,
Prediction,
RuleWithSource,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import {
@ -104,18 +105,18 @@ export async function* streamDiffLines({
// Rules will be included with edit prompt
// If any rules are present this will result in using chat instead of legacy completion
const lastUserMessage: UserChatMessage | undefined =
const lastUserMessage =
typeof prompt === "string"
? {
? ({
role: "user",
content: prompt,
}
: (findLast(prompt, (msg) => msg.role === "user") as
| UserChatMessage
| undefined);
} as UserChatMessage)
: (findLast(
prompt,
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined);
const systemMessage = getSystemMessageWithRules({
currentModel: llm.model,
rules,
userMessage: lastUserMessage,
baseSystemMessage: undefined,

14
core/index.d.ts vendored
View file

@ -1,4 +1,8 @@
import { DataDestination, ModelRole, PromptTemplates } from "@continuedev/config-yaml";
import {
DataDestination,
ModelRole,
PromptTemplates,
} from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { LLMConfigurationStatuses } from "./llm/constants";
import { GetGhTokenArgs } from "./protocol/ide";
@ -153,6 +157,10 @@ export interface ModelInstaller {
signal: AbortSignal,
progressReporter?: (task: string, increment: number, total: number) => void,
): Promise<any>;
isInstallingModel(
modelName: string
): Promise<boolean>;
}
export type ContextProviderType = "normal" | "query" | "submenu";
@ -428,6 +436,7 @@ export type ToolStatus =
| "generating"
| "generated"
| "calling"
| "errored"
| "done"
| "canceled";
@ -1211,6 +1220,7 @@ export type EditStatus =
| "done";
export type ApplyStateStatus =
| "not-started" // Apply state created but not necessarily streaming
| "streaming" // Changes are being applied to the file
| "done" // All changes have been applied, awaiting user to accept/reject
| "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed"
@ -1501,7 +1511,7 @@ export interface RuleWithSource {
| "rules-block"
| "json-systemMessage"
| ".continuerules";
if?: string;
globs?: string | string[];
rule: string;
description?: string;
ruleFile?: string;

View file

@ -7,6 +7,8 @@ import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceIn
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { LLMError } from "../llm/index.js";
import { getRootCause } from "../util/errors.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
@ -350,6 +352,10 @@ export class CodebaseIndexer {
): IndexingProgressUpdate {
console.log("error when indexing: ", err);
if (err instanceof Error) {
const cause = getRootCause(err);
if (cause instanceof LLMError) {
throw cause;
}
return this.errorToProgressUpdate(err);
}
return {
@ -361,7 +367,8 @@ export class CodebaseIndexer {
}
private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
let errMsg: string = `${err}`;
const cause = getRootCause(err);
let errMsg: string = `${cause}`;
let shouldClearIndexes = false;
// Check if any of the error regexes match

View file

@ -36,6 +36,7 @@ import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import type * as LanceType from "vectordb";
import { LLMError } from "../../llm";
import { DocsCache, SiteIndexingResults } from "./DocsCache";
// Purposefully lowercase because lancedb converts
@ -421,6 +422,7 @@ export default class DocsService {
return false;
}
// eslint-disable-next-line max-statements
async indexAndAdd(
siteIndexingConfig: SiteIndexingConfig,
forceReindex: boolean = false,
@ -506,6 +508,16 @@ export default class DocsService {
try {
await provider.embed(["continue-test-run"]);
} catch (e) {
if (e instanceof LLMError) {
// Report the error to the IDE
this.messenger?.request("reportError", e);
}
this.handleStatusUpdate({
...fixedStatus,
description: `Failed to test embeddings connection. ${e}`,
status: "failed",
progress: 1,
});
console.error("Failed to test embeddings connection", e);
return;
}

View file

@ -95,6 +95,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"pixtral",
"llama3.2",
"llama-3.2",
"llama4"
];
function modelSupportsTools(modelDescription: ModelDescription) {
@ -175,7 +176,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
lower.includes("pplx") ||
lower.includes("gemini") ||
lower.includes("grok") ||
lower.includes("moonshot")
lower.includes("moonshot") ||
lower.includes("mercury")
) {
return undefined;
}

View file

@ -7,26 +7,6 @@ const DEFAULT_ARGS = {
temperature: DEFAULT_TEMPERATURE,
};
const GPT_4_CTX_LEN = 128_000;
const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
"gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-0613": 4096,
"gpt-3.5-turbo-16k": 16_384,
"gpt-35-turbo-16k": 16_384,
"gpt-35-turbo-0613": 4096,
"gpt-35-turbo": 4096,
"gpt-4": 4096,
"gpt-4-32k": 32_000,
"gpt-4-turbo-preview": 32_000,
"gpt-4o": GPT_4_CTX_LEN,
"gpt-4o-mini": GPT_4_CTX_LEN,
"gpt-4-vision": GPT_4_CTX_LEN,
"gpt-4-0125-preview": GPT_4_CTX_LEN,
"gpt-4-1106-preview": GPT_4_CTX_LEN,
};
const TOKEN_BUFFER_FOR_SAFETY = 350;
const PROXY_URL = "http://localhost:65433";
const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
@ -38,12 +18,10 @@ export enum LLMConfigurationStatuses {
}
export {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_BATCH_SIZE,
DEFAULT_MAX_CHUNK_SIZE,
DEFAULT_MAX_TOKENS,
PROXY_URL,
TOKEN_BUFFER_FOR_SAFETY,
};

View file

@ -3,15 +3,16 @@ import {
ChatMessage,
RuleWithSource,
TextMessagePart,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import { messageIsEmpty } from "./messages";
import { isUserOrToolMsg } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L8";
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
@ -57,14 +58,10 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
of changes unless the user specifically asks for code only.
</important_rules>`;
const CANCELED_TOOL_CALL_MESSAGE =
"This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool.";
export function constructMessages(
history: ChatHistoryItem[],
baseChatSystemMessage: string | undefined,
rules: RuleWithSource[],
modelName: string,
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
@ -92,26 +89,22 @@ export function constructMessages(
...historyItem.message,
content,
});
} else if (historyItem.toolCallState?.status === "canceled") {
// Canceled tool call
msgs.push({
...historyItem.message,
content: CANCELED_TOOL_CALL_MESSAGE,
});
} else {
msgs.push(historyItem.message);
}
}
const userMessage = findLast(msgs, (msg) => msg.role === "user") as
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
| UserChatMessage
| ToolResultChatMessage
| undefined;
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
rules,
userMessage,
currentModel: modelName,
userMessage: lastUserMsg,
});
if (systemMessage.trim()) {
msgs.unshift({
role: "system",
@ -119,16 +112,6 @@ export function constructMessages(
});
}
// We dispatch an empty assistant chat message to the history on submission. Don't send it
const lastMessage = msgs.at(-1);
if (
lastMessage &&
lastMessage.role === "assistant" &&
messageIsEmpty(lastMessage)
) {
msgs.pop();
}
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const { id, ...rest } = msg as any;

View file

@ -1,6 +1,6 @@
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
import { renderChatMessage } from "../util/messageContent.js";
import {
@ -9,13 +9,13 @@ import {
LlamaAsyncEncoder,
} from "./asyncEncoder.js";
import { autodetectTemplateType } from "./autodetect.js";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
import llamaTokenizer from "./llamaTokenizer.js";
import {
addSpaceToAnyEmptyMessages,
chatMessageIsEmpty,
flattenMessages,
messageHasToolCalls,
isUserOrToolMsg,
messageHasToolCallId,
} from "./messages.js";
interface Encoding {
encode: Tiktoken["encode"];
@ -124,6 +124,51 @@ function countTokens(
}
}
// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10
function countToolsTokens(tools: Tool[], modelName: string): number {
const count = (value: string) =>
encodingForModel(modelName).encode(value).length;
let numTokens = 12;
for (const tool of tools) {
let functionTokens = count(tool.function.name);
if (tool.function.description) {
functionTokens += count(tool.function.description);
}
const props = tool.function.parameters?.properties;
if (props) {
for (const key in props) {
functionTokens += count(key);
const fields = props[key];
if (fields) {
const fieldType = fields["type"];
const fieldDesc = fields["description"];
const fieldEnum = fields["enum"];
if (fieldType && typeof fieldType === "string") {
functionTokens += 2;
functionTokens += count(fieldType);
}
if (fieldDesc && typeof fieldDesc === "string") {
functionTokens += 2;
functionTokens += count(fieldDesc);
}
if (fieldEnum && Array.isArray(fieldEnum)) {
functionTokens -= 3;
for (const e of fieldEnum) {
functionTokens += 3;
functionTokens += typeof e === "string" ? count(e) : 5;
}
}
}
}
}
numTokens += functionTokens;
}
return numTokens + 12;
}
function countChatMessageTokens(
modelName: string,
chatMessage: ChatMessage,
@ -131,8 +176,38 @@ function countChatMessageTokens(
// Doing simpler, safer version of what is here:
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
// every message follows <|im_start|>{role/name}\n{content}<|end|>\n
const TOKENS_PER_MESSAGE: number = 4;
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
const BASE_TOKENS = 4;
const TOOL_CALL_EXTRA_TOKENS = 10;
const TOOL_OUTPUT_EXTRA_TOKENS = 10;
let tokens = BASE_TOKENS;
if (chatMessage.content) {
tokens += countTokens(chatMessage.content, modelName);
}
if ("toolCalls" in chatMessage && chatMessage.toolCalls) {
for (const call of chatMessage.toolCalls) {
tokens += TOOL_CALL_EXTRA_TOKENS;
tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this
}
}
if (chatMessage.role === "thinking") {
if (chatMessage.redactedThinking) {
tokens += countTokens(chatMessage.redactedThinking, modelName);
}
if (chatMessage.signature) {
tokens += countTokens(chatMessage.signature, modelName);
}
}
if (chatMessage.role === "tool") {
tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety
if (chatMessage.toolCallId) {
tokens += countTokens(chatMessage.toolCallId, modelName);
}
}
return tokens;
}
function pruneLinesFromTop(
@ -193,6 +268,20 @@ function pruneStringFromTop(
return encoding.decode(tokens.slice(tokens.length - maxTokens));
}
const MAX_TOKEN_SAFETY_BUFFER = 1000;
const TOKEN_SAFETY_PROPORTION = 0.02;
function getTokenCountingBufferSafety(contextLength: number) {
return Math.min(
MAX_TOKEN_SAFETY_BUFFER,
contextLength * TOKEN_SAFETY_PROPORTION,
);
}
const MIN_RESPONSE_TOKENS = 1000;
function getMinResponseTokens(maxTokens: number) {
return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
}
function pruneRawPromptFromTop(
modelName: string,
contextLength: number,
@ -200,184 +289,36 @@ function pruneRawPromptFromTop(
tokensForCompletion: number,
): string {
const maxTokens =
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
contextLength -
tokensForCompletion -
getTokenCountingBufferSafety(contextLength);
return pruneStringFromTop(modelName, maxTokens, prompt);
}
function pruneRawPromptFromBottom(
modelName: string,
contextLength: number,
prompt: string,
tokensForCompletion: number,
): string {
const maxTokens =
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
return pruneStringFromBottom(modelName, maxTokens, prompt);
}
function summarize(message: ChatMessage): string {
return `${renderChatMessage(message).substring(0, 100)}...`;
}
function pruneChatHistory(
modelName: string,
msgs: ChatMessage[],
contextLength: number,
tokensForCompletion: number,
): ChatMessage[] {
// Move system message to 2nd to last to give it priority
const systemMessage = msgs.find((msg) => msg.role === "system");
const chatHistory: ChatMessage[] = msgs.filter(
(msg) => msg.role !== "system",
);
if (systemMessage) {
chatHistory.splice(-1, 0, systemMessage);
}
let totalTokens =
tokensForCompletion +
chatHistory.reduce((acc, message) => {
return acc + countChatMessageTokens(modelName, message);
}, 0);
// 0. Prune any messages that take up more than 1/3 of the context length
const zippedMessagesAndTokens: [ChatMessage, number][] = [];
// Zipped ChatMessage with its token counts
chatHistory.forEach((message) => {
const zippedItem: [ChatMessage, number] = [
message,
countTokens(message.content, modelName),
];
zippedMessagesAndTokens.push(zippedItem);
});
const zippedLongerThanOneThird = zippedMessagesAndTokens.filter(
([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3,
);
zippedLongerThanOneThird.sort(
(
[_messageA, tokensA]: [ChatMessage, number],
[_messageB, tokensB]: [ChatMessage, number],
) => {
return tokensB - tokensA;
},
);
const longerThanOneThird = zippedLongerThanOneThird.map(
([message, _token]: [ChatMessage, number]) => message,
);
const distanceFromThird = zippedLongerThanOneThird.map(
([_message, token]: [ChatMessage, number]) => token - contextLength / 3,
);
for (let i = 0; i < longerThanOneThird.length; i++) {
// Prune line-by-line from the top
const message = longerThanOneThird[i];
const content = renderChatMessage(message);
const deltaNeeded = totalTokens - contextLength;
const delta = Math.min(deltaNeeded, distanceFromThird[i]);
message.content = pruneStringFromTop(
modelName,
countTokens(message.content, modelName) - delta,
content,
);
totalTokens -= delta;
}
// 1. Replace beyond last 5 messages with summary
let i = 0;
while (totalTokens > contextLength && i < chatHistory.length - 5) {
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(summarize(message), modelName);
message.content = summarize(message);
i++;
}
// 2. Remove entire messages until the last 5
while (chatHistory.length > 5 && totalTokens > contextLength) {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
// 3. Truncate message in the last 5, except last 1
i = 0;
while (
totalTokens > contextLength &&
chatHistory.length > 0 &&
i < chatHistory.length - 1
) {
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(summarize(message), modelName);
message.content = summarize(message);
i++;
}
// 4. Remove entire messages in the last 5, except last 1
while (totalTokens > contextLength && chatHistory.length > 1) {
// If tool call/response detected prune both (can't have response with no call)
// TODO prune lines from tool response before pruning both messages
if (
chatHistory.length > 2 &&
messageHasToolCalls(chatHistory[0]) &&
chatHistory[1].role === "tool"
) {
const firstMessage = chatHistory.shift()!;
const secondMessage = chatHistory.shift()!;
totalTokens -= countTokens(firstMessage.content, modelName);
totalTokens -= countTokens(secondMessage.content, modelName);
} else {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
}
// 5. Truncate last message
if (totalTokens > contextLength && chatHistory.length > 0) {
const message = chatHistory[0];
message.content = pruneRawPromptFromTop(
modelName,
contextLength,
renderChatMessage(message),
tokensForCompletion,
);
totalTokens = contextLength;
}
// put system message back if applicable
if (
chatHistory.length > 1 &&
chatHistory[chatHistory.length - 2].role === "system"
) {
const movedSystemMessage = chatHistory.splice(-2, 1)[0];
chatHistory.unshift(movedSystemMessage);
}
return chatHistory;
}
/*
Goal: reconcile chat messages with available context length
Guidelines:
- Always keep last user message, system message, and tools
- Never allow tool output without the corresponding tool call
- Remove older messages first
*/
function compileChatMessages({
modelName,
msgs,
contextLength,
maxTokens,
supportsImages,
tools,
}: {
modelName: string;
msgs: ChatMessage[];
contextLength: number;
maxTokens: number;
supportsImages: boolean;
tools?: Tool[];
}): ChatMessage[] {
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
// If images not supported, convert MessagePart[] to string
if (!supportsImages) {
for (const msg of msgsCopy) {
@ -388,15 +329,118 @@ function compileChatMessages({
}
}
const history = pruneChatHistory(
modelName,
msgsCopy,
contextLength,
maxTokens + TOKEN_BUFFER_FOR_SAFETY,
);
// Extract system message
const systemMsg = msgsCopy.find((msg) => msg.role === "system");
msgsCopy = msgsCopy.filter((msg) => msg.role !== "system");
const flattenedHistory = flattenMessages(history);
// Remove any empty messages or non-user/tool trailing messages
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
while (msgsCopy.length > 1) {
if (isUserOrToolMsg(msgsCopy.at(-1))) {
break;
}
msgsCopy.pop();
}
const lastUserOrToolMsg = msgsCopy.pop();
if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
}
let lastToolCallsMsg: ChatMessage | undefined = undefined;
if (lastUserOrToolMsg.role === "tool") {
lastToolCallsMsg = msgsCopy.pop();
if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
throw new Error(
`Error parsing chat history: tool call found to match tool output for id ${lastUserOrToolMsg.toolCallId}`,
);
}
}
let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
if (lastToolCallsMsg) {
lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
}
// System message
let systemMsgTokens = 0;
if (systemMsg) {
systemMsgTokens = countChatMessageTokens(modelName, systemMsg);
}
// Tools
let toolTokens = 0;
if (tools) {
toolTokens = countToolsTokens(tools, modelName);
}
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
const minOutputTokens = getMinResponseTokens(maxTokens);
let inputTokensAvailable = contextLength;
// Leave space for output/safety
inputTokensAvailable -= countingSafetyBuffer;
inputTokensAvailable -= minOutputTokens;
// Non-negotiable messages
inputTokensAvailable -= toolTokens;
inputTokensAvailable -= systemMsgTokens;
inputTokensAvailable -= lastMessagesTokens;
// Make sure there's enough context for the non-excludable items
if (inputTokensAvailable < 0) {
throw new Error(
`Not enough context available to include the system message, last user message, and tools.
There must be at least ${minOutputTokens} tokens remaining for output.
Request had the following token counts:
- contextLength: ${contextLength}
- counting safety buffer: ${countingSafetyBuffer}
- tools: ~${toolTokens}
- system message: ~${systemMsgTokens}
- last user or tool + tool call message tokens: ~${lastMessagesTokens}
- max output tokens: ${maxTokens}`,
);
}
// Now remove messages till we're under the limit
let currentTotal = 0;
const historyWithTokens = msgsCopy.map((message) => {
const tokens = countChatMessageTokens(modelName, message);
currentTotal += tokens;
return {
...message,
tokens,
};
});
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
const message = historyWithTokens.shift()!;
currentTotal -= message.tokens;
// At this point make sure no latent tool response without corresponding call
while (historyWithTokens[0]?.role === "tool") {
const message = historyWithTokens.shift()!;
currentTotal -= message.tokens;
}
}
// Now reassemble
const reassembled: ChatMessage[] = [];
if (systemMsg) {
reassembled.push(systemMsg);
}
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
if (lastToolCallsMsg) {
reassembled.push(lastToolCallsMsg);
}
reassembled.push(lastUserOrToolMsg);
// Flatten the messages (combines adjacent similar messages)
const flattenedHistory = flattenMessages(reassembled);
return flattenedHistory;
}
@ -404,7 +448,6 @@ export {
compileChatMessages,
countTokens,
countTokensAsync,
flattenMessages,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,

View file

@ -40,7 +40,6 @@ import {
modelSupportsImages,
} from "./autodetect.js";
import {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_BATCH_SIZE,
@ -72,7 +71,7 @@ export class LLMError extends Error {
}
export function isModelInstaller(provider: any): provider is ModelInstaller {
return provider && typeof provider.installModel === "function";
return provider && typeof provider.installModel === "function" && typeof provider.isInstallingModel === "function";;
}
type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
@ -281,28 +280,6 @@ export abstract class BaseLLM implements ILLM {
return Promise.resolve([]);
}
private _compileChatMessages(
options: CompletionOptions,
messages: ChatMessage[],
) {
let contextLength = this.contextLength;
if (
options.model !== this.model &&
options.model in CONTEXT_LENGTH_FOR_MODEL
) {
contextLength =
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
}
return compileChatMessages({
modelName: options.model,
msgs: messages,
contextLength,
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
});
}
private _templatePromptLikeMessages(prompt: string): string {
if (!this.templateMessages) {
return prompt;
@ -879,7 +856,14 @@ export abstract class BaseLLM implements ILLM {
completionOptions = this._modifyCompletionOptions(completionOptions);
const messages = this._compileChatMessages(completionOptions, _messages);
const messages = compileChatMessages({
modelName: completionOptions.model,
msgs: _messages,
contextLength: this.contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
});
const prompt = this.templateMessages
? this.templateMessages(messages)

View file

@ -226,7 +226,11 @@ describe("LLM", () => {
apiKey: process.env.MISTRAL_API_KEY,
model: "codestral-latest",
}),
{ testFim: true, skip: false },
{
testFim: true,
skip: false,
testToolCall: true,
},
);
testLLM(
new Azure({

View file

@ -1,3 +1,4 @@
import { Mutex } from "async-mutex";
import { spawn } from "child_process";
import { LLMOptions, ModelInstaller } from "../../index.js";
import OpenAI from "./OpenAI.js";
@ -47,6 +48,9 @@ class Docker extends OpenAI implements ModelInstaller {
"deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M",
};
private static modelsBeingInstalled: Set<string> = new Set();
private static modelsBeingInstalledMutex = new Mutex();
constructor(options: LLMOptions) {
super(options);
@ -164,6 +168,16 @@ class Docker extends OpenAI implements ModelInstaller {
): Promise<any> {
const targetModel = this.modelMap[modelName] || modelName;
const release = await Docker.modelsBeingInstalledMutex.acquire();
try {
if (Docker.modelsBeingInstalled.has(modelName)) {
throw new Error(`Model '${modelName}' is already being installed.`);
}
Docker.modelsBeingInstalled.add(modelName);
} finally {
release();
}
try {
// Report starting the installation
progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100);
@ -184,12 +198,28 @@ class Docker extends OpenAI implements ModelInstaller {
return { success: true, stdout, stderr };
} catch (error) {
console.error(`Failed to install Docker model ${targetModel}:`, error);
// Fix: Type check the error before accessing message property
// Fix: Type check the error before accessing message property
const errorMessage =
error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to install Docker model ${targetModel}: ${errorMessage}`,
);
} finally {
const release = await Docker.modelsBeingInstalledMutex.acquire();
try {
Docker.modelsBeingInstalled.delete(modelName);
} finally {
release();
}
}
}
public async isInstallingModel(modelName: string): Promise<boolean> {
const release = await Docker.modelsBeingInstalledMutex.acquire();
try {
return Docker.modelsBeingInstalled.has(modelName);
} finally {
release();
}
}
}

View file

@ -18,13 +18,12 @@ import OpenAI from "./OpenAI.js";
class Inception extends OpenAI {
static providerName = "inception";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://copenhagen.api.inceptionlabs.ai/v1/",
model: "mercury-editor-small-experimental",
apiBase: "https://api.inceptionlabs.ai/v1/",
model: "mercury-coder-small",
completionOptions: {
temperature: 0.0,
maxTokens: 150,
presencePenalty: 1.5,
stop: ["\n\n", "\n \n", "<|endoftext|>"],
stop: ["<|endoftext|>"],
model: "mercury-editor-small-experimental", // Added model to fix TypeScript error
},
};
@ -45,13 +44,13 @@ class Inception extends OpenAI {
body: JSON.stringify({
model: options.model,
prompt: prefix,
suffix,
max_tokens: options.maxTokens,
suffix: suffix.trim() === "" ? "<|endoftext|>" : suffix,
max_tokens: options.maxTokens ?? 150, // Only want this for /fim, not chat
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stop: [...(options.stop ?? []), "\n\n", "\n \n"],
stream: true,
}),
headers: {
@ -62,6 +61,9 @@ class Inception extends OpenAI {
signal,
});
for await (const chunk of streamSse(resp)) {
if (!chunk.choices[0]) {
continue;
}
yield chunk.choices[0].text;
}
}

View file

@ -1,3 +1,4 @@
import { Mutex } from "async-mutex";
import { JSONSchema7, JSONSchema7Object } from "json-schema";
import {
@ -138,6 +139,9 @@ class Ollama extends BaseLLM implements ModelInstaller {
maxEmbeddingBatchSize: 64,
};
private static modelsBeingInstalled: Set<string> = new Set();
private static modelsBeingInstalledMutex = new Mutex();
private fimSupported: boolean = false;
constructor(options: LLMOptions) {
@ -592,33 +596,62 @@ class Ollama extends BaseLLM implements ModelInstaller {
if (!modelInfo) {
throw new Error(`'${modelName}' not found in the Ollama registry!`);
}
const response = await fetch(this.getEndpoint("api/pull"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ name: modelName }),
signal,
});
const reader = response.body?.getReader();
//TODO: generate proper progress based on modelInfo size
while (true) {
const { done, value } = (await reader?.read()) || {
done: true,
value: undefined,
};
if (done) {
break;
const release = await Ollama.modelsBeingInstalledMutex.acquire();
try {
if (Ollama.modelsBeingInstalled.has(modelName)) {
throw new Error(`Model '${modelName}' is already being installed.`);
}
Ollama.modelsBeingInstalled.add(modelName);
} finally {
release();
}
const chunk = new TextDecoder().decode(value);
const lines = chunk.split("\n").filter(Boolean);
for (const line of lines) {
const data = JSON.parse(line);
progressReporter?.(data.status, data.completed, data.total);
try {
const response = await fetch(this.getEndpoint("api/pull"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ name: modelName }),
signal,
});
const reader = response.body?.getReader();
//TODO: generate proper progress based on modelInfo size
while (true) {
const { done, value } = (await reader?.read()) || {
done: true,
value: undefined,
};
if (done) {
break;
}
const chunk = new TextDecoder().decode(value);
const lines = chunk.split("\n").filter(Boolean);
for (const line of lines) {
const data = JSON.parse(line);
progressReporter?.(data.status, data.completed, data.total);
}
}
} finally {
const release = await Ollama.modelsBeingInstalledMutex.acquire();
try {
Ollama.modelsBeingInstalled.delete(modelName);
} finally {
release();
}
}
}
public async isInstallingModel(modelName: string): Promise<boolean> {
const release = await Ollama.modelsBeingInstalledMutex.acquire();
try {
return Ollama.modelsBeingInstalled.has(modelName);
} finally {
release();
}
}
}

View file

@ -9,20 +9,17 @@ class SambaNova extends OpenAI {
};
private static MODEL_IDS: { [name: string]: string } = {
"qwen2.5-coder-32b": "Qwen2.5-Coder-32B-Instruct",
"llama4-scout": "Llama-4-Scout-17B-16E-Instruct",
"llama4-maverick": "Llama-4-Maverick-17B-128E-Instruct",
"llama3.3-70b": "Meta-Llama-3.3-70B-Instruct",
"llama3.1-8b": "Meta-Llama-3.1-8B-Instruct",
"llama3.1-70b": "Meta-Llama-3.1-70B-Instruct",
"llama3.1-405b": "Meta-Llama-3.1-405B-Instruct",
"llama3.1-tulu-405b": "Llama-3.1-Tulu-3-405B",
"llama3.2-1b": "Meta-Llama-3.2-1B-Instruct",
"llama3.2-3b": "Meta-Llama-3.2-3B-Instruct",
"llama3.2-11b": "Llama-3.2-11B-Vision-Instruct",
"llama3.2-90b": "Llama-3.2-90B-Vision-Instruct",
"qwen2.5-72b": "Qwen2.5-72B-Instruct",
"qwq-32b": "QwQ-32B-Preview",
"qwq-32b": "QwQ-32B",
"deepseek-r1-distill-llama-70b": "DeepSeek-R1-Distill-Llama-70B",
"deepseek-r1": "DeepSeek-R1",
"deepseek-v3": "DeepSeek-V3-0324",
};
protected _convertModelName(model: string) {

View file

@ -1,5 +1,5 @@
import { ChatMessage } from "..";
import { flattenMessages } from "./countTokens";
import { flattenMessages } from "./messages";
describe("flattenMessages", () => {
it("should return an empty array when given an empty array", () => {

View file

@ -49,6 +49,31 @@ export function addSpaceToAnyEmptyMessages(
});
}
export function isUserOrToolMsg(msg: ChatMessage | undefined): boolean {
if (!msg) {
return false;
}
return msg.role === "user" || msg.role === "tool";
}
export function isToolMessageForId(
msg: ChatMessage | undefined,
toolCallId: string,
): boolean {
return !!msg && msg.role === "tool" && msg.toolCallId === toolCallId;
}
export function messageHasToolCallId(
msg: ChatMessage | undefined,
toolCallId: string,
): boolean {
return (
!!msg &&
msg.role === "assistant" &&
!!msg.toolCalls?.find((call) => call.id === toolCallId)
);
}
export function chatMessageIsEmpty(message: ChatMessage): boolean {
switch (message.role) {
case "system":

View file

@ -0,0 +1,201 @@
import { RuleWithSource, UserChatMessage } from "../..";
import { getSystemMessageWithRules } from "./getSystemMessageWithRules";
describe("getSystemMessageWithRules", () => {
const baseSystemMessage = "Base system message";
const tsRule: RuleWithSource = {
name: "TypeScript Rule",
rule: "Follow TypeScript best practices",
globs: "**/*.ts?(x)",
source: "rules-block",
};
// Rule without pattern (always active)
const generalRule: RuleWithSource = {
name: "General Rule",
rule: "Always write clear comments",
source: "rules-block",
};
// Rule with a different pattern
const pythonRule: RuleWithSource = {
name: "Python Rule",
rule: "Follow PEP 8 guidelines",
globs: "**/*.py",
source: "rules-block",
};
it("should not include pattern-matched rules when no file paths are mentioned", () => {
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage: undefined,
rules: [tsRule],
});
expect(result).toBe(baseSystemMessage);
});
it("should include general rules (without matches) regardless of file paths", () => {
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage: undefined,
rules: [generalRule],
});
expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`);
});
it("should include only matching rules based on file paths", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
"```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
});
// Should include TS rule and general rule, but not Python rule
const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
it("should include multiple matching rules", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
"```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```\n```python test.py\nprint('hello')\n```",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
});
// Should include all rules
const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
it("should include only general rules when no paths match pattern-specific rules", () => {
const userMessage: UserChatMessage = {
role: "user",
content: "```ruby test.rb\nputs 'hello'\n```",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
});
// Should only include the general rule
const expected = `${baseSystemMessage}\n\n${generalRule.rule}`;
expect(result).toBe(expected);
});
it("should NOT match with comma-separated glob patterns", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
"```ts src/main.ts\nconsole.log('hello');\n```\n```ts tests/example.test.ts\ntest('should work', () => {});\n```",
};
// Rule with comma-separated glob patterns
const commaRule: RuleWithSource = {
name: "TypeScript Standards",
rule: "Use TypeScript best practices for comma-separated globs",
globs: "src/**/*.ts, tests/**/*.ts",
source: "rules-block",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [commaRule],
});
// With the current implementation, the comma-separated pattern is treated as a single string,
// so it won't match any of the file paths (minimatch doesn't support comma-separated patterns)
expect(result).toBe(baseSystemMessage);
});
it("should match with an array of glob patterns", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
"```ts src/main.ts\nconsole.log('hello');\n```\n```ts tests/example.test.ts\ntest('should work', () => {});\n```\n```ts config/settings.ts\nconst config = {};\n```",
};
// Rule with an array of glob patterns
const arrayGlobRule: RuleWithSource = {
name: "TypeScript Standards",
rule: "Use TypeScript best practices for array globs",
globs: ["src/**/*.ts", "tests/**/*.ts"],
source: "rules-block",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
});
// With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts
expect(result).toBe(`${baseSystemMessage}\n\n${arrayGlobRule.rule}`);
});
it("should match only patterns in the array", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
"```ts src/main.ts\nconsole.log('hello');\n```\n```ts config/settings.ts\nconst config = {};\n```",
};
// Rule with an array of glob patterns
const arrayGlobRule: RuleWithSource = {
name: "TypeScript Standards",
rule: "Use TypeScript best practices for array globs",
globs: ["src/**/*.ts", "tests/**/*.ts"],
source: "rules-block",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
});
// Should match src/main.ts but not config/settings.ts
expect(result).toBe(`${baseSystemMessage}\n\n${arrayGlobRule.rule}`);
});
it("should not match any when no patterns in the array match", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
"```ts config/settings.ts\nconst config = {};\n```\n```ruby test.rb\nputs 'hello'\n```",
};
// Rule with an array of glob patterns
const arrayGlobRule: RuleWithSource = {
name: "TypeScript Standards",
rule: "Use TypeScript best practices for array globs",
globs: ["src/**/*.ts", "tests/**/*.ts"],
source: "rules-block",
};
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
});
// Should not match any file paths
expect(result).toBe(baseSystemMessage);
});
});

View file

@ -1,32 +1,52 @@
import { RuleWithSource, UserChatMessage } from "../..";
import { minimatch } from "minimatch";
import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
import { isRuleActive } from "./isRuleActive";
/**
* Checks if a path matches any of the provided globs
*/
const matchesGlobs = (
path: string,
globs: string | string[] | undefined,
): boolean => {
if (!globs) return true;
if (typeof globs === "string") {
return minimatch(path, globs);
}
if (Array.isArray(globs)) {
return globs.some((glob) => minimatch(path, glob));
}
return false;
};
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,
rules,
currentModel,
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | undefined;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
currentModel: string;
}) => {
const filePathsFromMessage = userMessage
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
: [];
let systemMessage = baseSystemMessage ?? "";
for (const rule of rules) {
if (
isRuleActive({
rule,
activePaths: filePathsFromMessage,
currentModel,
})
) {
// A rule is active if it has no globs (applies to all files)
// or if at least one file path matches its globs
const hasNoGlobs = !rule.globs;
const matchesAnyFilePath = filePathsFromMessage.some((path) =>
matchesGlobs(path, rule.globs),
);
if (hasNoGlobs || matchesAnyFilePath) {
systemMessage += `\n\n${rule.rule}`;
}
}

View file

@ -1,61 +0,0 @@
import { RuleWithSource } from "../..";
import { isRuleActive } from "./isRuleActive";
describe("isRuleActive", () => {
const rule: RuleWithSource = {
name: "My Rule",
rule: "Do no harm",
if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}',
source: "rules-block",
};
it("should return false when activePaths is empty", () => {
expect(
isRuleActive({
rule,
activePaths: [],
currentModel: "claude-3-7-sonnet",
}),
).toBe(false);
});
it("should return false when no matching paths exist", () => {
expect(
isRuleActive({
rule,
activePaths: ["test.py", "main.js"],
currentModel: "claude-3-7-sonnet",
}),
).toBe(false);
});
it("should return true when both conditions are met", () => {
expect(
isRuleActive({
rule,
activePaths: ["Component.tsx", "main.js"],
currentModel: "claude-3-7-sonnet",
}),
).toBe(true);
});
it("should return false when only glob matches but model doesn't", () => {
expect(
isRuleActive({
rule,
activePaths: ["Component.tsx"],
currentModel: "gpt-4",
}),
).toBe(false);
});
it("should return false when model matches but glob doesn't", () => {
expect(
isRuleActive({
rule,
activePaths: ["Component.ts"],
currentModel: "claude-3-7-sonnet",
}),
).toBe(false);
});
});

View file

@ -1,64 +0,0 @@
import { compileExpression } from "filtrex";
import { minimatch } from "minimatch";
import { RuleWithSource } from "../..";
const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/;
const createGlobFunction = (activePaths: string[]) => {
return (pattern: string) => {
const result = activePaths.some((path) => minimatch(path, pattern));
return result;
};
};
const contains = (str: string, searchStr: string): boolean => {
return str.includes(searchStr);
};
const evaluateIf = ({
condition,
activePaths,
currentModel,
}: {
condition: string;
activePaths: string[];
currentModel: string;
}) => {
const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim();
if (!expression) {
return true;
}
try {
const evaluate = compileExpression(expression, {
extraFunctions: {
glob: createGlobFunction(activePaths),
contains,
},
constants: {
"current.model.model": currentModel,
},
});
return evaluate({});
} catch (error) {
console.error("Error evaluating rule condition:", error);
return false;
}
};
export const isRuleActive = ({
rule,
activePaths,
currentModel,
}: {
rule: RuleWithSource;
activePaths: string[];
currentModel: string;
}): boolean => {
if (rule.if) {
return evaluateIf({ condition: rule.if, activePaths, currentModel });
}
return true;
};

View file

@ -143,6 +143,36 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
});
});
describe("mistral", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["mistral"];
it("should return true for supported models", () => {
expect(supportsFn("mistral-large-latest")).toBe(true);
expect(supportsFn("mistral-small-latest")).toBe(true);
expect(supportsFn("codestral-latest")).toBe(true);
expect(supportsFn("ministral-8b-latest")).toBe(true);
expect(supportsFn("ministral-3b-latest")).toBe(true);
expect(supportsFn("pixtral-12b-2409")).toBe(true);
expect(supportsFn("pixtral-large-latest")).toBe(true);
expect(supportsFn("open-mistral-nemo")).toBe(true);
});
it("should return false for other unsupported models", () => {
expect(supportsFn("mistral-saba-latest")).toBe(false);
expect(supportsFn("mistral-embed")).toBe(false);
expect(supportsFn("mistral-moderation-latest")).toBe(false);
expect(supportsFn("mistral-ocr-latest")).toBe(false);
expect(supportsFn("open-codestral-mamba")).toBe(false);
});
it("should handle case insensitivity", () => {
expect(supportsFn("MISTRAL-LARGE-LATEST")).toBe(true);
expect(supportsFn("CODESTRAL-LATEST")).toBe(true);
expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true);
expect(supportsFn("PIXTRAL-12B-2409")).toBe(true);
});
});
describe("ollama", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["ollama"];

View file

@ -79,6 +79,18 @@ export const PROVIDER_TOOL_SUPPORT: Record<
return true;
}
},
mistral: (model) => {
// https://docs.mistral.ai/capabilities/function_calling/
return !model.toLowerCase().includes("mamba") &&
[
"codestral",
"mistral-large",
"mistral-small",
"pixtral",
"ministral",
"mistral-nemo"
].some((part) => model.toLowerCase().includes(part));
},
// https://ollama.com/search?c=tools
ollama: (model) => {
let modelName = "";
@ -125,7 +137,9 @@ export const PROVIDER_TOOL_SUPPORT: Record<
sambanova: (model) => {
// https://docs.sambanova.ai/cloud/docs/capabilities/function-calling
if (
model.toLowerCase().startsWith("meta-llama-3")
model.toLowerCase().startsWith("meta-llama-3") ||
model.toLowerCase().includes("llama-4") ||
model.toLowerCase().includes("deepseek")
) {
return true;
}

352
core/package-lock.json generated
View file

@ -16,7 +16,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.18",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -39,6 +39,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
@ -71,6 +72,7 @@
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"winston": "^3.17.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.24.2"
@ -2902,6 +2904,14 @@
"node": ">=14.21.3"
}
},
"node_modules/@colors/colors": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz",
"integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==",
"engines": {
"node": ">=0.1.90"
}
},
"node_modules/@continuedev/config-types": {
"version": "1.0.14",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz",
@ -2932,31 +2942,42 @@
"integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw=="
},
"node_modules/@continuedev/openai-adapters": {
"version": "1.0.18",
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.18.tgz",
"integrity": "sha512-VkYNhW+XKVXnn5FTLCGoJkcejkDWSCUvvIS6WnYusmS1+W5MJBFZQ5q6O/WA17U0UF9Xou81RWfCltYs4fXnyQ==",
"version": "1.0.19",
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.19.tgz",
"integrity": "sha512-9bfgTHPThRZAIn5T/zaWvKhMgVDFgpP3zr9DIkBT5THRNIrbbWd6VrguNEp9ASlX85ohNiXnk+jiC/FfFcH++w==",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.3",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
"openai": "^4.76.0",
"uuid": "^11.1.0",
"zod": "^3.24.2"
}
},
"node_modules/@continuedev/openai-adapters/node_modules/@continuedev/config-yaml": {
"version": "1.0.86",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.86.tgz",
"integrity": "sha512-X0H1iPunFcqxgTcoS87EvbqNHjfkfidWt8rQ2CU5A8iBzPSDI/jdkok0Bm0MjgzgZuXbR6GxvwMcZcOTiFw1nA==",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
"node_modules/@continuedev/openai-adapters/node_modules/uuid": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"bin": {
"config-yaml": "dist/cli.js"
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/@dabh/diagnostics": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
"integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==",
"dependencies": {
"colorspace": "1.1.x",
"enabled": "2.0.x",
"kuler": "^2.0.0"
}
},
"node_modules/@esbuild/darwin-arm64": {
@ -3845,9 +3866,10 @@
}
},
"node_modules/@octokit/endpoint": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.5.tgz",
"integrity": "sha512-ekqR4/+PCLkEBF6qgj8WqJfvDq65RH85OAgrtnVp1mSxaXF03u2xW/hUdweGS5654IlC0wkNYC18Z50tSYTAFw==",
"version": "9.0.6",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz",
"integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==",
"license": "MIT",
"dependencies": {
"@octokit/types": "^13.1.0",
"universal-user-agent": "^6.0.0"
@ -3917,12 +3939,13 @@
}
},
"node_modules/@octokit/request": {
"version": "8.4.0",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.0.tgz",
"integrity": "sha512-9Bb014e+m2TgBeEJGEbdplMVWwPmL1FPtggHQRkV+WVsMggPtEkLKPlcVYm/o8xKLkpJ7B+6N8WfQMtDLX2Dpw==",
"version": "8.4.1",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz",
"integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==",
"license": "MIT",
"dependencies": {
"@octokit/endpoint": "^9.0.1",
"@octokit/request-error": "^5.1.0",
"@octokit/endpoint": "^9.0.6",
"@octokit/request-error": "^5.1.1",
"@octokit/types": "^13.1.0",
"universal-user-agent": "^6.0.0"
},
@ -3931,9 +3954,10 @@
}
},
"node_modules/@octokit/request-error": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.0.tgz",
"integrity": "sha512-GETXfE05J0+7H2STzekpKObFe765O5dlAKUTLNGeH+x47z7JjXHfsHKo5z21D/o/IOZTUEI6nyWyR+bZVP/n5Q==",
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz",
"integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==",
"license": "MIT",
"dependencies": {
"@octokit/types": "^13.1.0",
"deprecation": "^2.0.0",
@ -4983,6 +5007,11 @@
"integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==",
"dev": true
},
"node_modules/@types/triple-beam": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
"integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw=="
},
"node_modules/@types/uuid": {
"version": "9.0.8",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz",
@ -5629,8 +5658,7 @@
"node_modules/async": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"dev": true
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="
},
"node_modules/async-mutex": {
"version": "0.5.0",
@ -5852,44 +5880,75 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
},
"node_modules/bare-events": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.0.tgz",
"integrity": "sha512-/E8dDe9dsbLyh2qrZ64PEPadOQ0F4gbl1sUJOrmph7xOiIxfY8vwab/4bFLh4Y88/Hk/ujKcrQKc+ps0mv873A==",
"version": "2.5.4",
"resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz",
"integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==",
"license": "Apache-2.0",
"optional": true
},
"node_modules/bare-fs": {
"version": "2.3.5",
"resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-2.3.5.tgz",
"integrity": "sha512-SlE9eTxifPDJrT6YgemQ1WGFleevzwY+XAP1Xqgl56HtcrisC2CHCZ2tq6dBpcH2TnNxwUEUGhweo+lrQtYuiw==",
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.3.tgz",
"integrity": "sha512-OeEZYIg+2qepaWLyphaOXHAHKo3xkM8y3BeGAvHdMN8GNWvEAU1Yw6rYpGzu/wDDbKxgEjVeVDpgGhDzaeMpjg==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"bare-events": "^2.0.0",
"bare-path": "^2.0.0",
"bare-stream": "^2.0.0"
"bare-events": "^2.5.4",
"bare-path": "^3.0.0",
"bare-stream": "^2.6.4"
},
"engines": {
"bare": ">=1.16.0"
},
"peerDependencies": {
"bare-buffer": "*"
},
"peerDependenciesMeta": {
"bare-buffer": {
"optional": true
}
}
},
"node_modules/bare-os": {
"version": "2.4.4",
"resolved": "https://registry.npmjs.org/bare-os/-/bare-os-2.4.4.tgz",
"integrity": "sha512-z3UiI2yi1mK0sXeRdc4O1Kk8aOa/e+FNWZcTiPB/dfTWyLypuE99LibgRaQki914Jq//yAWylcAt+mknKdixRQ==",
"optional": true
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz",
"integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==",
"license": "Apache-2.0",
"optional": true,
"engines": {
"bare": ">=1.14.0"
}
},
"node_modules/bare-path": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/bare-path/-/bare-path-2.1.3.tgz",
"integrity": "sha512-lh/eITfU8hrj9Ru5quUp0Io1kJWIk1bTjzo7JH1P5dWmQ2EL4hFUlfI8FonAhSlgIfhn63p84CDY/x+PisgcXA==",
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz",
"integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"bare-os": "^2.1.0"
"bare-os": "^3.0.1"
}
},
"node_modules/bare-stream": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.4.2.tgz",
"integrity": "sha512-XZ4ln/KV4KT+PXdIWTKjsLY+quqCaEtqqtgGJVPw9AoM73By03ij64YjepK0aQvHSWDb6AfAZwqKaFu68qkrdA==",
"version": "2.6.5",
"resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz",
"integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"streamx": "^2.20.0"
"streamx": "^2.21.0"
},
"peerDependencies": {
"bare-buffer": "*",
"bare-events": "*"
},
"peerDependenciesMeta": {
"bare-buffer": {
"optional": true
},
"bare-events": {
"optional": true
}
}
},
"node_modules/base64-js": {
@ -6453,6 +6512,37 @@
"color-support": "bin.js"
}
},
"node_modules/colorspace": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz",
"integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==",
"dependencies": {
"color": "^3.1.3",
"text-hex": "1.0.x"
}
},
"node_modules/colorspace/node_modules/color": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz",
"integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==",
"dependencies": {
"color-convert": "^1.9.3",
"color-string": "^1.6.0"
}
},
"node_modules/colorspace/node_modules/color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"dependencies": {
"color-name": "1.1.3"
}
},
"node_modules/colorspace/node_modules/color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw=="
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@ -7080,9 +7170,9 @@
}
},
"node_modules/dotenv": {
"version": "16.4.7",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz",
"integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==",
"version": "16.5.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz",
"integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==",
"engines": {
"node": ">=12"
},
@ -7173,6 +7263,11 @@
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="
},
"node_modules/enabled": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz",
"integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ=="
},
"node_modules/encoding": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz",
@ -8075,6 +8170,11 @@
"pend": "~1.2.0"
}
},
"node_modules/fecha": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
"integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw=="
},
"node_modules/fetch-blob": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
@ -8201,6 +8301,11 @@
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz",
"integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA=="
},
"node_modules/fn.name": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz",
"integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw=="
},
"node_modules/follow-redirects": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
@ -9429,6 +9534,15 @@
"integrity": "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==",
"optional": true
},
"node_modules/is-localhost-ip": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-localhost-ip/-/is-localhost-ip-2.0.0.tgz",
"integrity": "sha512-vlgs2cSgMOfnKU8c1ewgKPyum9rVrjjLLW2HBdL5i0iAJjOs8NY55ZBd/hqUTaYR0EO9CKZd3hVSC2HlIbygTQ==",
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/is-map": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",
@ -10937,6 +11051,11 @@
"node": ">=6"
}
},
"node_modules/kuler": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
"integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A=="
},
"node_modules/launchdarkly-eventsource": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/launchdarkly-eventsource/-/launchdarkly-eventsource-2.0.3.tgz",
@ -11096,6 +11215,22 @@
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="
},
"node_modules/logform": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz",
"integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==",
"dependencies": {
"@colors/colors": "1.6.0",
"@types/triple-beam": "^1.3.2",
"fecha": "^4.2.0",
"ms": "^2.1.1",
"safe-stable-stringify": "^2.3.1",
"triple-beam": "^1.3.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/long": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz",
@ -12103,6 +12238,14 @@
"wrappy": "1"
}
},
"node_modules/one-time": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz",
"integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==",
"dependencies": {
"fn.name": "1.x.x"
}
},
"node_modules/onetime": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
@ -12924,9 +13067,10 @@
}
},
"node_modules/prebuild-install/node_modules/tar-fs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
"integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
"license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",
@ -13746,6 +13890,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/safe-stable-stringify": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
"engines": {
"node": ">=10"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@ -14224,6 +14376,14 @@
"node": ">=8"
}
},
"node_modules/stack-trace": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
"integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==",
"engines": {
"node": "*"
}
},
"node_modules/stack-utils": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz",
@ -14530,16 +14690,17 @@
}
},
"node_modules/tar-fs": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.6.tgz",
"integrity": "sha512-iokBDQQkUyeXhgPYaZxmczGPhnhXZ0CmrqI+MOb/WFGS9DW5wnfrLgtjUJBvz50vQ3qfRwJ62QVoCFu8mPVu5w==",
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz",
"integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==",
"license": "MIT",
"dependencies": {
"pump": "^3.0.0",
"tar-stream": "^3.1.5"
},
"optionalDependencies": {
"bare-fs": "^2.1.1",
"bare-path": "^2.1.0"
"bare-fs": "^4.0.1",
"bare-path": "^3.0.0"
}
},
"node_modules/tar-stream": {
@ -14707,6 +14868,11 @@
"b4a": "^1.6.4"
}
},
"node_modules/text-hex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",
"integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg=="
},
"node_modules/text-table": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
@ -14775,6 +14941,14 @@
"tree-sitter-wasms": "^0.1.11"
}
},
"node_modules/triple-beam": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
"integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==",
"engines": {
"node": ">= 14.0.0"
}
},
"node_modules/ts-api-utils": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
@ -15582,6 +15756,66 @@
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="
},
"node_modules/winston": {
"version": "3.17.0",
"resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz",
"integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==",
"dependencies": {
"@colors/colors": "^1.6.0",
"@dabh/diagnostics": "^2.0.2",
"async": "^3.2.3",
"is-stream": "^2.0.0",
"logform": "^2.7.0",
"one-time": "^1.0.0",
"readable-stream": "^3.4.0",
"safe-stable-stringify": "^2.3.1",
"stack-trace": "0.0.x",
"triple-beam": "^1.3.0",
"winston-transport": "^4.9.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/winston-transport": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
"integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==",
"dependencies": {
"logform": "^2.7.0",
"readable-stream": "^3.6.2",
"triple-beam": "^1.3.0"
},
"engines": {
"node": ">= 12.0.0"
}
},
"node_modules/winston-transport/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/winston/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",

View file

@ -50,7 +50,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.18",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -73,6 +73,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
@ -105,6 +106,7 @@
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"winston": "^3.17.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.24.2"

View file

@ -101,7 +101,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
selectedModelTitle: string;
},
ContextItemWithId[],
];
@ -156,7 +155,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"chatDescriber/describe": [
{
selectedModelTitle: string;
text: string;
},
string | undefined,
@ -203,15 +201,12 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }];
"tools/call": [
{ toolCall: ToolCall; selectedModelTitle: string },
{ contextItems: ContextItem[] },
{ toolCall: ToolCall },
{ contextItems: ContextItem[]; errorMessage?: string },
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
isItemTooBig: [
{ item: ContextItemWithId; selectedModelTitle: string | undefined },
boolean,
];
isItemTooBig: [{ item: ContextItemWithId }, boolean];
didChangeControlPlaneSessionInfo: [
{ sessionInfo: ControlPlaneSessionInfo | undefined },
void,

View file

@ -99,6 +99,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
ControlPlaneSessionInfo | undefined,
];
logoutOfControlPlane: [undefined, void];
reportError:[any, void];
closeSidebar: [undefined, void];
};

View file

@ -17,3 +17,5 @@ export enum BuiltInToolNames {
}
export const BUILT_IN_GROUP_NAME = "Built-In";
export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile];

View file

@ -130,40 +130,72 @@ async function callToolFromUri(
}
}
// Handles calls for core/non-client tools
// Returns an error context item if the tool call fails
// Note: Edit tool is handled on client
export async function callTool(
tool: Tool,
args: any,
callArgs: string,
extras: ToolExtras,
): Promise<ContextItem[]> {
): Promise<{
contextItems: ContextItem[];
errorMessage: string | undefined;
}> {
const args = JSON.parse(callArgs || "{}");
const uri = tool.uri ?? tool.function.name;
switch (uri) {
case BuiltInToolNames.ReadFile:
return await readFileImpl(args, extras);
// Note: Custom GUI handling for edit
case BuiltInToolNames.CreateNewFile:
return await createNewFileImpl(args, extras);
case BuiltInToolNames.GrepSearch:
return await grepSearchImpl(args, extras);
case BuiltInToolNames.FileGlobSearch:
return await fileGlobSearchImpl(args, extras);
case BuiltInToolNames.RunTerminalCommand:
return await runTerminalCommandImpl(args, extras);
case BuiltInToolNames.SearchWeb:
return await searchWebImpl(args, extras);
case BuiltInToolNames.ViewDiff:
return await viewDiffImpl(args, extras);
case BuiltInToolNames.LSTool:
return await lsToolImpl(args, extras);
case BuiltInToolNames.ReadCurrentlyOpenFile:
return await readCurrentlyOpenFileImpl(args, extras);
case BuiltInToolNames.CreateRuleBlock:
return await createRuleBlockImpl(args, extras);
// case BuiltInToolNames.ViewRepoMap:
// return await viewRepoMapImpl(args, extras);
// case BuiltInToolNames.ViewSubdirectory:
// return await viewSubdirectoryImpl(args, extras);
default:
return await callToolFromUri(uri, args, extras);
try {
let contextItems: ContextItem[] = [];
switch (uri) {
case BuiltInToolNames.ReadFile:
contextItems = await readFileImpl(args, extras);
break;
case BuiltInToolNames.CreateNewFile:
contextItems = await createNewFileImpl(args, extras);
break;
case BuiltInToolNames.GrepSearch:
contextItems = await grepSearchImpl(args, extras);
break;
case BuiltInToolNames.FileGlobSearch:
contextItems = await fileGlobSearchImpl(args, extras);
break;
case BuiltInToolNames.RunTerminalCommand:
contextItems = await runTerminalCommandImpl(args, extras);
break;
case BuiltInToolNames.SearchWeb:
contextItems = await searchWebImpl(args, extras);
break;
case BuiltInToolNames.ViewDiff:
contextItems = await viewDiffImpl(args, extras);
break;
case BuiltInToolNames.LSTool:
contextItems = await lsToolImpl(args, extras);
break;
case BuiltInToolNames.ReadCurrentlyOpenFile:
contextItems = await readCurrentlyOpenFileImpl(args, extras);
break;
case BuiltInToolNames.CreateRuleBlock:
contextItems = await createRuleBlockImpl(args, extras);
break;
default:
contextItems = await callToolFromUri(uri, args, extras);
}
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;
});
}
return {
contextItems,
errorMessage: undefined,
};
} catch (e) {
let errorMessage = `${e}`;
if (e instanceof Error) {
errorMessage = e.message;
}
return {
contextItems: [],
errorMessage,
};
}
}

View file

@ -4,32 +4,35 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const createRuleBlock: Tool = {
type: "function",
displayTitle: "Create Rule Block",
wouldLikeTo: 'create a rule block for "{{{ rule_name }}}"',
isCurrently: 'creating a rule block for "{{{ rule_name }}}"',
hasAlready: 'created a rule block for "{{{ rule_name }}}"',
wouldLikeTo: 'create a rule block for "{{{ name }}}"',
isCurrently: 'creating a rule block for "{{{ name }}}"',
hasAlready: 'created a rule block for "{{{ name }}}"',
readonly: false,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.CreateRuleBlock,
description:
"Creates a persistent rule that applies to all future conversations. " +
"Use for establishing ongoing code standards or preferences (e.g. 'use named exports', 'follow Google docstrings'). " +
"Not for one-time instructions. Rules are stored as YAML in `.continue/rules`.",
"Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently.",
parameters: {
type: "object",
required: ["rule_name", "rule_content"],
required: ["name", "rule"],
properties: {
rule_name: {
name: {
type: "string",
description:
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')",
},
rule_content: {
rule: {
type: "string",
description:
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
},
globs: {
type: "string",
description:
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
},
},
},
},

View file

@ -3,7 +3,7 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface EditToolArgs {
filepath: string;
new_contents: string;
changes: string;
}
export const editFileTool: Tool = {
@ -20,16 +20,17 @@ export const editFileTool: Tool = {
"Use this tool to edit an existing file. If you don't know the contents of the file, read it first.",
parameters: {
type: "object",
required: ["filepath", "new_contents"],
required: ["filepath", "changes"],
properties: {
filepath: {
type: "string",
description:
"The path of the file to edit, relative to the root of the workspace.",
},
new_contents: {
changes: {
type: "string",
description: "The new file contents",
description:
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock. Use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... rest of code here ...'",
},
},
},

View file

@ -0,0 +1,78 @@
import * as YAML from "yaml";
import { createRuleBlockImpl } from "./createRuleBlock";
// Mock the extras parameter with necessary functions
const mockIde = {
getWorkspaceDirs: jest.fn().mockResolvedValue(["/"]),
writeFile: jest.fn().mockResolvedValue(undefined),
openFile: jest.fn().mockResolvedValue(undefined),
};
const mockExtras = {
ide: mockIde,
};
describe("createRuleBlockImpl", () => {
beforeEach(() => {
jest.clearAllMocks();
});
it("should create a basic rule with name and rule content", async () => {
const args = {
name: "Test Rule",
rule: "Always write tests",
};
const result = await createRuleBlockImpl(args, mockExtras as any);
// Verify that writeFile was called with the correct YAML
expect(mockIde.writeFile).toHaveBeenCalled();
const yamlContent = mockIde.writeFile.mock.calls[0][1];
const parsedYaml = YAML.parse(yamlContent);
// Verify the structure of the YAML
expect(parsedYaml).toEqual({
name: "Test Rule",
version: "0.0.1",
schema: "v1",
rules: [
{
name: "Test Rule",
rule: "Always write tests",
},
],
});
});
it("should create a rule with glob pattern", async () => {
const args = {
name: "TypeScript Rule",
rule: "Use interfaces for object shapes",
globs: "**/*.{ts,tsx}",
};
await createRuleBlockImpl(args, mockExtras as any);
// Verify the YAML structure with globs
const yamlContent = mockIde.writeFile.mock.calls[0][1];
const parsedYaml = YAML.parse(yamlContent);
expect(parsedYaml.rules[0]).toEqual({
name: "TypeScript Rule",
rule: "Use interfaces for object shapes",
globs: "**/*.{ts,tsx}",
});
});
it("should create a filename based on sanitized rule name", async () => {
const args = {
name: "Special Ch@racters & Spaces",
rule: "Handle special characters",
};
await createRuleBlockImpl(args, mockExtras as any);
// Check that the filename is sanitized
const fileUri = mockIde.writeFile.mock.calls[0][0];
expect(fileUri).toContain("special-chracters-spaces.yaml");
});
});

View file

@ -4,8 +4,9 @@ import { ToolImpl } from ".";
import { joinPathsToUri } from "../../util/uri";
export interface CreateRuleBlockArgs {
rule_name: string;
rule_content: string;
name: string;
rule: string;
globs?: string;
}
export const createRuleBlockImpl: ToolImpl = async (
@ -13,22 +14,24 @@ export const createRuleBlockImpl: ToolImpl = async (
extras,
) => {
// Sanitize rule name for use in filename (remove special chars, replace spaces with dashes)
const safeRuleName = args.rule_name
const safeRuleName = args.name
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-");
const ruleBlock: ConfigYaml = {
name: args.rule_name,
version: "0.0.1",
rules: [
// This can be either a string or an object with {name, rule}
// Since we want a simple rule, we use the string format
args.rule_content,
],
const ruleObject = {
name: args.name,
rule: args.rule,
...(args.globs ? { globs: args.globs.trim() } : {}),
};
const ruleBlock: ConfigYaml = {
name: args.name,
version: "0.0.1",
schema: "v1",
rules: [ruleObject],
};
// Convert the rule block to YAML
const ruleYaml = YAML.stringify(ruleBlock);
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
@ -44,9 +47,13 @@ export const createRuleBlockImpl: ToolImpl = async (
return [
{
name: "Rule Block Created",
description: `Created ${args.rule_name} rule`,
content: ruleYaml,
name: "New Rule Block",
description: "", // No description throws an error in the GUI
uri: {
type: "file",
value: rulesDirUri,
},
content: "Rule created successfully",
},
];
};

13
core/util/errors.ts Normal file
View file

@ -0,0 +1,13 @@
/**
* Recursively retrieves the root cause of an error by traversing through its `cause` property.
*
* @param err - The error object to analyze. It can be of any type.
* @returns The root cause of the error, or the original error if no further cause is found.
*/
export function getRootCause(err: any): any {
if (err.cause) {
return getRootCause(err.cause);
}
return err;
}

14
core/util/logger.ts Normal file
View file

@ -0,0 +1,14 @@
import winston from "winston";
console.log("NODE_ENV", process.env.NODE_ENV);
export const logger = winston.createLogger({
level: "info",
format: winston.format.json(),
transports: [
// Write all logs with importance level of `info` or higher to `info.log`
new winston.transports.File({ filename: "e2e.log", level: "info" }),
// Normal console.log behavior
new winston.transports.Console(),
],
});

View file

@ -13,8 +13,16 @@ import Types from "../config/types";
dotenv.config();
const CONTINUE_GLOBAL_DIR =
process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue");
const CONTINUE_GLOBAL_DIR = (() => {
const configPath = process.env.CONTINUE_GLOBAL_DIR;
if (configPath) {
// Convert relative path to absolute paths based on current working directory
return path.isAbsolute(configPath)
? configPath
: path.resolve(process.cwd(), configPath);
}
return path.join(os.homedir(), ".continue");
})();
// export const DEFAULT_CONFIG_TS_CONTENTS = `import { Config } from "./types"\n\nexport function modifyConfig(config: Config): Config {
// return config;
@ -376,12 +384,16 @@ export function getPromptLogsPath(): string {
return path.join(getLogsDirPath(), "prompt.log");
}
export function getGlobalFolderWithName(name: string): string {
return path.join(getContinueGlobalPath(), name);
}
export function getGlobalPromptsPath(): string {
return path.join(getContinueGlobalPath(), "prompts");
return getGlobalFolderWithName("prompts");
}
export function getGlobalAssistantsPath(): string {
return path.join(getContinueGlobalPath(), "assistants");
return getGlobalFolderWithName("assistants");
}
export function readAllGlobalPromptFiles(

View file

@ -15,5 +15,6 @@ Currently the following providers are supported:
- [Ollama](../customize/model-providers/top-level/ollama.mdx) - we recommend [Qwen 2.5 Coder 7b](https://hub.continue.dev/ollama/qwen2.5-coder-7b). Also see all Ollama models that support tools [here](https://ollama.com/search?c=tools).
- [OpenAI](../customize/model-providers/top-level/openai.mdx) - we recommend [GPT-4o](https://hub.continue.dev/openai/gpt-4o)
- [Gemini](../customize/model-providers/top-level/gemini.mdx) - we recommend [Gemini 2.0 Flash](https://hub.continue.dev/google/gemini-2.0-flash)
- [Mistral](../customize/model-providers/top-level/mistral.mdx) - we recommend [Codestral](https://hub.continue.dev/mistral/codestral)
The best chat models generally support tool usage. See [recommended chat models](../customize/model-roles/chat.mdx#recommended-chat-models) for more.

View file

@ -0,0 +1,21 @@
---
title: Context Blocks
sidebar_label: Context
description: Determine what internal information your AI assistant can access
keywords: [context, blocks, repositories, integration, knowledge base]
sidebar_position: 2
---
These blocks determine what internal information your AI assistant can access:
- **Connect to source repositories** and issues, CI/CD systems, wikis, and knowledge bases
- **Determine the scope** of what the AI can "see" when providing assistance
- **Customize** to match your specific development environment
- **Include proprietary code patterns** unique to your organization
- **Integrate data sources** to connect to any internal system with valuable context
![Context Blocks Overview](/img/context-blocks-overview.png)
## Learn More
Learn more about context providers [here](../reference.md#context), and check out [this guide](../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider.

20
docs/docs/blocks/data.md Normal file
View file

@ -0,0 +1,20 @@
---
title: Data Blocks
sidebar_label: Data
description: Help organizations capture and analyze AI assistant usage data
keywords: [data, blocks, analytics, metrics, storage, compliance]
sidebar_position: 7
---
These help organizations capture and analyze AI assistant usage data:
- **Analytics Integration**: Export metrics to observability platforms like Splunk or New Relic
- **Cloud Storage**: Store development data in S3/Azure Blob for model fine-tuning and auditing
- **Impact Measurement**: Track acceptance rates and productivity outcomes for ROI calculation
- **Compliance Reporting**: Generate audit trails for security and governance requirements
![Data Blocks Overview](/img/data-blocks-overview.png)
## Learn More
You can read more about development data [here](../customize/deep-dives/development-data.md). Data destinations are configured in the [`data`](../reference.md#data) section of `config.yaml`.

19
docs/docs/blocks/docs.md Normal file
View file

@ -0,0 +1,19 @@
---
title: Docs Blocks
sidebar_label: Docs
description: Bring your documentation directly into the IDE
keywords: [docs, blocks, documentation, guidance, flow]
sidebar_position: 3
---
This is how Continue brings your documentation directly into the IDE:
- **Provide just-in-time guidance** without context switching
- **Reduce support burden** by making information discoverable
- **Keep developers in flow** by eliminating searches through multiple systems
![Docs Blocks Overview](/img/docs-blocks-overview.png)
## Learn More
Learn more in the [@Docs deep dive](../customize/deep-dives/docs.mdx), and view [`docs`](../reference.md#docs) in the YAML Reference for more details.

44
docs/docs/blocks/mcp.md Normal file
View file

@ -0,0 +1,44 @@
---
title: MCP Blocks
---
title: MCP Blocks
sidebar_label: MCP
description: Model Context Protocol servers provide specialized functionality
keywords: [mcp, blocks, model context protocol, integrations, tools]
sidebar_position: 4
---
Model Context Protocol servers provide specialized functionality:
- **Enable integration** with external tools and systems
- **Create extensible interfaces** for custom capabilities
- **Support complex interactions** with your development environment
- **Allow partners** to contribute specialized functionality
- **Connect to databases** to understand schema and data models during development
![MCP Blocks Overview](/img/mcp-blocks-overview.png)
## Learn More
Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../reference.md#mcpservers) in the YAML Reference for more details.
description: Model Context Protocol servers provide specialized functionality
keywords: [mcp, blocks, model context protocol, integrations, tools]
sidebar_position: 4
---
Model Context Protocol servers provide specialized functionality:
- Enable integration with external tools and systems
- Create extensible interfaces for custom capabilities
- Support more complex interactions with your development environment
- Allow partners to contribute specialized functionality
- Database Connectors: Understand schema and data models during development
![MCP Blocks Overview](/img/mcp-blocks-overview.png)
## Learn More
Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../reference.md#mcpservers) in the YAML Reference for more details.

View file

@ -0,0 +1,24 @@
---
title: Model Blocks
sidebar_label: Model
description: Foundation of the entire assistant experience offering specialized capabilities
keywords: [model, blocks, chat, edit, apply, autocomplete, embedding, reranker]
sidebar_position: 1
---
These blocks form the foundation of the entire assistant experience, offering different specialized capabilities:
- **[Chat](../customize/model-roles/chat.mdx)**: Power conversational interactions about code and provide detailed guidance
- **[Edit](../customize/model-roles/edit.mdx)**: Handle complex code transformations and refactoring tasks
- **[Apply](../customize/model-roles/apply.mdx)**: Execute targeted code modifications with high accuracy
- **[Autocomplete](../customize/model-roles/autocomplete.md)**: Provide real-time suggestions as developers type
- **[Embedding](../customize/model-roles/embeddings.mdx)**: Transform code into vector representations for semantic search
- **[Reranker](../customize/model-roles/reranking.mdx)**: Improve search relevance by ordering results based on semantic meaning
![Model Blocks Overview](/img/model-blocks-overview.png)
## Learn More
Continue supports [many model providers](../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
Read more about roles [here](../customize/model-roles/intro.mdx) and view [`models`](../reference.md#models) in the YAML Reference.

View file

@ -0,0 +1,21 @@
---
title: Prompt Blocks
sidebar_label: Prompt
description: Specialized instructions that shape how models respond
keywords: [prompts, blocks, instructions, guidance, code review]
sidebar_position: 6
---
These are the specialized instructions that shape how models respond:
- **Define interaction patterns** for specific tasks or frameworks
- **Encode domain expertise** for particular technologies
- **Ensure consistent guidance** aligned with organizational practices
- **Can be shared and reused** across multiple assistants
- **Act as automated code reviewers** that ensure consistency across teams
![Prompt Blocks Overview](/img/prompts-blocks-overview.png)
## Learn More
Prompt blocks have the same syntax as [prompt files](../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](../reference.md#prompts).

19
docs/docs/blocks/rules.md Normal file
View file

@ -0,0 +1,19 @@
---
title: Rules Blocks
sidebar_label: Rules
description: Guardrails for your AI coding assistants
keywords: [rules, blocks, standards, practices, guardrails]
sidebar_position: 5
---
Think of these as the guardrails for your AI coding assistants:
- **Enforce company-specific coding standards** and security practices
- **Implement quality checks** that match your engineering culture
- **Create paved paths** for developers to follow organizational best practices
![Rules Blocks Overview](/img/rules-blocks-overview.png)
## Learn More
Learn more in the [rules deep dive](../customize/deep-dives/rules.md), and view [`rules`](../reference.md#rules) in the YAML Reference for more details.

View file

@ -17,12 +17,14 @@ Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editi
Local user-level configuration is stored and can be edited in your home directory in `config.yaml`:
To open `config.yaml`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open Assistant configuration` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below.
- `~/.continue/config.yaml` (MacOS / Linux)
- `%USERPROFILE%\.continue\config.yaml` (Windows)
When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist.
To open this `config.yaml`, you need to open the assistants dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Assistant" option, select the cog icon. It will open the local `config.yaml`.
![local-config-open-steps](/img/local-config-open-steps.png)
When editing this file, you can see the available options suggested as you type, or check the reference below. When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist.
See the full reference for `config.yaml` [here](../../reference.md).

View file

@ -1,5 +1,5 @@
---
description: Learn how to customize the system prompt with a `.continuerules` file
description: Rules are used to provide instructions to the model for Chat, Edit, and Agent requests.
keywords: [rules, .continuerules, system, prompt, message]
---
@ -7,7 +7,7 @@ keywords: [rules, .continuerules, system, prompt, message]
Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests.
Rules are **_NOT_** included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx).
Rules are not included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx).
You can view the current rules by clicking the pen icon above the main toolbar:
@ -20,27 +20,36 @@ To form the system message, rules are joined with new lines, in the order they a
Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally.
:::info Automatically create local rule blocks
When in Agent mode, you can simply prompt the agent to create a rule for you.
When in Agent mode, you can simply prompt the agent to create a rule for you using the `builtin_create_rule_block` tool if enabled.
For example, you can say "Create a rule for this", and a rule will be created for you in `~/.continue/rules` based on your conversation.
For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation.
:::
### Syntax
Rules blocks can be simple text, or have the following properties:
- `name` (**required**): A display name/title for the rule
- `rule` (**required**): The text content of the rule
Examples:
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
```yaml title="config.yaml"
rules:
- Always annotate Python functions with their parameter and return types
- name: TypeScript best practices
rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly.
globs: "**/*.{ts,tsx}"
- name: TypeScript test patterns
rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking.
globs:
- "src/**/*.test.ts"
- "tests/**/*.ts"
- uses: myprofile/my-mood-setter
with:
TONE: consise
- Always annotate Python functions with their parameter and return types
- Always write Google style docstrings for functions and classes
- name: Server-side components
rule: When writing Next.js React components, use server-side components where possible instead of client components.
TONE: concise
```
## Chat System Message

View file

@ -9,9 +9,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: SambaNova Qwen2.5 coder
- name: SambaNova Llama 4 Scout
provider: sambanova
model: qwen2.5-coder-32b
model: Llama-4-Scout-17B-16E-Instruct
apiKey: <YOUR_SAMBANOVA_API_KEY>
```
</TabItem>
@ -20,9 +20,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor
{
"models": [
{
"title": "SambaNova Qwen2.5 coder",
"title": "SambaNova Llama 4 Scout",
"provider": "sambanova",
"model": "qwen2.5-coder-32b",
"model": "Llama-4-Scout-17B-16E-Instruct",
"apiKey": "<YOUR_SAMBANOVA_API_KEY>"
}
]

View file

@ -0,0 +1,36 @@
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
# Morph
Morph provides a fast apply model that helps you quickly and accurately apply code changes from chat suggestions to your files. It's optimized for speed and precision when integrating generated code into your existing codebase. You can sign up for Morph's generous free tier [here](https://morphllm.com/dashboard). Then, update your configuration file as follows:
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- uses: morphllm/morph-v0
with:
MORPH_API_KEY: ${{ secrets.MORPH_API_KEY }}
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"models": [
{
"title": "Morph Fast Apply",
"provider": "openai",
"model": "morph-v0",
"apiKey": "<YOUR_MORPH_API_KEY>",
"apiBase": "https://api.morphllm.com/v1/",
"roles": ["apply", "chat"],
"promptTemplates": {
"apply": "<code>{{{ original_code }}}</code>\n<update>{{{ new_code }}}</update>"
}
}
]
}
```
</TabItem>
</Tabs>

View file

@ -143,7 +143,7 @@ For example, a Target URI of `https://just-an-example.openai.azure.com/openai/de
models:
- name: GPT-4o Azure
model: gpt-4o
provider: openai
provider: azure
apiBase: https://just-an-example.openai.azure.com
apiKey: <YOUR_AZURE_API_KEY>
env:
@ -157,7 +157,7 @@ For example, a Target URI of `https://just-an-example.openai.azure.com/openai/de
{
"title": "GPT-4o Azure",
"model": "gpt-4o",
"provider": "openai",
"provider": "azure",
"apiBase": "https://just-an-example.openai.azure.com",
"deployment": "gpt-4o-july",
"apiVersion": "2023-03-15-preview",

View file

@ -0,0 +1,81 @@
---
title: Inception
slug: ../inception
---
import TabItem from "@theme/TabItem";
import Tabs from "@theme/Tabs";
:::info
You can get an API key from the [Inception Dashboard](https://platform.inceptionlabs.ai/dashboard/api-keys).
:::
## Chat model
We recommend configuring **Mercury Coder Small** as your chat model.
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- uses: inceptionlabs/mercury-coder-small
with:
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"models": [
{
"title": "Mercury Coder Small",
"provider": "inception",
"model": "mercury-coder-small",
"apiKey": "<INCEPTION_API_KEY>"
}
]
}
```
</TabItem>
</Tabs>
## Autocomplete model
We also recommend configuring **Mercury Coder Small** as your autocomplete model.
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- uses: inceptionlabs/mercury-coder-small
with:
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"tabAutocompleteModel": [
{
"title": "Mercury Coder Small",
"provider": "inception",
"model": "mercury-coder-small",
"apiKey": "<INCEPTION_API_KEY>"
}
]
}
```
</TabItem>
</Tabs>
## Embeddings model
Inception currently does not offer any embeddings models.
[Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers.
## Reranking model
Inception currently does not offer any reranking models.
[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.

View file

@ -1,18 +1,8 @@
---
title: Apply Role
description: Apply model role
keywords: [apply, model, role]
sidebar_position: 4
---
import TabItem from "@theme/TabItem";
import Tabs from "@theme/Tabs";
When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file.
## Recommended Apply models
We recommend [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can get an API key [here](https://app.relace.ai/settings/api-keys).
We recommend [Morph Fast Apply](https://morphllm.com) or [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can sign up for Morph's free tier [here](https://morphllm.com/dashboard) or get a Relace API key [here](https://app.relace.ai/settings/api-keys).
However, most Chat models can also be used for applying code changes. We recommend smaller/cheaper models for the task, such as Claude 3.5 Haiku.

View file

@ -18,7 +18,7 @@ In Continue, these models are used for normal [Chat](../../chat/how-to-use-it.md
For the best overall Chat experience, you will want to use a 400B+ parameter model or one of the frontier models.
### Claude Sonnet 3.5 from Anthropic
### Claude Sonnet 3.7 from Anthropic
Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-providers/top-level/anthropic.mdx).

View file

@ -47,7 +47,17 @@ Continue can retrieve context from a custom HTTP server that you create and serv
Then, create a server that responds to requests as are made from [HttpContextProvider.ts](https://github.com/continuedev/continue/blob/main/core/context/providers/HttpContextProvider.ts). See the `hello` endpoint in [context_provider_server.py](https://github.com/continuedev/continue/blob/main/core/context/providers/context_provider_server.py) for an example that uses FastAPI.
The `"options"` property can be used to send additional parameters to your endpoint, which will be included in the request body.
The `"options"` property can be used to send additional parameters to your endpoint. The full request body has the following shape:
```typescript
{
query: string;
fullInput: string;
options: Record<string, JsonValue>;
workspacePath?: string; // Only provided if the server is local.
}
```
:::info
The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompts](../deep-dives/prompts.md) where possible.

View file

@ -153,7 +153,7 @@ Replicate makes it easy to host and run open-source AI with an API.
SambaNova Cloud provides world record Llama3.1 70B/405B serving.
1. Create an account [here](https://cloud.sambanova.ai/)
1. Create an account [here](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup )
2. Copy your API key
3. Update your Continue config file like this:

View file

@ -159,6 +159,8 @@ Parameters that control the behavior of text generation and completion settings.
- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`.
- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes).
- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream.
- `reasoning`: Enables thinking/reasoning for Anthropic Claude 3.7+ models.
- `reasoningBudgetTokens`: Sets budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
Example

View file

@ -32,7 +32,7 @@ Assistants can either explicitly define blocks - see [Properties](#properties) b
### Using Blocks
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from https://hub.continue.dev.
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev).
Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type.
@ -167,7 +167,7 @@ The `models` section defines the language models used in your configuration. Mod
- `apiBase`: Can be used to override the default API base that is specified per model
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`.
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [autocomplete](./customize/model-roles/autocomplete.md#prompt-templating)
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are `chatTemplate`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [`autocomplete`](./customize/model-roles/autocomplete.md#prompt-templating). The `chatTemplate` property must be a valid template name, such as `llama3` or `anthropic`.
- `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode:
- `baseSystemMessage`: Can be used to override the default system prompt.
- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings:
@ -181,6 +181,8 @@ The `models` section defines the language models used in your configuration. Mod
- `topK`: Maximum number of tokens considered at each step.
- `stop`: An array of stop tokens that will terminate the completion.
- `n`: Number of completions to generate.
- `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models.
- `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
- `requestOptions`: HTTP request options specific to the model.
- `timeout`: Timeout for each request to the language model.
- `verifySsl`: Whether to verify SSL certificates for requests.
@ -270,19 +272,25 @@ Explicit rules can either be simple text or an object with the following propert
- `name` (**required**): A display name/title for the rule
- `rule` (**required**): The text content of the rule
<!-- `if` -->
Example
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
```yaml title="config.yaml"
rules:
- Always annotate Python functions with their parameter and return types
- name: TypeScript best practices
rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly.
globs: "**/*.{ts,tsx}"
- name: TypeScript test patterns
rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking.
globs:
- "src/**/*.test.ts"
- "tests/**/*.ts"
- uses: myprofile/my-mood-setter
with:
TONE: concise
- Always annotate Python functions with their parameter and return types
- Always write Google style docstrings for functions and classes
- name: Server-side components
rule: When writing Next.js React components, use server-side components where possible instead of client components.
```
---

View file

@ -1,7 +1,6 @@
# SambaNova Cloud
SambaNova 云是一个运行大型 AI 模型的云平台,有 Llama 3.1 70B/405B 性能的世界记录。你可以在 [这里](https://cloud.sambanova.ai/) 登录,在最初的欢迎屏幕复制你的 API key ,然后在 [模型列表](https://community.sambanova.ai/t/quick-start-guide/104) 任何模型上点击 play 按钮。
SambaNova 云是一个运行大型 AI 模型的云平台,有 Llama 3.1 70B/405B 性能的世界记录。你可以在 [这里](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup ) 登录,在最初的欢迎屏幕复制你的 API key ,然后在 [模型列表](https://community.sambanova.ai/t/quick-start-guide/104) 任何模型上点击 play 按钮。
```json title="config.json"
{
"models": [

View file

@ -95,7 +95,7 @@ Replicate 让使用 API 托管和运行开源 AI 变得简单。
SambaNova Cloud 提供 Llama3.1 70B/405B 服务的世界记录。
1. 创建账号 [在这里](https://cloud.sambanova.ai/)
1. 创建账号 [在这里](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup)
2. 复制你的 API key
3. 更新你的 Continue 配置文件像这样:

View file

@ -55,6 +55,16 @@ const sidebars = {
},
],
},
{
type: "category",
label: "Blocks",
items: [
{
type: "autogenerated",
dirName: "blocks",
},
],
},
"telemetry",
"troubleshooting",
{
@ -68,7 +78,6 @@ const sidebars = {
{
type: "category",
label: "Model providers",
collapsed: false,
link: {
slug: "/customize/model-providers",
type: "generated-index",

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

BIN
docs/static/img/data-blocks-overview.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

BIN
docs/static/img/docs-blocks-overview.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
docs/static/img/mcp-blocks-overview.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.14
pluginVersion=1.0.15
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -432,6 +432,25 @@ class IdeProtocolClient(
}
}
"acceptDiff" -> {
val params = Gson().fromJson(
dataElement.toString(),
AcceptDiffParams::class.java
)
val filepath = params.filepath;
acceptOrRejectDiff(filepath, true)
}
"rejectDiff" -> {
val params = Gson().fromJson(
dataElement.toString(),
RejectDiffParams::class.java
)
val filepath = params.filepath;
acceptOrRejectDiff(filepath, false)
}
"applyToFile" -> {
val params = Gson().fromJson(
dataElement.toString(),
@ -648,6 +667,29 @@ class IdeProtocolClient(
continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid())
}
fun acceptOrRejectDiff(filepath: String, accepted: Boolean) {
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
if (virtualFile != null) {
ApplicationManager.getApplication().invokeAndWait {
val openedEditor =
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
if (openedEditor != null) {
val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor
if (editor != null) {
val diffStreamService = project.service<DiffStreamService>()
if (accepted) {
diffStreamService.accept(editor)
} else {
diffStreamService.reject(editor)
}
}
}
}
}
}
fun deleteAtIndex(index: Int) {
continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid())
}

View file

@ -42,7 +42,7 @@ class IntelliJIDE(
private val project: Project,
private val continuePluginService: ContinuePluginService,
) : IDE {
) : IDE {
private val gitService = GitService(project, continuePluginService)
@ -57,6 +57,19 @@ class IntelliJIDE(
val os = getOS()
ripgrep =
Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + if (os == OS.WINDOWS) ".exe" else "").toString()
// Make ripgrep executable if on Unix-like systems
try {
if (os == OS.LINUX || os == OS.MAC) {
val file = File(ripgrep)
if (!file.canExecute()) {
file.setExecutable(true)
}
}
} catch (e: Throwable) {
e.printStackTrace()
}
}
/**
@ -179,6 +192,7 @@ class IntelliJIDE(
override suspend fun writeFile(path: String, contents: String) {
val file = File(URI(path))
file.parentFile?.mkdirs()
file.writeText(contents)
}
@ -194,7 +208,13 @@ class IntelliJIDE(
}
override suspend fun openFile(path: String) {
val file = LocalFileSystem.getInstance().findFileByPath(URI(path).path)
// Convert URI path to absolute file path
val filePath = File(URI(path)).absolutePath
// Find the file using the absolute path
val file = withContext(Dispatchers.IO) {
LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath)
}
file?.let {
ApplicationManager.getApplication().invokeLater {
FileEditorManager.getInstance(project).openFile(it, true)
@ -311,7 +331,7 @@ class IntelliJIDE(
val ideInfo = this.getIdeInfo()
if (ideInfo.remoteName == "local") {
val command = GeneralCommandLine(
ripgrep,
ripgrep,
"--files",
"--iglob",
pattern,
@ -320,37 +340,37 @@ class IntelliJIDE(
"--ignore-file",
".gitignore",
)
command.setWorkDirectory(project.basePath)
val results = ExecUtil.execAndGetOutput(command).stdout
return results.split("\n")
} else {
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
// Leaving in here for ideas
// val projectBasePath = project.basePath ?: return emptyList()
// val scope = GlobalSearchScope.projectScope(project)
//
// // Get all ignore patterns from .continueignore files
// val ignorePatterns = mutableSetOf<String>()
// VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root ->
// VfsUtil.collectChildrenRecursively(root).forEach { file ->
// if (file.name == ".continueignore") {
// file.inputStream.bufferedReader().useLines { lines ->
// ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") })
// }
// }
// }
// }
//
// return FilenameIndex.getAllFilesByExt(project, "*", scope)
// .filter { file ->
// val relativePath = file.path.removePrefix("$projectBasePath/")
// // Check if file matches pattern and isn't ignored
// PatternUtil.(relativePath, pattern) &&
// !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) }
// }
// .map { it.path.removePrefix("$projectBasePath/") }
// Leaving in here for ideas
// val projectBasePath = project.basePath ?: return emptyList()
// val scope = GlobalSearchScope.projectScope(project)
//
// // Get all ignore patterns from .continueignore files
// val ignorePatterns = mutableSetOf<String>()
// VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root ->
// VfsUtil.collectChildrenRecursively(root).forEach { file ->
// if (file.name == ".continueignore") {
// file.inputStream.bufferedReader().useLines { lines ->
// ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") })
// }
// }
// }
// }
//
// return FilenameIndex.getAllFilesByExt(project, "*", scope)
// .filter { file ->
// val relativePath = file.path.removePrefix("$projectBasePath/")
// // Check if file matches pattern and isn't ignored
// PatternUtil.(relativePath, pattern) &&
// !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) }
// }
// .map { it.path.removePrefix("$projectBasePath/") }
}
}
@ -358,20 +378,20 @@ class IntelliJIDE(
val ideInfo = this.getIdeInfo()
if (ideInfo.remoteName == "local") {
val command = GeneralCommandLine(
ripgrep,
"-i",
ripgrep,
"-i",
"--ignore-file",
".continueignore",
"--ignore-file",
".gitignore",
"-C",
"2",
"--heading",
"-e",
query,
".gitignore",
"-C",
"2",
"--heading",
"-e",
query,
"."
)
command.setWorkDirectory(project.basePath)
return ExecUtil.execAndGetOutput(command).stdout
} else {
@ -415,7 +435,7 @@ class IntelliJIDE(
// return searchResults.toString()
}
}
override suspend fun subprocess(command: String, cwd: String?): List<Any> {
val commandList = command.split(" ")

View file

@ -15,6 +15,16 @@ data class ApplyToFileParams(
val toolCallId: String?
)
data class AcceptDiffParams(
val filepath: String,
val streamId: String
)
data class RejectDiffParams(
val filepath: String,
val streamId: String
)
data class InsertAtCursorParams(
val text: String
)

View file

@ -71,6 +71,16 @@
"title": "Ollama keep_alive",
"description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min",
"type": "integer"
},
"reasoning": {
"title": "Reasoning",
"description": "Enable thinking/reasoning for Anthropic Claude 3.7+ models",
"type": "boolean"
},
"reasoningBudgetTokens": {
"title": "Reasoning Budget Tokens",
"description": "Set budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models",
"type": "integer"
}
}
},
@ -216,7 +226,8 @@
"siliconflow",
"function-network",
"scaleway",
"relace"
"relace",
"morph"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)",
@ -250,7 +261,7 @@
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).",
"### SambaNova\n SambaNova provides fast inference of open-source language models with zero data retention. To get started, obtain an API key in [SambaNova Cloud](https://cloud.sambanova.ai/apis).",
"### SambaNova\n SambaNova provides fast inference of open-source language models with zero data retention. To get started, obtain an API key in [SambaNova Cloud](https://cloud.sambanova.ai/apis?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup ).",
"### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)",
"### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.",
"### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).",
@ -263,7 +274,8 @@
"### SiliconFlow\nTo get started with SiliconFlow, obtain your API key from [SiliconCloud](https://cloud.siliconflow.cn/account/ak). SiliconCloud provides cost-effective GenAI services based on excellent open source basic models.\n> [Models](https://siliconflow.cn/zh-cn/models)",
"### Function Network offers private, affordable user-owned AI\nTo get started with Function Network, obtain your API key from [Function Network](https://www.function.network/join-waitlist). Function Network provides a variety of models for chat, completion, and embeddings.",
"### Scaleway\n Generative APIs are serverless endpoints for the most popular AI models.\nHosted in European data centers and priced competitively per million tokens used, models served by Scaleway are ideal for users requiring low latency, full data privacy, and 100% compliance with EU AI Act. To get access to the Scaleway Generative APIs, read the [Quickstart guide](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/) and get a [valid API key](https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/).",
"### Relace\n Relace provides a fast apply model. To get started, obtain an API key from [here](https://app.relace.ai/settings/api-keys)."
"### Relace\n Relace provides a fast apply model. To get started, obtain an API key from [here](https://app.relace.ai/settings/api-keys).",
"### Morph\nMorph provides a fast apply model. To get started, obtain an API key from [here](https://morphllm.com/dashboard)."
],
"type": "string"
},
@ -959,7 +971,8 @@
"gemini-2.0-flash-lite-preview-02-05",
"gemini-2.0-flash-lite",
"gemini-2.0-flash-exp-image-generation",
"gemini-2.5-pro-exp-03-25"
"gemini-2.5-pro-exp-03-25",
"gemini-2.5-pro-latest"
]
}
}
@ -1565,6 +1578,7 @@
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
"gemini-2.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash",
"mistral-tiny",
@ -1651,20 +1665,17 @@
"anyOf": [
{
"enum": [
"Qwen2.5-Coder-32B-Instruct",
"Llama-4-Scout-17B-16E-Instruct",
"Llama-4-Maverick-17B-128E-Instruct",
"Meta-Llama-3.3-70B-Instruct",
"Meta-Llama-3.1-8B-Instruct",
"Meta-Llama-3.1-70B-Instruct",
"Meta-Llama-3.1-405B-Instruct",
"Llama-3.1-Tulu-3-405B",
"Meta-Llama-3.2-1B-Instruct",
"Meta-Llama-3.2-3B-Instruct",
"Llama-3.2-11B-Vision-Instruct",
"Llama-3.2-90B-Vision-Instruct",
"Qwen2.5-72B-Instruct",
"QwQ-32B-Preview",
"QwQ-32B",
"DeepSeek-R1-Distill-Llama-70B",
"DeepSeek-R1"
"DeepSeek-R1",
"DeepSeek-V3-0324"
]
},
{

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.24",
"version": "1.1.28",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.24",
"version": "1.1.28",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/fetch": "^1.0.3",
@ -31,7 +31,7 @@
"highlightable": "^1.3.0-beta.0",
"http-proxy": "^1.18.1",
"http-proxy-agent": "^7.0.0",
"http-proxy-middleware": "^2.0.6",
"http-proxy-middleware": "^2.0.9",
"https-proxy-agent": "^7.0.2",
"ignore": "^5.3.0",
"jsdom": "^24.0.0",
@ -109,7 +109,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.18",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -132,6 +132,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
@ -164,6 +165,7 @@
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"winston": "^3.17.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.24.2"
@ -6900,9 +6902,10 @@
}
},
"node_modules/http-proxy-middleware": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz",
"integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==",
"version": "2.0.9",
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.9.tgz",
"integrity": "sha512-c1IyJYLYppU574+YI7R4QyX2ystMtVXZwIdzazUIPIJsHuWNd+mho2j+bKoHftndicGj9yh+xjd+l0yj7VeT1Q==",
"license": "MIT",
"dependencies": {
"@types/http-proxy": "^1.17.8",
"http-proxy": "^1.18.1",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.24",
"version": "1.1.29",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -688,7 +688,7 @@
"highlightable": "^1.3.0-beta.0",
"http-proxy": "^1.18.1",
"http-proxy-agent": "^7.0.0",
"http-proxy-middleware": "^2.0.6",
"http-proxy-middleware": "^2.0.9",
"https-proxy-agent": "^7.0.2",
"ignore": "^5.3.0",
"jsdom": "^24.0.0",

View file

@ -5,11 +5,11 @@ import {
type AutocompleteOutcome,
} from "core/autocomplete/util/types";
import { ConfigHandler } from "core/config/ConfigHandler";
import { startLocalOllama } from "core/util/ollamaHelper";
import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { handleLLMError } from "../util/errorHandling";
import { showFreeTrialLoginMessage } from "../util/messages";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
@ -24,7 +24,6 @@ import {
} from "./statusBar";
import type { IDE } from "core";
import { handleLLMError } from "../util/errorHandling";
interface VsCodeCompletionInput {
document: vscode.TextDocument;
@ -34,8 +33,8 @@ interface VsCodeCompletionInput {
export class ContinueCompletionProvider
implements vscode.InlineCompletionItemProvider {
private onError(e: any) {
if (handleLLMError(e)) {
private async onError(e: any) {
if (await handleLLMError(e)) {
return;
}
let message = e.message;

View file

@ -795,7 +795,7 @@ const getCommandsMap: (
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
},
"continue.openConfigPage": () => {
vscode.commands.executeCommand("continue.navigateTo", "/config", true);
vscode.commands.executeCommand("continue.navigateTo", "/config", false);
},
"continue.selectFilesAsContext": async (
firstUri: vscode.Uri,

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