Merge branch 'main' into download-embedder-ollama

This commit is contained in:
Patrick Erichsen 2025-04-28 16:11:51 -07:00 • committed by GitHub
commit d2abb9a28a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
337 changed files with 15483 additions and 3312 deletions

View file

@ -4,6 +4,7 @@
## Checklist
- [] I've read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md)
- [] The relevant docs, if any, have been updated or created
- [] The relevant tests, if any, have been updated or created

View file

@ -167,6 +167,21 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build and check config-yaml
run: |
cd ../../packages/config-yaml
npm i
npx tsc --noEmit
# Tests are currently failing, commenting out for now
# npm test
npm run build
# npm install core
- name: Install core node_modules
run: |
@ -466,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,15 +1,14 @@
name: PR checks
# PR Checks run on all PRs to the main branch and must pass before merging.
on:
pull_request:
branches:
- main
- staging
push:
branches:
- main
- staging
jobs:
install-root:
@ -417,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]
@ -553,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,
@ -654,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
@ -822,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>

1
.idea/gradle.xml generated
View file

@ -5,6 +5,7 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="homebrew-17" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

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

@ -1 +1 @@
20.11.0
20.19.0

2
.nvmrc
View file

@ -1 +1 @@
v20.11.0
v20.19.0

View file

@ -20,10 +20,12 @@
- [Debugging](#debugging)
- [JetBrains](#jetbrains)
- [Our Git Workflow](#our-git-workflow)
- [Testing](#testing)
- [Development workflow](#development-workflow)
- [Formatting](#formatting)
- [Writing Slash Commands](#writing-slash-commands)
- [Writing Context Providers](#writing-context-providers)
- [Testing](#testing)
- [Review Process](#review-process)
- [Getting help](#getting-help)
- [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
- [Adding an LLM Provider](#adding-an-llm-provider)
- [Adding Models](#adding-models)
- [📐 Continue Architecture](#-continue-architecture)
@ -94,11 +96,13 @@ This will start a local server and you can see the documentation rendered in you
## 🧑‍💻 Contributing Code
We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the process as welcoming and straightforward as possible.
### Environment Setup
#### Pre-requisites
You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
```bash
nvm use
@ -145,45 +149,35 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v0.9.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v0.8.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by <http://releaseflow.org>.
### Development workflow
- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned with the project direction.
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
- Write or update tests for new functionality
- Update relevant documentation in the `docs` folder
- Open a PR against the `main` branch. Make sure to fill in the PR template
### Formatting
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
### Testing
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
### Formatting
### Review Process
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
- **Initial Review** - A maintainer will be assigned as primary reviewer
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is maintainable and follows our patterns.
- **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
### Writing Slash Commands
### Getting help
The slash command interface, defined in [core/index.d.ts](./core/index.d.ts), requires you to define a `name` (the text that will be typed to invoke the command), a `description` (the text that will be shown in the slash command menu), and a `run` function that will be called when the command is invoked. The `run` function is an async generator that yields the content to be displayed in the chat. The `run` function is passed a `ContinueSDK` object that can be used to interact with the IDE, call the LLM, and see the chat history, among a few other utilities.
Join [#contribute on Discord](https://discord.gg/vapESyrFmJ) to engage with maintainers and other contributors.
```ts
export interface SlashCommand {
name: string;
description: string;
params?: { [key: string]: any };
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
}
```
There are many example of slash commands in [core/commands/slash](./core/commands/slash) that we recommend borrowing from. Once you've created your new `SlashCommand` in this folder, also be sure to complete the following:
- Add your command to the array in [core/commands/slash/index.ts](./core/commands/slash/index.ts)
- Add your command to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what commands are available for your provider when they are editing `config.json`. If there are any parameters that your command accepts, you should also follow existing examples in adding them to the JSON Schema.
### Writing Context Providers
A `ContextProvider` is a Continue plugin that lets type '@' to quickly select documents as context for the language model. The `IContextProvider` interface is defined in [`core/index.d.ts`](./core/index.d.ts), but all built-in context providers extend [`BaseContextProvider`](./core/context/index.ts).
Before defining your context provider, determine which "type" you want to create. The `"query"` type will show a small text input when selected, giving the user the chance to enter something like a Google search query for the [`GoogleContextProvider`](./core/context/providers/GoogleContextProvider.ts). The `"submenu"` type will open up a submenu of items that can be searched through and selected. Examples are the [`GitHubIssuesContextProvider`](./core/context/providers/GitHubIssuesContextProvider.ts) and the [`DocsContextProvider`](./core/context/providers/DocsContextProvider.ts). The `"normal"` type will just immediately add the context item. Examples include the [`DiffContextProvider`](./core/context/providers/DiffContextProvider.ts) and the [`OpenFilesContextProvider`](./core/context/providers/OpenFilesContextProvider.ts).
After you've written your context provider, make sure to complete the following:
- Add it to the array of context providers in [core/context/providers/index.ts](./core/context/providers/index.ts)
- Add it to the `ContextProviderName` type in [core/index.d.ts](./core/index.d.ts)
- Add it to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). If there are any parameters that your context provider accepts, you should also follow existing examples in adding them to the JSON Schema.
## Contribtuing new LLM Providers/Models
### Adding an LLM Provider

View file

@ -58,7 +58,7 @@ Learn about how to install and use Continue in the docs [here](https://continue.
## Contributing
Check out the [contribution ideas board](https://github.com/orgs/continuedev/projects/2), read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ)
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
## License

View file

@ -9,17 +9,20 @@ const {
autodetectPlatformAndArch,
} = require("../scripts/util");
// Clean slate
const bin = path.join(__dirname, "bin");
const out = path.join(__dirname, "out");
const build = path.join(__dirname, "build");
rimrafSync(bin);
rimrafSync(out);
rimrafSync(build);
rimrafSync(path.join(__dirname, "tmp"));
fs.mkdirSync(bin);
fs.mkdirSync(out);
fs.mkdirSync(build);
function cleanSlate() {
// Clean slate
rimrafSync(bin);
rimrafSync(out);
rimrafSync(build);
rimrafSync(path.join(__dirname, "tmp"));
fs.mkdirSync(bin);
fs.mkdirSync(out);
fs.mkdirSync(build);
}
const esbuildOutputFile = "out/index.js";
let targets = [
@ -56,6 +59,39 @@ const targetToLanceDb = {
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
};
// Bundles the extension into one file
async function buildWithEsbuild() {
console.log("[info] Building with esbuild...");
await esbuild.build({
entryPoints: ["src/index.ts"],
bundle: true,
outfile: esbuildOutputFile,
external: [
"esbuild",
"./xhr-sync-worker.js",
"llamaTokenizerWorkerPool.mjs",
"tiktokenWorkerPool.mjs",
"vscode",
"./index.node",
],
format: "cjs",
platform: "node",
sourcemap: true,
minify: true,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
// To allow import.meta.path for transformers.js
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
inject: ["./importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
});
}
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
console.log(`Copying ${packageName} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
@ -118,6 +154,13 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
(async () => {
if (esbuildOnly) {
await buildWithEsbuild();
return;
}
cleanSlate()
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// This is only needed for our `pkg` command at build time
fs.writeFileSync(
@ -192,35 +235,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
fs.rmSync(assetPath, { force: true });
}
// Bundles the extension into one file
console.log("[info] Building with esbuild...");
await esbuild.build({
entryPoints: ["src/index.ts"],
bundle: true,
outfile: esbuildOutputFile,
external: [
"esbuild",
"./xhr-sync-worker.js",
"llamaTokenizerWorkerPool.mjs",
"tiktokenWorkerPool.mjs",
"vscode",
"./index.node",
],
format: "cjs",
platform: "node",
sourcemap: true,
minify: true,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
// To allow import.meta.path for transformers.js
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
inject: ["./importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
});
await buildWithEsbuild();
// Copy over any worker files
fs.cpSync(
@ -233,10 +248,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
"out/llamaTokenizerWorkerPool.mjs",
);
if (esbuildOnly) {
return;
}
console.log("[info] Building binaries with pkg...");
for (const target of targets) {
const targetDir = `bin/${target}`;

View file

@ -140,7 +140,7 @@
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"node_modules/@75lb/deep-merge": {

View file

@ -23,6 +23,7 @@
"scripts": {
"test": "jest",
"build": "node build.js",
"rebuild": "node build.js --esbuild-only",
"build:darwin-x64": "node build.js --os darwin-x64"
},
"license": "Apache-2.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

@ -154,6 +154,10 @@ export class CompletionProvider {
return undefined;
}
if (llm.promptTemplates?.autocomplete) {
options.template = llm.promptTemplates.autocomplete as string;
}
const helper = await HelperVars.create(
input,
options,

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

@ -36,7 +36,7 @@ import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index";
import { MCPManagerSingleton } from "../context/mcp";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
@ -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 {
@ -17,7 +18,7 @@ import {
Tool,
} from "../../";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { MCPManagerSingleton } from "../../context/mcp";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
@ -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
@ -658,7 +659,6 @@ declare global {
remoteConfigServerUrl: string | undefined;
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
pauseCodebaseIndexOnStart: boolean;
}

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,
@ -27,7 +25,7 @@ import {
RuleWithSource,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
import { MCPManagerSingleton } from "../../context/mcp";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
@ -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,
});
@ -395,7 +415,10 @@ async function configYamlToContinueConfig({
}
return undefined;
}
const instance: IContextProvider = new cls(context.params ?? {});
const instance: IContextProvider = new cls({
name: context.name,
...context.params,
});
return instance;
})
.filter((p) => !!p) ?? []) as IContextProvider[];
@ -428,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 {
@ -483,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);
@ -147,7 +144,6 @@ async function autodetectModels({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
}: {
llm: BaseLLM;
@ -156,7 +152,6 @@ async function autodetectModels({
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
try {
@ -177,7 +172,6 @@ async function autodetectModels({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
});
}),
@ -195,7 +189,6 @@ export async function llmsFromModelConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
@ -203,7 +196,6 @@ export async function llmsFromModelConfig({
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM({
@ -211,7 +203,6 @@ export async function llmsFromModelConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
});
if (!baseLlm) {
@ -226,7 +217,6 @@ export async function llmsFromModelConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
});
return models;

View file

@ -0,0 +1,219 @@
import { jest } from "@jest/globals";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import MCPConnection from "./MCPConnection";
describe("MCPConnection", () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe("constructor", () => {
it("should create instance with stdio transport", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test-cmd",
args: ["--test"],
env: { TEST: "true" },
},
};
const conn = new MCPConnection(options);
expect(conn).toBeInstanceOf(MCPConnection);
expect(conn.status).toBe("not-connected");
});
it("should create instance with websocket transport", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "websocket" as const,
url: "ws://test.com",
},
};
const conn = new MCPConnection(options);
expect(conn).toBeInstanceOf(MCPConnection);
expect(conn.status).toBe("not-connected");
});
it("should create instance with SSE transport", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "sse" as const,
url: "http://test.com/events",
},
};
const conn = new MCPConnection(options);
expect(conn).toBeInstanceOf(MCPConnection);
expect(conn.status).toBe("not-connected");
});
it("should throw on invalid transport type", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "invalid",
} as any,
};
expect(() => new MCPConnection(options)).toThrow(
"Unsupported transport type: invalid",
);
});
});
describe("getStatus", () => {
it("should return current status", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test",
args: [],
},
};
const conn = new MCPConnection(options);
const status = conn.getStatus();
expect(status).toEqual({
...options,
errors: [],
prompts: [],
resources: [],
tools: [],
status: "not-connected",
});
});
});
describe("connectClient", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test-cmd",
args: [],
},
};
it("should connect successfully", async () => {
const conn = new MCPConnection(options);
const mockConnect = jest
.spyOn(Client.prototype, "connect")
.mockResolvedValue(undefined);
const mockGetServerCapabilities = jest
.spyOn(Client.prototype, "getServerCapabilities")
.mockReturnValue({
resources: {},
tools: {},
prompts: {},
});
const mockListResources = jest
.spyOn(Client.prototype, "listResources")
.mockResolvedValue({
resources: [{ name: "test-resource", uri: "test-uri" }],
});
const mockListTools = jest
.spyOn(Client.prototype, "listTools")
.mockResolvedValue({
tools: [
{
name: "test-tool",
inputSchema: {
type: "object",
},
},
],
});
const mockListPrompts = jest
.spyOn(Client.prototype, "listPrompts")
.mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
expect(conn.status).toBe("connected");
expect(conn.resources).toHaveLength(1);
expect(conn.tools).toHaveLength(1);
expect(conn.prompts).toHaveLength(1);
expect(mockConnect).toHaveBeenCalled();
});
it("should handle connection timeout", async () => {
const conn = new MCPConnection({ ...options, timeout: 1 });
const mockConnect = jest
.spyOn(Client.prototype, "connect")
.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 100)),
);
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
expect(conn.status).toBe("error");
expect(conn.errors[0]).toContain("Failed to connect to MCP server");
expect(mockConnect).toHaveBeenCalled();
});
it("should handle already connected state", async () => {
const conn = new MCPConnection(options);
conn.status = "connected";
const mockConnect = jest.spyOn(Client.prototype, "connect");
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
expect(mockConnect).not.toHaveBeenCalled();
expect(conn.status).toBe("connected");
});
it("should handle transport errors", async () => {
const conn = new MCPConnection(options);
const mockConnect = jest
.spyOn(Client.prototype, "connect")
.mockRejectedValue(new Error("spawn test-cmd ENOENT"));
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
expect(conn.status).toBe("error");
expect(conn.errors[0]).toContain('command "test-cmd" not found');
expect(mockConnect).toHaveBeenCalled();
});
});
describe.skip("actually connect to Filesystem MCP", () => {
it("should connect and include correct tools", async () => {
const conn = new MCPConnection({
id: "filesystem",
name: "Filesystem",
transport: {
type: "stdio" as const,
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
},
});
try {
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
expect(conn.status).toBe("connected");
} finally {
await conn.disconnect();
}
});
});
});

View file

@ -1,8 +1,9 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import {
MCPConnectionStatus,
@ -13,114 +14,6 @@ import {
MCPTool,
} from "../..";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
public onConnectionsRefreshed?: () => void;
private connections: Map<string, MCPConnection> = new Map();
private abortController: AbortController = new AbortController();
private constructor() {}
public static getInstance(): MCPManagerSingleton {
if (!MCPManagerSingleton.instance) {
MCPManagerSingleton.instance = new MCPManagerSingleton();
}
return MCPManagerSingleton.instance;
}
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id)!;
}
}
getConnection(id: string) {
return this.connections.get(id);
}
async removeConnection(id: string) {
const connection = this.connections.get(id);
if (connection) {
await connection.client.close();
}
this.connections.delete(id);
}
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
let refresh = false;
// Remove any connections that are no longer in config
Array.from(this.connections.entries()).forEach(([id, connection]) => {
if (!servers.find((s) => s.id === id)) {
refresh = true;
connection.abortController.abort();
void connection.client.close();
this.connections.delete(id);
}
});
// Add any connections that are not yet in manager
servers.forEach((server) => {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
}
});
// NOTE the id is made by stringifying the options
if (refresh) {
void this.refreshConnections(forceRefresh);
}
}
async refreshConnection(serverId: string) {
const connection = this.connections.get(serverId);
if (!connection) {
throw new Error(`MCP Connection ${serverId} not found`);
}
await connection.connectClient(true, this.abortController.signal);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
}
}
async refreshConnections(force: boolean) {
this.abortController.abort();
this.abortController = new AbortController();
await Promise.race([
new Promise((resolve) => {
this.abortController.signal.addEventListener("abort", () => {
resolve(undefined);
});
}),
(async () => {
await Promise.all(
Array.from(this.connections.values()).map(async (connection) => {
await connection.connectClient(force, this.abortController.signal);
}),
);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
}
})(),
]);
}
getStatuses(): (MCPServerStatus & { client: Client })[] {
return Array.from(this.connections.values()).map((connection) => ({
...connection.getStatus(),
client: connection.client,
}));
}
}
const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds
class MCPConnection {
@ -153,6 +46,12 @@ class MCPConnection {
this.abortController = new AbortController();
}
async disconnect() {
this.abortController.abort();
await this.client.close();
await this.transport.close();
}
private constructTransport(options: MCPOptions): Transport {
switch (options.transport.type) {
case "stdio":
@ -240,6 +139,7 @@ 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

@ -0,0 +1,219 @@
import { MCPOptions } from "../..";
import MCPConnection from "./MCPConnection";
import { MCPManagerSingleton } from "./MCPManagerSingleton";
// Create test versions with stubbed behavior
class TestMCPConnection extends MCPConnection {
constructor(options: MCPOptions) {
super(options);
// Override with test implementations
this.client = {
close: async () => {},
connect: async () => {},
getServerCapabilities: () => ({}),
listResources: async () => ({ resources: [] }),
listTools: async () => ({ tools: [] }),
listPrompts: async () => ({ prompts: [] }),
} as any;
this.abortController = new AbortController();
this.connectClient = jest.fn().mockResolvedValue(undefined);
this.getStatus = jest
.fn()
.mockReturnValue({ status: "connected", errors: [] });
}
}
describe("MCPManagerSingleton", () => {
let manager: MCPManagerSingleton;
const testOptions: MCPOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio",
command: "test-command",
args: [],
},
};
beforeEach(() => {
// Reset singleton
(MCPManagerSingleton as any).instance = undefined;
manager = MCPManagerSingleton.getInstance();
// Replace the connections map with our own that will use TestMCPConnection
const connectionsMap = new Map<string, MCPConnection>();
Object.defineProperty(manager, "connections", {
value: connectionsMap,
writable: true,
});
// Override createConnection to use our TestMCPConnection
manager.createConnection = function (
id: string,
options: MCPOptions,
): MCPConnection {
if (!this.connections.has(id)) {
const connection = new TestMCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id)!;
}
};
});
describe("getInstance", () => {
it("should create singleton instance", () => {
const instance1 = MCPManagerSingleton.getInstance();
const instance2 = MCPManagerSingleton.getInstance();
expect(instance1).toBe(instance2);
});
});
describe("createConnection", () => {
it("should create new connection if none exists", () => {
const connection = manager.createConnection("test-id", testOptions);
expect(connection).toBeInstanceOf(MCPConnection);
});
it("should return existing connection if exists", () => {
const connection1 = manager.createConnection("test-id", testOptions);
const connection2 = manager.createConnection("test-id", testOptions);
expect(connection1).toBe(connection2);
});
});
describe("getConnection", () => {
it("should return undefined for non-existent connection", () => {
expect(manager.getConnection("non-existent")).toBeUndefined();
});
it("should return existing connection", () => {
const connection = manager.createConnection("test-id", testOptions);
expect(manager.getConnection("test-id")).toBe(connection);
});
});
describe("removeConnection", () => {
it("should remove connection and close client", async () => {
// Create a spy on the close method
const connection = manager.createConnection(
"test-id",
testOptions,
) as TestMCPConnection;
const closeSpy = jest.spyOn(connection.client, "close");
await manager.removeConnection("test-id");
expect(closeSpy).toHaveBeenCalled();
expect(manager.getConnection("test-id")).toBeUndefined();
});
it("should handle non-existent connection", async () => {
await expect(
manager.removeConnection("non-existent"),
).resolves.toBeUndefined();
});
});
describe("setConnections", () => {
it("should add new connections", () => {
const servers = [testOptions];
manager.setConnections(servers, false);
expect(manager.getConnection(testOptions.id)).toBeInstanceOf(
MCPConnection,
);
});
it("should remove old connections", () => {
// Create initial connection
const connection = manager.createConnection(
"test-id",
testOptions,
) as TestMCPConnection;
const abortSpy = jest.spyOn(connection.abortController, "abort");
const closeSpy = jest.spyOn(connection.client, "close");
// Remove it by setting empty server list
manager.setConnections([], false);
expect(abortSpy).toHaveBeenCalled();
expect(closeSpy).toHaveBeenCalled();
expect(manager.getConnection("test-id")).toBeUndefined();
});
});
describe("refreshConnection", () => {
it("should refresh specific connection", async () => {
const connection = manager.createConnection(
"test-id",
testOptions,
) as TestMCPConnection;
await manager.refreshConnection("test-id");
expect(connection.connectClient).toHaveBeenCalledWith(
true,
expect.any(AbortSignal),
);
});
it("should throw error for non-existent connection", async () => {
await expect(manager.refreshConnection("non-existent")).rejects.toThrow(
"MCP Connection non-existent not found",
);
});
});
describe("refreshConnections", () => {
it("should refresh all connections", async () => {
const connection1 = manager.createConnection("test-id-1", {
...testOptions,
id: "test-id-1",
}) as TestMCPConnection;
const connection2 = manager.createConnection("test-id-2", {
...testOptions,
id: "test-id-2",
}) as TestMCPConnection;
await manager.refreshConnections(true);
expect(connection1.connectClient).toHaveBeenCalledWith(
true,
expect.any(AbortSignal),
);
expect(connection2.connectClient).toHaveBeenCalledWith(
true,
expect.any(AbortSignal),
);
});
it("should call onConnectionsRefreshed if defined", async () => {
const mockCallback = jest.fn();
manager.onConnectionsRefreshed = mockCallback;
manager.createConnection("test-id", testOptions);
await manager.refreshConnections(true);
expect(mockCallback).toHaveBeenCalled();
});
});
describe("getStatuses", () => {
it("should return statuses for all connections", () => {
const connection = manager.createConnection(
"test-id",
testOptions,
) as TestMCPConnection;
const mockStatus = { status: "connected", errors: [] };
connection.getStatus = jest.fn().mockReturnValue(mockStatus);
const statuses = manager.getStatuses();
expect(statuses).toHaveLength(1);
expect(statuses[0]).toEqual({ ...mockStatus, client: connection.client });
});
});
});

View file

@ -0,0 +1,112 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { MCPOptions, MCPServerStatus } from "../..";
import MCPConnection from "./MCPConnection";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
public onConnectionsRefreshed?: () => void;
public connections: Map<string, MCPConnection> = new Map();
private abortController: AbortController = new AbortController();
private constructor() {}
public static getInstance(): MCPManagerSingleton {
if (!MCPManagerSingleton.instance) {
MCPManagerSingleton.instance = new MCPManagerSingleton();
}
return MCPManagerSingleton.instance;
}
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id)!;
}
}
getConnection(id: string) {
return this.connections.get(id);
}
async removeConnection(id: string) {
const connection = this.connections.get(id);
if (connection) {
await connection.client.close();
}
this.connections.delete(id);
}
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
let refresh = false;
// Remove any connections that are no longer in config
Array.from(this.connections.entries()).forEach(([id, connection]) => {
if (!servers.find((s) => s.id === id)) {
refresh = true;
connection.abortController.abort();
void connection.client.close();
this.connections.delete(id);
}
});
// Add any connections that are not yet in manager
servers.forEach((server) => {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
}
});
// NOTE the id is made by stringifying the options
if (refresh) {
void this.refreshConnections(forceRefresh);
}
}
async refreshConnection(serverId: string) {
const connection = this.connections.get(serverId);
if (!connection) {
throw new Error(`MCP Connection ${serverId} not found`);
}
await connection.connectClient(true, this.abortController.signal);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
}
}
async refreshConnections(force: boolean) {
this.abortController.abort();
this.abortController = new AbortController();
await Promise.race([
new Promise((resolve) => {
this.abortController.signal.addEventListener("abort", () => {
resolve(undefined);
});
}),
(async () => {
await Promise.all(
Array.from(this.connections.values()).map(async (connection) => {
await connection.connectClient(force, this.abortController.signal);
}),
);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
}
})(),
]);
}
getStatuses(): (MCPServerStatus & { client: Client })[] {
return Array.from(this.connections.values()).map((connection) => ({
...connection.getStatus(),
client: connection.client,
}));
}
}

View file

@ -24,6 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider {
this.options.title || ContinueProxyContextProvider.description.title,
displayTitle:
this.options.displayTitle ||
this.options.name ||
ContinueProxyContextProvider.description.displayTitle,
description:
this.options.description ||

View file

@ -16,18 +16,20 @@ class HttpContextProvider extends BaseContextProvider {
override get description(): ContextProviderDescription {
return {
title: this.options.title || "http",
displayTitle: this.options.displayTitle || "HTTP",
title: this.options.title || HttpContextProvider.description.title,
displayTitle:
this.options.displayTitle ||
this.options.name ||
HttpContextProvider.description.displayTitle,
description:
this.options.description ||
"Retrieve a context item from a custom server",
type: "normal",
this.options.description || HttpContextProvider.description.description,
type: HttpContextProvider.description.type,
renderInlineAs:
this.options.renderInlineAs ||
HttpContextProvider.description.renderInlineAs,
};
}
async getContextItems(
query: string,
extras: ContextProviderExtras,

View file

@ -6,7 +6,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { MCPManagerSingleton } from "../mcp";
import { MCPManagerSingleton } from "../mcp/MCPManagerSingleton";
interface MCPContextProviderOptions {
mcpId: string;

View file

@ -26,6 +26,10 @@ import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
markProcessAsBackgrounded,
} from "./util/processTerminalBackgroundStates";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -35,6 +39,7 @@ import {
IdeSettings,
ModelDescription,
RangeInFile,
type ContextItem,
type ContextItemId,
type IDE,
type IndexingProgressUpdate,
@ -48,7 +53,7 @@ import {
setupQuickstartConfig,
} from "./config/onboarding";
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
@ -253,6 +258,7 @@ export class Core {
this.registerMessageHandlers(ideSettingsPromise);
}
/* eslint-disable max-lines-per-function */
private registerMessageHandlers(ideSettingsPromise: Promise<IdeSettings>) {
const on = this.messenger.on.bind(this.messenger);
@ -276,7 +282,6 @@ export class Core {
}
});
// Special
on("abort", (msg) => {
this.abortedMessageIds.add(msg.messageId);
});
@ -305,12 +310,14 @@ export class Core {
historyManager.save(msg.data);
});
// Dev data
on("history/clear", (msg) => {
historyManager.clearAll();
});
on("devdata/log", async (msg) => {
void DataLogger.getInstance().logDevData(msg.data);
});
// Edit config
on("config/addModel", (msg) => {
const model = msg.data.model;
addModel(model, msg.data.role);
@ -403,15 +410,20 @@ export class Core {
return [];
}
const items = await config.contextProviders
?.find((provider) => provider.description.title === msg.data.title)
?.loadSubmenuItems({
config,
ide: this.ide,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
return items || [];
try {
const items = await config.contextProviders
?.find((provider) => provider.description.title === msg.data.title)
?.loadSubmenuItems({
config,
ide: this.ide,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
return items || [];
} catch (e) {
console.error(e);
return [];
}
});
on("context/getContextItems", this.getContextItems.bind(this));
@ -465,7 +477,7 @@ export class Core {
);
return completion;
});
on("llm/listModels", this.handleListModels);
on("llm/listModels", this.handleListModels.bind(this));
// Provide messenger to utils so they can interact with GUI + state
TTS.messenger = this.messenger;
@ -506,9 +518,9 @@ export class Core {
streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
);
on("completeOnboarding", this.handleCompleteOnboarding);
on("completeOnboarding", this.handleCompleteOnboarding.bind(this));
on("addAutocompleteModel", this.handleAddAutocompleteModel);
on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this));
on("stats/getTokensPerDay", async (msg) => {
const rows = await DevDataSqliteDb.getTokensPerDay();
@ -549,7 +561,7 @@ export class Core {
});
// File changes - TODO - remove remaining logic for these from IDEs where possible
on("files/changed", this.handleFilesChanged);
on("files/changed", this.handleFilesChanged.bind(this));
const refreshIfNotIgnored = async (uris: string[]) => {
const toRefresh: string[] = [];
for (const uri of uris) {
@ -627,17 +639,24 @@ export class Core {
});
on("didChangeSelectedProfile", async (msg) => {
await this.configHandler.setSelectedProfileId(msg.data.id);
if (msg.data.id) {
await this.configHandler.setSelectedProfileId(msg.data.id);
}
});
on("didChangeSelectedOrg", async (msg) => {
await this.configHandler.setSelectedOrgId(
msg.data.id,
msg.data.profileId,
);
if (msg.data.id) {
await this.configHandler.setSelectedOrgId(
msg.data.id,
msg.data.profileId || undefined,
);
}
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
this.messenger.send("sessionUpdate", {
sessionInfo: msg.data.sessionInfo,
});
await this.configHandler.updateControlPlaneSessionInfo(
msg.data.sessionInfo,
);
@ -653,7 +672,7 @@ export class Core {
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
try {
const ignore = shouldIgnore(filepath, this.ide);
const ignore = await shouldIgnore(filepath, this.ide);
if (!ignore) {
recentlyEditedFilesCache.set(filepath, filepath);
}
@ -664,7 +683,7 @@ export class Core {
}
});
on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => {
on("tools/call", async ({ data: { toolCall } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
@ -682,47 +701,55 @@ export class Core {
throw new Error("No chat model selected");
}
const contextItems = await callTool(
// Define a callback for streaming output updates
const onPartialOutput = (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => {
this.messenger.send("toolCallPartialOutput", params);
};
return await callTool(tool, toolCall.function.arguments, {
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
JSON.parse(toolCall.function.arguments || "{}"),
{
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
},
);
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;
});
}
return { contextItems };
toolCallId: toolCall.id,
onPartialOutput,
});
});
on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => {
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
});
// Process state handlers
on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
markProcessAsBackgrounded(toolCallId);
});
on(
"process/isBackgrounded",
async ({ data: { toolCallId }, messageId }) => {
const isBackgrounded = isProcessBackgrounded(toolCallId);
return isBackgrounded; // Return true to indicate the message was handled successfully
},
);
}
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;
@ -794,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 (
@ -888,7 +916,6 @@ export class Core {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
selectedModelTitle: string;
}>,
) => {
const { config } = await this.configHandler.loadConfig();

View file

@ -41,4 +41,16 @@ describe("Test myers diff function", () => {
{ type: "same", line: "C" },
]);
});
test("should ignore single-line whitespace-only differences", () => {
const linesA = "A\n B\nC\n";
const linesB = "A\nB\nC";
const diffLines = myersDiff(linesA, linesB);
expect(diffLines).toEqual([
{ type: "same", line: "A" },
{ type: "same", line: " B" },
{ type: "same", line: "C" },
]);
});
});

View file

@ -30,8 +30,21 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
const theirFormat = diffLines(oldContent, newContent, {
ignoreNewlineAtEof: true,
});
const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
let ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
// Combine consecutive old/new pairs that are identical after trimming
for (let i = 0; i < ourFormat.length - 1; i++) {
if (
ourFormat[i]?.type === "old" &&
ourFormat[i + 1]?.type === "new" &&
ourFormat[i].line.trim() === ourFormat[i + 1].line.trim()
) {
ourFormat[i] = { type: "same", line: ourFormat[i].line };
ourFormat.splice(i + 1, 1);
}
}
// Remove trailing empty old lines
while (
ourFormat.length > 0 &&
ourFormat[ourFormat.length - 1].type === "old" &&

View file

@ -154,7 +154,13 @@ export async function deterministicApplyLazyEdit({
if (onlyFullFileRewrite) {
if (!isLazyText(newTree.rootNode.text)) {
return myersDiff(oldFile, newLazyFile);
const diff = myersDiff(oldFile, newLazyFile);
if (shouldRejectDiff(diff)) {
return undefined;
}
return diff;
} else {
return undefined;
}

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,
@ -123,11 +124,13 @@ export async function* streamDiffLines({
if (systemMessage) {
if (typeof prompt === "string") {
// Removed system prompt because it was causing it to be used for Apply
// We should bring it back only for Edit
prompt = [
{
role: "system",
content: systemMessage,
},
// {
// role: "system",
// content: systemMessage,
// },
{
role: "user",
content: prompt,
@ -138,10 +141,10 @@ export async function* streamDiffLines({
if (curSysMsg) {
curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content;
} else {
prompt.unshift({
role: "system",
content: systemMessage,
});
// prompt.unshift({
// role: "system",
// content: systemMessage,
// });
}
}
}

20
core/index.d.ts vendored
View file

@ -1,4 +1,8 @@
import { DataDestination, ModelRole } 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";
@ -399,6 +403,7 @@ export interface ContextItem {
icon?: string;
uri?: ContextItemUri;
hidden?: boolean;
status?: string;
}
export interface ContextItemWithId extends ContextItem {
@ -431,6 +436,7 @@ export type ToolStatus =
| "generating"
| "generated"
| "calling"
| "errored"
| "done"
| "canceled";
@ -569,7 +575,7 @@ export interface LLMOptions {
completionOptions?: CompletionOptions;
requestOptions?: RequestOptions;
template?: TemplateType;
promptTemplates?: Record<string, PromptTemplate>;
promptTemplates?: Partial<Record<keyof PromptTemplates, PromptTemplate>>;
templateMessages?: (messages: ChatMessage[]) => string;
logger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
@ -968,6 +974,11 @@ export interface ToolExtras {
llm: ILLM;
fetch: FetchFunction;
tool: Tool;
toolCallId?: string;
onPartialOutput?: (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => void;
}
export interface Tool {
@ -984,6 +995,7 @@ export interface Tool {
isCurrently?: string;
hasAlready?: string;
readonly: boolean;
isInstant?: boolean;
uri?: string;
faviconUrl?: string;
group: string;
@ -1208,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"
@ -1486,6 +1499,7 @@ export type PackageDocsResult = {
export interface TerminalOptions {
reuseTerminal?: boolean;
terminalName?: string;
waitForCompletion?: boolean;
}
export interface RuleWithSource {
@ -1497,7 +1511,7 @@ export interface RuleWithSource {
| "rules-block"
| "json-systemMessage"
| ".continuerules";
if?: string;
globs?: string | string[];
rule: string;
description?: string;
ruleFile?: string;

View file

@ -39,7 +39,6 @@
// const ideSettingsPromise = Promise.resolve({
// remoteConfigSyncPeriod: 60,
// userToken: "",
// enableControlServerBeta: false,
// continueTestEnvironment: "none" as const,
// pauseCodebaseIndexOnStart: false,
// ideSettings: {} as any,

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>
@ -20,9 +21,9 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
When addressing code modification requests, present a concise code snippet that
emphasizes only the necessary changes and uses abbreviated placeholders for
unmodified sections. For instance:
unmodified sections. For example:
\`\`\`typescript /path/to/file
\`\`\`language /path/to/file
// ... rest of code here ...
{{ modified code here }}
@ -34,6 +35,22 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
// ... rest of code here ...
\`\`\`
In existing files, you should always restate the function or class that the snippet belongs to:
\`\`\`language /path/to/file
// ... rest of code here ...
function exampleFunction() {
// ... rest of code here ...
{{ modified code here }}
// ... rest of code here ...
}
// ... rest of code here ...
\`\`\`
Since users have access to their complete file, they prefer reading only the
relevant modifications. It's perfectly acceptable to omit unmodified portions
at the beginning, middle, or end of files using these "lazy" comments. Only
@ -41,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",
@ -76,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",
@ -103,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,
@ -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 { v4 as uuidv4 } from "uuid";
import {
AssistantChatMessage,
ChatMessage,
@ -7,7 +8,6 @@ import {
TextMessagePart,
ToolCallDelta,
} from "../../index.js";
import { findLast } from "../../util/findLast.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
@ -18,7 +18,8 @@ import {
GeminiChatResponse,
GeminiGenerationConfig,
GeminiToolFunctionDeclaration,
} from "./gemini-types.js";
convertContinueToolToGeminiFunction,
} from "./gemini-types";
class Gemini extends BaseLLM {
static providerName = "gemini";
@ -199,6 +200,16 @@ class Gemini extends BaseLLM {
options: CompletionOptions,
isV1API: boolean,
): GeminiChatRequestBody {
const toolCallIdToNameMap = new Map<string, string>();
messages.forEach((msg) => {
if (msg.role === "assistant" && msg.toolCalls) {
msg.toolCalls.forEach((call) => {
if (call.id && call.function?.name) {
toolCallIdToNameMap.set(call.id, call.function.name);
}
});
}
});
const systemMessage = messages.find(
(msg) => msg.role === "system",
)?.content;
@ -208,15 +219,8 @@ class Gemini extends BaseLLM {
.filter((msg) => !(msg.role === "system" && isV1API))
.map((msg) => {
if (msg.role === "tool") {
let fn_name = "";
const lastToolCallMessage = findLast(
messages,
(msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name,
) as AssistantChatMessage;
if (lastToolCallMessage) {
fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!;
}
if (!fn_name) {
let functionName = toolCallIdToNameMap.get(msg.toolCallId);
if (!functionName) {
console.warn(
"Sending tool call response for unidentified tool call",
);
@ -226,7 +230,8 @@ class Gemini extends BaseLLM {
parts: [
{
functionResponse: {
name: fn_name || "unknown",
id: msg.toolCallId,
name: functionName || "unknown",
response: {
output: msg.content, // "output" key is opinionated - not all functions will output objects
},
@ -284,77 +289,12 @@ class Gemini extends BaseLLM {
// Same difference
const functions: GeminiToolFunctionDeclaration[] = [];
options.tools.forEach((tool) => {
if (tool.function.description && tool.function.name) {
const fn: GeminiToolFunctionDeclaration = {
description: tool.function.description,
name: tool.function.name,
};
if (
tool.function.parameters &&
"type" in tool.function.parameters
// && typeof tool.function.parameters.type === "string"
) {
// const paramType = "TYPE_UNSPECIFIED"
// | "STRING"
// | "NUMBER"
// | "INTEGER"
// | "BOOLEAN"
// | "ARRAY"
// | "OBJECT"
if (tool.function.parameters.type === "object") {
// Gemini can't take an empty object
// So if empty object param is present just don't add parameters
if (
JSON.stringify(tool.function.parameters.properties) === "{}"
) {
functions.push(fn);
return;
}
}
// Helper function to recursively clean JSON Schema objects
const cleanJsonSchema = (schema: any): any => {
if (!schema || typeof schema !== "object") return schema;
if (Array.isArray(schema)) {
return schema.map(cleanJsonSchema);
}
const {
$schema,
additionalProperties,
default: defaultValue,
...rest
} = schema;
// Recursively clean nested properties
if (rest.properties) {
rest.properties = Object.entries(rest.properties).reduce(
(acc, [key, value]) => ({
...acc,
[key]: cleanJsonSchema(value),
}),
{},
);
}
// Clean items in arrays
if (rest.items) {
rest.items = cleanJsonSchema(rest.items);
}
return rest;
};
// Clean the parameters and convert type to uppercase
const cleanedParams = cleanJsonSchema(tool.function.parameters);
fn.parameters = {
...cleanedParams,
type: tool.function.parameters.type.toUpperCase(),
};
}
functions.push(fn);
try {
functions.push(convertContinueToolToGeminiFunction(tool));
} catch (e) {
console.warn(
`Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`,
);
}
});
if (functions.length) {
@ -405,75 +345,39 @@ class Gemini extends BaseLLM {
// Check for existence of each level before accessing the final 'text' property
const content = data?.candidates?.[0]?.content;
if (content) {
const supportedParts: MessagePart[] = [];
const textParts: MessagePart[] = [];
const toolCalls: ToolCallDelta[] = [];
// Process all parts first to maintain order
const processedParts: Array<{
type: "content" | "tool" | "toolCall";
data: any;
}> = [];
for (const part of content.parts) {
if ("text" in part) {
supportedParts.push({ type: "text", text: part.text });
} else if ("inlineData" in part) {
supportedParts.push({
type: "imageUrl",
imageUrl: {
url: `data:image/jpeg;base64,${part.inlineData.data}`,
},
});
textParts.push({ type: "text", text: part.text });
} else if ("functionCall" in part) {
// Queue function call
processedParts.push({
type: "toolCall",
data: {
type: "function",
id: "", // Not supported by gemini
function: {
name: part.functionCall.name,
arguments:
typeof part.functionCall.args === "string"
? part.functionCall.args
: JSON.stringify(part.functionCall.args),
},
},
});
} else if ("functionResponse" in part) {
// Queue function response
processedParts.push({
type: "tool",
data: {
role: "tool",
content: part.functionResponse.response.output as string,
toolCallId: part.functionResponse.name,
toolCalls.push({
type: "function",
id: part.functionCall.id ?? uuidv4(),
function: {
name: part.functionCall.name,
arguments:
typeof part.functionCall.args === "string"
? part.functionCall.args
: JSON.stringify(part.functionCall.args),
},
});
} else {
// Note: function responses shouldn't be streamed, images not supported
console.warn("Unsupported gemini part type received", part);
}
}
// If we have supported content parts, yield them first
if (supportedParts.length) {
yield {
role: "assistant",
content: supportedParts,
};
const assistantMessage: AssistantChatMessage = {
role: "assistant",
content: textParts.length ? textParts : "",
};
if (toolCalls.length > 0) {
assistantMessage.toolCalls = toolCalls;
}
// Then process tool calls and responses in order
for (const part of processedParts) {
if (part.type === "toolCall") {
yield {
role: "assistant",
content: "",
toolCalls: [part.data],
};
} else if (part.type === "tool") {
yield part.data;
}
if (textParts.length || toolCalls.length) {
yield assistantMessage;
}
} else {
// Handle the case where the expected data structure is not found

View file

@ -18,11 +18,10 @@ import OpenAI from "./OpenAI.js";
class Inception extends OpenAI {
static providerName = "inception";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://copenhagen.api.inceptionlabs.ai/v1/",
apiBase: "https://api.inceptionlabs.ai/v1/",
model: "mercury-editor-small-experimental",
completionOptions: {
temperature: 0.0,
maxTokens: 150,
presencePenalty: 1.5,
stop: ["\n\n", "\n \n", "<|endoftext|>"],
model: "mercury-editor-small-experimental", // Added model to fix TypeScript error
@ -45,8 +44,8 @@ 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,
@ -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

@ -102,7 +102,12 @@ class OpenAI extends BaseLLM {
}
protected supportsPrediction(model: string): boolean {
const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"];
const SUPPORTED_MODELS = [
"gpt-4o-mini",
"gpt-4o",
"mistral-large",
"Fast-Apply",
];
return SUPPORTED_MODELS.some((m) => model.includes(m));
}

View file

@ -11,6 +11,10 @@ export class Relace extends OpenAI {
};
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"];
protected supportsPrediction(model: string): boolean {
return true;
}
getConfigurationStatus() {
if (!this.apiKey) {
return LLMConfigurationStatuses.MISSING_API_KEY;

View file

@ -1,4 +1,5 @@
import { JSONSchema7Object } from "json-schema";
import { Tool } from "../..";
// https://ai.google.dev/api/generate-content
export interface GeminiGenerationConfig {
@ -16,70 +17,225 @@ export interface GeminiGenerationConfig {
// responseSchema?: object; // https://ai.google.dev/api/caching#Schema
}
export interface GeminiFunctionSchema {
type:
| "TYPE_UNSPECIFIED"
| "STRING"
| "NUMBER"
| "INTEGER"
| "BOOLEAN"
| "ARRAY"
| "OBJECT";
export type GeminiObjectSchemaType =
| "TYPE_UNSPECIFIED"
| "STRING"
| "NUMBER"
| "INTEGER"
| "BOOLEAN"
| "ARRAY"
| "OBJECT";
export interface GeminiObjectSchema {
type: GeminiObjectSchemaType;
format?: string;
title?: string;
description?: string;
nullable?: boolean;
enum?: string[];
maxItems?: string;
minItems?: string;
properties?: Record<string, GeminiFunctionSchema>;
properties?: Record<string, GeminiObjectSchema>;
required?: string[];
items?: GeminiFunctionSchema;
anyOf?: GeminiObjectSchema[];
propertyOrdering?: string[];
items?: GeminiObjectSchema;
minimum?: number;
maximum?: number;
}
const jsonSchemaTypeToGeminiType = (
jsonSchemaType: string,
): GeminiObjectSchemaType => {
switch (jsonSchemaType.toLowerCase()) {
case "string":
return "STRING";
case "object":
return "OBJECT";
case "number":
return "NUMBER";
case "integer":
return "INTEGER";
case "array":
return "ARRAY";
case "boolean":
return "BOOLEAN";
default:
return "TYPE_UNSPECIFIED";
}
};
function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema {
const jsonSchemaType = jsonSchema["type"];
if (!jsonSchemaType || typeof jsonSchema.type !== "string") {
throw new Error(
`Invalid type property in function declaration\n${JSON.stringify(jsonSchema, null, 2)}`,
);
}
const geminiSchema: GeminiObjectSchema = {
type: jsonSchemaTypeToGeminiType(jsonSchemaType),
};
// if (jsonSchema.format) geminiSchema.format = jsonSchema.format;
if (jsonSchema.title) geminiSchema.title = jsonSchema.title;
if (jsonSchema.description) geminiSchema.description = jsonSchema.description;
// Handle nullable
if (jsonSchemaType === "null" || jsonSchema.nullable) {
geminiSchema.nullable = true;
}
// Handle enum values
if (Array.isArray(jsonSchema.enum)) {
geminiSchema.enum = jsonSchema.enum.map(String);
}
// Handle array constraints
if (jsonSchemaType === "array") {
if (typeof jsonSchema.maxItems !== "undefined") {
geminiSchema.maxItems = String(jsonSchema.maxItems);
}
if (typeof jsonSchema.minItems !== "undefined") {
geminiSchema.minItems = String(jsonSchema.minItems);
}
// Handle array items
if (jsonSchema.items) {
geminiSchema.items = convertJsonSchemaToGeminiSchema(jsonSchema.items);
}
}
// Handle numeric constraints
if (typeof jsonSchema.minimum !== "undefined") {
geminiSchema.minimum = Number(jsonSchema.minimum);
}
if (typeof jsonSchema.maximum !== "undefined") {
geminiSchema.maximum = Number(jsonSchema.maximum);
}
// Handle properties for objects
if (jsonSchema.properties) {
geminiSchema.properties = {};
for (const [key, value] of Object.entries(jsonSchema.properties)) {
geminiSchema.properties[key] = convertJsonSchemaToGeminiSchema(value);
}
}
// Handle required properties
if (Array.isArray(jsonSchema.required)) {
geminiSchema.required = jsonSchema.required;
}
// Handle anyOf
if (Array.isArray(jsonSchema.anyOf)) {
geminiSchema.anyOf = jsonSchema.anyOf.map(convertJsonSchemaToGeminiSchema);
}
// TODO/UNSUPPORTED:
// format
// property ordering:
// if (Array.isArray(jsonSchema.propertyOrdering)) {
// geminiSchema.propertyOrdering = jsonSchema.propertyOrdering;
// }
return geminiSchema;
}
// https://ai.google.dev/api/caching#FunctionDeclaration
// Note "reponse" field (schema showing function output structure) is not supported at the moment
export function convertContinueToolToGeminiFunction(
tool: Tool,
): GeminiToolFunctionDeclaration {
if (!tool.function.name) {
throw new Error("Function name required");
}
const description = tool.function.description ?? "";
const name = tool.function.name;
const fn: GeminiToolFunctionDeclaration = {
description,
name,
};
if (
tool.function.parameters &&
"type" in tool.function.parameters &&
typeof tool.function.parameters.type === "string"
) {
// Gemini can't take an empty object
// So if empty object param is present just don't add parameters
if (tool.function.parameters.type === "object") {
if (JSON.stringify(tool.function.parameters.properties) === "{}") {
return fn;
}
}
fn.parameters = convertJsonSchemaToGeminiSchema(tool.function.parameters);
}
return fn;
}
export type GeminiTextContentPart = {
text: string;
};
export type GeminiInlineDataContentPart = {
inlineData: {
mimeType: string;
data: string;
};
};
export type GeminiFunctionCallContentPart = {
functionCall: {
id?: string;
name: string;
args: JSONSchema7Object;
};
};
export type GeminiFunctionResponseContentPart = {
functionResponse: {
id?: string;
name: string;
response: JSONSchema7Object;
};
};
export type GeminiFileDataContentPart = {
fileData: {
fileUri: string;
mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata
};
};
export type GeminiExecutableCodeContentPart = {
executableCode: {
language: "PYTHON" | "LANGUAGE_UNSPECIFIED";
code: string;
};
};
export type GeminiCodeExecutionResultContentPart = {
codeExecutionResult: {
outcome:
| "OUTCOME_UNSPECIFIED"
| "OUTCOME_OK"
| "OUTCOME_FAILED"
| "OUTCOME_DEADLINE_EXCEEDED";
output: string;
};
};
export type GeminiChatContentPart =
| {
text: string;
}
| {
inlineData: {
mimeType: string;
data: string;
};
}
| {
functionCall: {
name: string;
args: JSONSchema7Object;
};
}
| {
functionResponse: {
name: string;
response: JSONSchema7Object;
};
}
| {
fileData: {
fileUri: string;
mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata
};
}
| {
executableCode: {
language: "PYTHON" | "LANGUAGE_UNSPECIFIED";
code: string;
};
}
| {
codeExecutionResult: {
outcome:
| "OUTCOME_UNSPECIFIED"
| "OUTCOME_OK"
| "OUTCOME_FAILED"
| "OUTCOME_DEADLINE_EXCEEDED";
output: string;
};
};
| GeminiTextContentPart
| GeminiInlineDataContentPart
| GeminiFunctionCallContentPart
| GeminiFunctionResponseContentPart
| GeminiFileDataContentPart
| GeminiExecutableCodeContentPart
| GeminiCodeExecutionResultContentPart;
export interface GeminiChatContent {
role?: "user" | "model";
parts: GeminiChatContentPart[];
@ -88,7 +244,8 @@ export interface GeminiChatContent {
export interface GeminiToolFunctionDeclaration {
name: string;
description: string;
parameters?: GeminiFunctionSchema;
parameters?: GeminiObjectSchema;
response?: GeminiObjectSchema;
}
export interface GeminiTool {
functionDeclarations?: GeminiToolFunctionDeclaration[];

View file

@ -28,6 +28,7 @@ import FunctionNetwork from "./FunctionNetwork";
import Gemini from "./Gemini";
import Groq from "./Groq";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEI";
import HuggingFaceTGI from "./HuggingFaceTGI";
import Inception from "./Inception";
import Kindo from "./Kindo";
@ -57,6 +58,7 @@ import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import VertexAI from "./VertexAI";
import Vllm from "./Vllm";
import Voyage from "./Voyage";
import WatsonX from "./WatsonX";
import xAI from "./xAI";
@ -74,6 +76,7 @@ export const LLMClasses = [
Together,
Novita,
HuggingFaceTGI,
HuggingFaceTEIEmbeddingsProvider,
HuggingFaceInferenceAPI,
Kindo,
LlamaCpp,
@ -110,6 +113,7 @@ export const LLMClasses = [
Scaleway,
Relace,
Inception,
Voyage,
];
export async function llmFromDescription(

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

@ -51,7 +51,7 @@ export function toChatMessage(
type: toolCall.type!,
function: {
name: toolCall.function?.name!,
arguments: toolCall.function?.arguments!,
arguments: toolCall.function?.arguments! || "{}",
},
}));
}

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

@ -31,6 +31,13 @@ export const PROVIDER_TOOL_SUPPORT: Record<
return true;
}
},
azure: (model) => {
if (
model.toLowerCase().startsWith("gpt-4") ||
model.toLowerCase().startsWith("o3")
) return true;
return false;
},
openai: (model) => {
// https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
if (
@ -72,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 = "";

322
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",
@ -71,6 +71,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"
@ -105,7 +106,7 @@
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"../../../../../documents/code/continuedev/continue/packages/config-yaml": {
@ -133,7 +134,8 @@
"extraneous": true
},
"../packages/config-yaml": {
"version": "1.0.78",
"name": "@continuedev/config-yaml",
"version": "1.0.87",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -2901,6 +2903,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",
@ -2931,31 +2941,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": {
@ -4982,6 +5003,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",
@ -5628,8 +5654,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",
@ -5851,44 +5876,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": {
@ -6452,6 +6508,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",
@ -7079,9 +7166,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"
},
@ -7172,6 +7259,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",
@ -8074,6 +8166,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",
@ -8200,6 +8297,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",
@ -10936,6 +11038,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",
@ -11095,6 +11202,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",
@ -12102,6 +12225,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",
@ -12923,9 +13054,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",
@ -13745,6 +13877,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",
@ -14223,6 +14363,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",
@ -14529,16 +14677,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": {
@ -14706,6 +14855,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",
@ -14774,6 +14928,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",
@ -15581,6 +15743,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",
@ -105,12 +105,13 @@
"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"
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
}

View file

@ -32,6 +32,7 @@ import type {
ToolCall,
} from "../";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
import { ControlPlaneSessionInfo } from "../control-plane/client";
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
@ -50,6 +51,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, Session];
"history/save": [Session, void];
"history/clear": [undefined, void];
"devdata/log": [DevDataLogEvent, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [
@ -99,7 +101,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
selectedModelTitle: string;
},
ContextItemWithId[],
];
@ -154,7 +155,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"chatDescriber/describe": [
{
selectedModelTitle: string;
text: string;
},
string | undefined,
@ -201,13 +201,16 @@ 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,
];
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
};

View file

@ -100,12 +100,9 @@ export type ToIdeFromWebviewOrCoreProtocol = {
];
logoutOfControlPlane: [undefined, void];
reportError:[any, void];
closeSidebar: [undefined, void];
};
export type ToWebviewOrCoreFromIdeProtocol = {
didChangeActiveTextEditor: [{ filepath: string }, void];
didChangeControlPlaneSessionInfo: [
{ sessionInfo: ControlPlaneSessionInfo | undefined },
void,
];
};

View file

@ -14,6 +14,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"history/delete",
"history/load",
"history/save",
"history/clear",
"devdata/log",
"config/addModel",
"config/newPromptFile",
@ -61,6 +62,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"tools/call",
"controlPlane/openUrl",
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
];
// Message types to pass through from core to webview
@ -77,5 +80,7 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"setTTSActive",
"getWebviewHistoryLength",
"getCurrentSessionId",
"sessionUpdate",
"didCloseFiles",
"toolCallPartialOutput",
];

View file

@ -1,5 +1,6 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
import { ControlPlaneSessionInfo } from "../control-plane/client.js";
import type {
BrowserSerializedContinueConfig,
ContextItemWithId,
@ -40,4 +41,6 @@ export type ToWebviewFromIdeOrCoreProtocol = {
getWebviewHistoryLength: [undefined, number];
getCurrentSessionId: [undefined, string];
"jetbrains/setColors": [Record<string, string>, void];
sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
};

View file

@ -9,6 +9,7 @@ export enum BuiltInToolNames {
SearchWeb = "builtin_search_web",
ViewDiff = "builtin_view_diff",
LSTool = "builtin_ls",
CreateRuleBlock = "builtin_create_rule_block",
// excluded from allTools for now
ViewRepoMap = "builtin_view_repo_map",
@ -16,3 +17,5 @@ export enum BuiltInToolNames {
}
export const BUILT_IN_GROUP_NAME = "Built-In";
export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile];

View file

@ -1,9 +1,10 @@
import { ContextItem, Tool, ToolExtras } from "..";
import { MCPManagerSingleton } from "../context/mcp";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import { canParseUrl } from "../util/url";
import { BuiltInToolNames } from "./builtIn";
import { createNewFileImpl } from "./implementations/createNewFile";
import { createRuleBlockImpl } from "./implementations/createRuleBlock";
import { fileGlobSearchImpl } from "./implementations/globSearch";
import { grepSearchImpl } from "./implementations/grepSearch";
import { lsToolImpl } from "./implementations/lsTool";
@ -129,38 +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.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

@ -9,6 +9,7 @@ export const createNewFileTool: Tool = {
hasAlready: "created a new file at {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: true,
function: {
name: BuiltInToolNames.CreateNewFile,
description:

View file

@ -0,0 +1,36 @@
import { Tool } from "../..";
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 }}}"',
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`.",
parameters: {
type: "object",
required: ["rule_name", "rule_content"],
properties: {
rule_name: {
type: "string",
description:
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')",
},
rule_content: {
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.",
},
},
},
},
};

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

@ -8,6 +8,7 @@ export const globSearchTool: Tool = {
isCurrently: 'finding file matches for "{{{ pattern }}}"',
hasAlready: 'retreived file matches for "{{{ pattern }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.FileGlobSearch,

View file

@ -8,6 +8,7 @@ export const grepSearchTool: Tool = {
isCurrently: 'getting search results for "{{{ query }}}"',
hasAlready: 'retrieved search results for "{{{ query }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.GrepSearch,

View file

@ -9,6 +9,7 @@ export const lsTool: Tool = {
isCurrently: "listing files and folders in {{{ dirPath }}}",
hasAlready: "listed files and folders in {{{ dirPath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.LSTool,

View file

@ -8,6 +8,7 @@ export const readCurrentlyOpenFileTool: Tool = {
isCurrently: "reading the current file",
hasAlready: "viewed the current file",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ReadCurrentlyOpenFile,

View file

@ -8,6 +8,7 @@ export const readFileTool: Tool = {
isCurrently: "reading {{{ filepath }}}",
hasAlready: "viewed {{{ filepath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ReadFile,

View file

@ -12,17 +12,26 @@ export const runTerminalCommandTool: Tool = {
function: {
name: BuiltInToolNames.RunTerminalCommand,
description:
"Run a terminal command in the current directory. The shell is not stateful and will not remember any previous commands. Do NOT perform actions requiring special/admin priveleges.",
parameters: {
type: "object",
required: ["command"],
properties: {
command: {
type: "string",
description:
"The command to run. This will be passed directly into the IDE shell.",
"Run a terminal command in the current directory.\
The shell is not stateful and will not remember any previous commands.\
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
Do NOT perform actions requiring special/admin privileges.",
parameters: {
type: "object",
required: ["command"],
properties: {
command: {
type: "string",
description:
"The command to run. This will be passed directly into the IDE shell.",
},
waitForCompletion: {
type: "boolean",
description:
"Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
},
},
},
},
},
};

View file

@ -9,6 +9,7 @@ export const viewDiffTool: Tool = {
isCurrently: "getting the git diff",
hasAlready: "viewed the git diff",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ViewDiff,

View file

@ -9,6 +9,7 @@ export const viewRepoMapTool: Tool = {
isCurrently: "getting the repository map",
hasAlready: "viewed the repository map",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ViewRepoMap,

View file

@ -9,6 +9,7 @@ export const viewSubdirectoryTool: Tool = {
hasAlready: 'viewed a map of "{{{ directory_path }}}"',
readonly: true,
group: BUILT_IN_GROUP_NAME,
isInstant: true,
function: {
name: BuiltInToolNames.ViewSubdirectory,
description: "View the contents of a subdirectory",

View file

@ -0,0 +1,52 @@
import { ConfigYaml } from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { ToolImpl } from ".";
import { joinPathsToUri } from "../../util/uri";
export interface CreateRuleBlockArgs {
rule_name: string;
rule_content: string;
}
export const createRuleBlockImpl: ToolImpl = async (
args: CreateRuleBlockArgs,
extras,
) => {
// Sanitize rule name for use in filename (remove special chars, replace spaces with dashes)
const safeRuleName = args.rule_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,
],
};
// Convert the rule block to YAML
const ruleYaml = YAML.stringify(ruleBlock);
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const rulesDirUri = joinPathsToUri(
localContinueDir,
".continue",
"rules",
`${safeRuleName}.yaml`,
);
await extras.ide.writeFile(rulesDirUri, ruleYaml);
await extras.ide.openFile(rulesDirUri);
return [
{
name: "Rule Block Created",
description: `Created ${args.rule_name} rule`,
content: ruleYaml,
},
];
};

View file

@ -0,0 +1,334 @@
import { jest } from "@jest/globals";
import * as childProcess from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { IDE, ToolExtras } from "../..";
import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
import { runTerminalCommandImpl } from "./runTerminalCommand";
// We're using real child processes, so ensure these aren't mocked
jest.unmock("node:child_process");
jest.unmock("node:util");
describe("runTerminalCommandImpl", () => {
// Setup mocks and spies
const mockGetIdeInfo = jest.fn();
const mockGetWorkspaceDirs = jest.fn();
const mockOnPartialOutput = jest.fn();
const mockRunCommand = jest.fn();
// Use a simple approach to ensure background processes are terminated
let testPid: number | null = null;
// Create a temp directory for our tests
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'terminal-command-test-'));
beforeEach(() => {
jest.resetAllMocks();
// Setup backgrounded processes handling - don't mock, just make sure it's empty
// Get any processes that might be already tracked and clear them
const processMap = (processBackgroundStates as any).processTerminalBackgroundStates;
if (processMap && typeof processMap.clear === 'function') {
processMap.clear();
}
// Setup IDE mocks
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
mockGetWorkspaceDirs.mockReturnValue(Promise.resolve([`file://${tempDir}`]));
});
afterEach(async () => {
// Clean up any lingering test processes
if (testPid !== null) {
try {
// Platform-independent way to kill a process
if (process.platform === 'win32') {
await new Promise(resolve => {
childProcess.exec(`taskkill /F /PID ${testPid}`, () => resolve(null));
});
} else {
process.kill(testPid);
}
} catch (e) {
// Process might already be gone, ignore
}
testPid = null;
}
});
afterAll(() => {
// Clean up the temp directory after tests
fs.rmSync(tempDir, { recursive: true, force: true });
});
// Helper function to create a ToolExtras object
const createMockExtras = (overrides: Partial<{
onPartialOutput?: jest.Mock;
remoteName?: string;
}> = {}): ToolExtras => {
// Update IDE info if remoteName is provided
if (overrides.remoteName) {
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: overrides.remoteName }));
}
// Create a minimally compliant IDE mock
const mockIde = {
getIdeInfo: mockGetIdeInfo,
getWorkspaceDirs: mockGetWorkspaceDirs,
runCommand: mockRunCommand,
// Add stubs for other required IDE methods
getIdeSettings: jest.fn(),
getDiff: jest.fn(),
getClipboardContent: jest.fn(),
isTelemetryEnabled: jest.fn(),
readFile: jest.fn(),
writeFile: jest.fn(),
renameFile: jest.fn(),
deleteFile: jest.fn(),
globFiles: jest.fn(),
ls: jest.fn(),
};
// Create a base ToolExtras object with required properties
const baseExtras = {
ide: mockIde as unknown as IDE,
llm: {} as any,
fetch: {} as any,
tool: {} as any,
toolCallId: "test-tool-call"
} as ToolExtras;
// Apply overrides
if (overrides.onPartialOutput) {
baseExtras.onPartialOutput = overrides.onPartialOutput;
}
return baseExtras;
};
it("should execute a command synchronously and capture output", async () => {
// Use Node.js for cross-platform output generation
const command = `node -e "console.log('real test output')"`;
const args = { command, waitForCompletion: true };
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
// Verify real command output
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
expect(result[0].description).toBe("Terminal command output");
expect(result[0].content).toContain("real test output");
// Verify status field indicates successful completion
expect(result[0].status).toBe("Command completed");
});
it("should stream output when onPartialOutput is provided", async () => {
// This test uses Node to create a command that outputs data incrementally
const command = `node -e "
console.log('first output');
setTimeout(() => {
console.log('second output');
console.error('error output');
}, 50);
"`;
const args = { command, waitForCompletion: true };
const mockOutputFn = jest.fn();
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
// Execute the command with streaming
const result = await runTerminalCommandImpl(args, extras);
// Verify onPartialOutput was called with increasing content
expect(mockOutputFn).toHaveBeenCalled();
// Verify final result has all output
expect(result[0].content).toContain('first output');
expect(result[0].content).toContain('second output');
expect(result[0].content).toContain('error output');
// Verify status field indicates successful completion
expect(result[0].status).toBe("Command completed");
// Verify that initial streaming updates have empty status for regular commands
const firstCall = mockOutputFn.mock.calls[0][0];
if (firstCall && typeof firstCall === 'object') {
const contextItems = (firstCall as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
// For commands with waitForCompletion=true, status should be empty while streaming
expect(contextItems[0].status).toBe("");
}
}
});
it("should run commands in background when waitForCompletion is false", async () => {
// Create a self-identifying background process that writes its PID
// to a file we can access to kill it later
const pidFile = path.join(tempDir, 'test-pid.txt');
// This script creates a long-running process and writes its PID to our file
// Using a fixed duration timeout so we can be sure to clean it up
const command = `node -e "
const fs = require('fs');
console.log('starting background process with PID: ' + process.pid);
fs.writeFileSync('${pidFile}', process.pid.toString());
setTimeout(() => {
console.log('background process completed');
}, 500);
"`;
const args = { command, waitForCompletion: false };
const mockOutputFn = jest.fn();
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
const result = await runTerminalCommandImpl(args, extras);
// Result should indicate background running in either content or status
expect(result[0].content || result[0].status).toContain("running in the background");
// Verify status field indicates background running
expect(result[0].status).toBe("Command is running in the background...");
// Initial notification should indicate background running
expect(mockOutputFn).toHaveBeenCalled();
// Check the first call contains background running message
const firstCallData = mockOutputFn.mock.calls[0][0];
if (firstCallData && typeof firstCallData === 'object') {
const contextItems = (firstCallData as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
expect(contextItems[0].content).toContain("");
expect(contextItems[0].status).toMatch(/Command is running in the background.../);
}
}
// Wait a bit to make sure the PID file is written
await new Promise(resolve => setTimeout(resolve, 100));
// Read the PID file to get the process ID so we can kill it later
if (fs.existsSync(pidFile)) {
testPid = Number(fs.readFileSync(pidFile, 'utf-8'));
}
// Wait a bit longer for the process to complete and onPartialOutput to be called again
await new Promise(resolve => setTimeout(resolve, 400));
// Check for background process completion message in mockOutputFn calls
// Note: This is optional and depends on timing, so we don't want to strictly enforce it
let foundCompletionMessage = false;
for (let i = 0; i < mockOutputFn.mock.calls.length; i++) {
const call = mockOutputFn.mock.calls[i][0];
if (call && typeof call === 'object') {
const contextItems = (call as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
if (contextItems[0].status === "\nBackground command completed" ||
(contextItems[0].status && contextItems[0].status.includes("Background command"))) {
foundCompletionMessage = true;
break;
}
}
}
}
// If we found any completion message in the output, great!
// But we won't fail the test if we didn't, since it may be timing-dependent
if (mockOutputFn.mock.calls.length > 1) {
expect(foundCompletionMessage || true).toBeTruthy();
}
});
it("should handle remote environments", async () => {
// We'll keep mocking for remote environments as we can't test those directly
const args = { command: "echo 'test'", waitForCompletion: true };
const extras = createMockExtras({ remoteName: "ssh" });
const result = await runTerminalCommandImpl(args, extras);
// In remote environments, it should use the IDE's runCommand
expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'");
// Match the actual output message
expect(result[0].content).toContain("Terminal output not available");
expect(result[0].content).toContain("SSH environments");
// Verify status field indicates command failed in remote environments
expect(result[0].status).toBe("Command failed");
});
it("should handle errors when executing invalid commands", async () => {
// Use a command that should fail on any platform
const args = { command: "non-existent-command-xyz", waitForCompletion: true };
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result[0].name).toBe("Terminal");
expect(result[0].description).toBe("Terminal command output");
// The exact error message varies by platform, but should contain error information
const errorContent = result[0].content;
expect(
errorContent.includes("Command failed") ||
errorContent.includes("not found") ||
errorContent.includes("recognized") ||
/error/i.test(errorContent)
).toBe(true);
// Verify status field indicates command failure
expect(result[0].status).toContain("Command failed with:");
});
it("should handle error situations gracefully", async () => {
// Use Node.js script that writes to stderr for cross-platform testing
const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`;
const args = { command, waitForCompletion: true };
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
// Verify we still get a result with a name and description
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
expect(result[0].description).toBe("Terminal command output");
// The command should have executed and returned content
expect(result[0].content).toBeDefined();
// We should see the error message we wrote to stderr
expect(result[0].content).toContain("This is an error message");
// Verify status field indicates command failure - the exact message format can vary
// between different node versions and platforms
expect(result[0].status).toContain("Command failed");
});
it("should set appropriate status when a command completes successfully", async () => {
// Use a simple command that will succeed
const command = `node -e "console.log('success test')"`;
const args = { command, waitForCompletion: true };
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
expect(result[0].content).toContain("success test");
// Verify status field for successful command
expect(result[0].status).toBe("Command completed");
});
it("should include status info for background commands in non-streaming mode", async () => {
// Use a simple background command
const command = `node -e "setTimeout(() => console.log('done'), 300)"`;
const args = { command, waitForCompletion: false };
// No streaming in this test (no onPartialOutput)
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
// Verify both content and status fields for background commands
expect(result[0].content).toBe("Command is running in the background...");
expect(result[0].status).toBe("Command is running in the background...");
});
});

View file

@ -3,42 +3,270 @@ import util from "node:util";
import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
import { isProcessBackgrounded, removeBackgroundedProcess } from "../../util/processTerminalBackgroundStates";
const asyncExec = util.promisify(childProcess.exec);
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Default to waiting for completion if not specified
const waitForCompletion = args.waitForCompletion !== false;
const ideInfo = await extras.ide.getIdeInfo();
const toolCallId = extras.toolCallId || "";
if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") {
try {
const output = await asyncExec(args.command, {
cwd: fileURLToPath((await extras.ide.getWorkspaceDirs())[0]),
// For streaming output
if (extras.onPartialOutput) {
return new Promise((resolve, reject) => {
try {
const getWorkspaceDirsPromise = extras.ide.getWorkspaceDirs();
getWorkspaceDirsPromise
.then((workspaceDirs) => {
const cwd = fileURLToPath(workspaceDirs[0]);
let terminalOutput = "";
if (!waitForCompletion) {
const status = "Command is running in the background...";
if (extras.onPartialOutput) {
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: "",
status: status,
},
],
});
}
}
// Use spawn instead of exec to get streaming output
const childProc = childProcess.spawn(args.command, {
cwd,
shell: true,
});
childProc.stdout?.on("data", (data) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
const newOutput = data.toString();
terminalOutput += newOutput;
// Send partial output to UI
if (extras.onPartialOutput) {
const status = waitForCompletion ? "" : "Command is running in the background...";
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
],
});
}
});
childProc.stderr?.on("data", (data) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
const newOutput = data.toString();
terminalOutput += newOutput;
// Send partial output to UI, status is not required
if (extras.onPartialOutput) {
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
},
],
});
}
});
// If we don't need to wait for completion, resolve immediately
if (!waitForCompletion) {
const status = "Command is running in the background...";
resolve([
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
]);
}
childProc.on("close", (code) => {
// If this process has been backgrounded, clean it up from the map and return
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
}
if (!waitForCompletion) {
// Already resolved, just update the UI with final output
if (extras.onPartialOutput) {
const status = (code === 0 || !code
? "\nBackground command completed"
: `\nBackground command failed with exit code ${code}`)
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
],
});
}
} else {
// Normal completion, resolve now
if (code === 0) {
const status = "Command completed";
resolve([
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status
},
]);
} else {
const status = `Command failed with exit code ${code}`;
resolve([
{
name: "Terminal",
description: "Terminal command output",
content:
terminalOutput,
status: status,
},
]);
}
}
});
childProc.on("error", (error) => {
// If this process has been backgrounded, clean it up from the map and return
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
}
reject(error);
});
})
.catch((error) => {
reject(error);
});
} catch (error: any) {
reject(error);
}
});
return [
{
name: "Terminal",
description: "Terminal command output",
content: output.stdout ?? "",
},
];
} catch (error: any) {
return [
{
name: "Terminal",
description: "Terminal command output",
content: error.stderr || error.stdout || error.toString(),
},
];
} else {
// Fallback to non-streaming for older clients
const workspaceDirs = await extras.ide.getWorkspaceDirs();
const cwd = fileURLToPath(workspaceDirs[0]);
if (!waitForCompletion) {
// For non-streaming but also not waiting for completion, use spawn
// but don't attach any listeners other than error
try {
// Use spawn instead of exec but don't wait
const childProc = childProcess.spawn(args.command, {
cwd,
shell: true,
// Detach the process so it's not tied to the parent
detached: true,
// Redirect to /dev/null equivalent (works cross-platform)
stdio: 'ignore',
});
// Even for detached processes, add event handlers to clean up the background process map
childProc.on("close", () => {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
}
});
childProc.on("error", () => {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
}
});
// Unref the child to allow the Node.js process to exit
childProc.unref();
const status = "Command is running in the background...";
return [
{
name: "Terminal",
description: "Terminal command output",
content: status,
status: status,
},
];
} catch (error: any) {
const status = `Command failed with: ${error.message || error.toString()}`;
return [
{
name: "Terminal",
description: "Terminal command output",
content: status,
status: status
},
];
}
} else {
// Standard execution, waiting for completion
try {
const output = await asyncExec(args.command, { cwd });
const status = "Command completed";
return [
{
name: "Terminal",
description: "Terminal command output",
content: output.stdout ?? "",
status: status,
},
];
} catch (error: any) {
const status = `Command failed with: ${error.message || error.toString()}`;
return [
{
name: "Terminal",
description: "Terminal command output",
content: error.stderr ?? error.toString(),
status: status,
},
];
}
}
}
}
// For remote environments, just run the command
// Note: waitForCompletion is not supported in remote environments yet
await extras.ide.runCommand(args.command);
return [
{
name: "Terminal",
description: "Terminal command output",
content:
"[Terminal output not available. This is only available in local development environments and not in SSH environments for example.]",
"Terminal output not available. This is only available in local development environments and not in SSH environments for example.",
status: "Command failed",
},
];
};
}

View file

@ -1,4 +1,5 @@
import { createNewFileTool } from "./definitions/createNewFile";
import { createRuleBlock } from "./definitions/createRuleBlock";
import { editFileTool } from "./definitions/editFile";
import { globSearchTool } from "./definitions/globSearch";
import { grepSearchTool } from "./definitions/grepSearch";
@ -14,14 +15,13 @@ export const allTools = [
editFileTool,
createNewFileTool,
runTerminalCommandTool,
grepSearchTool,
globSearchTool,
searchWebTool,
viewDiffTool,
readCurrentlyOpenFileTool,
lsTool,
createRuleBlock,
// replacing with ls tool for now
// viewSubdirectoryTool,
// viewRepoMapTool,

View file

@ -4,7 +4,11 @@ import { Session, SessionMetadata } from "../index.js";
import { ListHistoryOptions } from "../protocol/core.js";
import { NEW_SESSION_TITLE } from "./constants.js";
import { getSessionFilePath, getSessionsListPath } from "./paths.js";
import {
getSessionFilePath,
getSessionsFolderPath,
getSessionsListPath,
} from "./paths.js";
function safeParseArray<T>(
value: string,
errorMessage: string = "Error parsing array",
@ -67,6 +71,10 @@ class HistoryManager {
);
}
clearAll() {
fs.rmSync(getSessionsFolderPath(), { recursive: true, force: true });
}
load(sessionId: string): Session {
try {
const sessionFile = getSessionFilePath(sessionId);

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

@ -0,0 +1,71 @@
import {
markProcessAsBackgrounded,
isProcessBackgrounded,
removeBackgroundedProcess
} from './processTerminalBackgroundStates';
describe('processTerminalBackgroundStates', () => {
beforeEach(() => {
// Clear any backgrounded processes before each test
const backgroundedProcesses = Array.from(
Object.getOwnPropertySymbols(global)
).find(symbol => String(symbol) === 'Symbol(processTerminalBackgroundStates)');
if (backgroundedProcesses) {
// Reset the map by reimporting the module
jest.resetModules();
}
});
test('should mark a process as backgrounded', () => {
const toolCallId = 'test-123';
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
});
test('should correctly identify non-backgrounded processes', () => {
const toolCallId = 'test-123';
const anotherToolCallId = 'test-456';
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
});
test('should remove a process from backgrounded state', () => {
const toolCallId = 'test-123';
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test('should handle removing non-existent processes', () => {
const toolCallId = 'test-123';
// Should not throw an error
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test('should handle multiple processes', () => {
const toolCallId1 = 'test-123';
const toolCallId2 = 'test-456';
const toolCallId3 = 'test-789';
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
expect(isProcessBackgrounded(toolCallId1)).toBe(true);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
expect(isProcessBackgrounded(toolCallId3)).toBe(false);
removeBackgroundedProcess(toolCallId1);
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
});
});

View file

@ -0,0 +1,17 @@
// Track which processes have been backgrounded
const processTerminalBackgroundStates = new Map<string, boolean>();
// Function to mark a process as backgrounded
export function markProcessAsBackgrounded(toolCallId: string): void {
processTerminalBackgroundStates.set(toolCallId, true);
}
// Function to check if a process is backgrounded
export function isProcessBackgrounded(toolCallId: string): boolean {
return processTerminalBackgroundStates.has(toolCallId);
}
// Function to remove a process from the backgrounded processes map
export function removeBackgroundedProcess(toolCallId: string): void {
processTerminalBackgroundStates.delete(toolCallId);
}

View file

@ -13,6 +13,6 @@
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
}

View file

@ -9,9 +9,10 @@ Agent offers the same functionality as Chat, while also including tools in the r
## The tool handshake
Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file.
Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file.
The following handshake describes how Agent uses tools:
1. In Agent mode, available tools are sent along with `user` chat requests
2. The model can choose to include a tool call in its response
3. The user gives permission. This step is skipped if the policy for that tool is set to `Automatic`
@ -32,7 +33,8 @@ Continue includes several built-in tools which provide the model access to IDE f
- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model
- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project
- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root
- **Search web** (`builtin_search_web`): Perform a web search to get top results
- **Search web** (`builtin_search_web`): Perform a web search to get top results
- **View diff** (`builtin_view_diff`): View the current working git diff
- **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map)
- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project
- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project
- **Create Rule Block** (`builtin_create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation

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.

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