Merge branch 'main' into Jazzcort/standardize-tooltip

This commit is contained in:
Jazzcort 2025-04-29 08:35:22 -04:00 • committed by GitHub
commit 49d35f5118
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
428 changed files with 17774 additions and 5231 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

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

View file

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

@ -32,7 +32,7 @@ const DraftIssueCommand: SlashCommand = {
let title = await llm.complete(
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
new AbortController().signal,
{ maxTokens: 20 },
{ maxTokens: 30 },
);
title = `${removeQuotesAndEscapes(title.trim())}\n\n`;
@ -40,7 +40,7 @@ const DraftIssueCommand: SlashCommand = {
let body = "";
const messages: ChatMessage[] = [
...history,
...history.filter((msg) => msg.role !== "system"),
{ role: "user", content: PROMPT(input, title) },
];

View file

@ -1,5 +1,6 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
import { ChatMessage, SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
export function constructMcpSlashCommand(
@ -22,8 +23,8 @@ export function constructMcpSlashCommand(
}
const result = await client.getPrompt({ name, arguments: argsObject });
const messages: ChatMessage[] = result.messages.map((msg) => {
const mcpMessages: PromptMessage[] = result.messages;
const messages: ChatMessage[] = mcpMessages.map((msg) => {
if (msg.content.type !== "text") {
throw new Error(
"Continue currently only supports text prompts through MCP",
@ -40,12 +41,22 @@ export function constructMcpSlashCommand(
return;
}
const reversedMessages = [...messages].reverse();
const messageToAppendInput =
reversedMessages.find((m) => m.role === "user") ??
reversedMessages.find((m) => m.role === "assistant") ??
reversedMessages[0];
messageToAppendInput.content += ` ${userInput}`;
if (userInput) {
const lastMessage = messages.at(-1);
if (!lastMessage || lastMessage.role !== "user") {
messages.push({
role: "user",
content: userInput,
});
} else {
let newContent = renderChatMessage(lastMessage);
if (newContent) {
newContent += "\n\n";
}
newContent += userInput;
lastMessage.content = newContent;
}
}
for await (const chunk of context.llm.streamChat(
messages,

View file

@ -4,7 +4,7 @@ import {
ControlPlaneClient,
ControlPlaneSessionInfo,
} from "../control-plane/client.js";
import { getControlPlaneEnv, useHub } from "../control-plane/env.js";
import { getControlPlaneEnv } from "../control-plane/env.js";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@ -15,8 +15,12 @@ import {
} from "../index.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getAllAssistantFiles } from "./loadLocalAssistants.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.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 {
@ -135,16 +139,11 @@ export class ConfigHandler {
const userId = await this.controlPlaneClient.userId;
if (userId) {
const orgDescs = await this.controlPlaneClient.listOrganizations();
if (await useHub(this.ideSettingsPromise)) {
const personalHubOrg = await this.getPersonalHubOrg();
const hubOrgs = await Promise.all(
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
);
return [...hubOrgs, personalHubOrg];
} else {
// Should only ever be one teams org. Will be removed soon anyways
return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org)));
}
const personalHubOrg = await this.getPersonalHubOrg();
const hubOrgs = await Promise.all(
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
);
return [...hubOrgs, personalHubOrg];
} else {
return [await this.getLocalOrg()];
}
@ -191,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);
}
@ -202,34 +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);
}
async getTeamsOrg(org: OrganizationDescription): Promise<OrgWithProfiles> {
const workspaces = await this.controlPlaneClient.listWorkspaces();
const profiles = await this.getAllLocalProfiles();
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.llmLogger,
this.reloadConfig.bind(this),
);
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
const localProfiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
return this.rectifyProfilesForOrg(org, profiles);
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
}
private async rectifyProfilesForOrg(
@ -276,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;
}
//////////////////
@ -446,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

@ -1,26 +0,0 @@
import { IDE } from "..";
import { joinPathsToUri } from "../util/uri";
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
export async function getSystemPromptDotFile(ide: IDE): Promise<string | null> {
const dirs = await ide.getWorkspaceDirs();
let prompts: string[] = [];
for (const dir of dirs) {
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
if (await ide.fileExists(dotFile)) {
try {
const content = await ide.readFile(dotFile);
prompts.push(content);
} catch (e) {
// ignore if file doesn't exist
}
}
}
if (!prompts.length) {
return null;
}
return prompts.join("\n\n");
}

View file

@ -0,0 +1,32 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "..";
import { joinPathsToUri } from "../util/uri";
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
export async function getWorkspaceContinueRuleDotFiles(ide: IDE) {
const dirs = await ide.getWorkspaceDirs();
const errors: ConfigValidationError[] = [];
const rules: RuleWithSource[] = [];
for (const dir of dirs) {
try {
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
const exists = await ide.fileExists(dotFile);
if (exists) {
const content = await ide.readFile(dotFile);
rules.push({
rule: content,
ruleFile: dotFile,
source: ".continuerules",
});
}
} catch (e) {
errors.push({
fatal: false,
message: `Failed to load system prompt dot file from workspace ${dir}: ${e instanceof Error ? e.message : e}`,
});
}
}
return { rules, errors };
}

View file

@ -18,7 +18,6 @@ import {
ContinueConfig,
ContinueRcJson,
CustomContextProvider,
CustomLLM,
EmbeddingsProviderDescription,
IContextProvider,
IDE,
@ -37,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";
@ -68,7 +67,6 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
getModelByRole,
@ -205,12 +203,6 @@ async function serializedToIntermediateConfig(
return config;
}
function isModelDescription(
llm: ModelDescription | CustomLLM,
): llm is ModelDescription {
return (llm as ModelDescription).title !== undefined;
}
export function isContextProviderWithParams(
contextProvider: CustomContextProvider | ContextProviderWithParams,
): contextProvider is ContextProviderWithParams {
@ -243,81 +235,81 @@ async function intermediateToFinalConfig({
// Auto-detect models
let models: BaseLLM[] = [];
for (const desc of config.models) {
if (isModelDescription(desc)) {
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
llmLogger,
config.completionOptions,
config.systemMessage,
);
if (!llm) {
continue;
}
if (llm.model === "AUTODETECT") {
try {
const modelNames = await llm.listModels();
const detectedModels = await Promise.all(
modelNames.map(async (modelName) => {
return await llmFromDescription(
{
...desc,
model: modelName,
title: modelName,
},
ide.readFile.bind(ide),
uniqueId,
ideSettings,
llmLogger,
copyOf(config.completionOptions),
config.systemMessage,
);
}),
);
models.push(
...(detectedModels.filter(
(x) => typeof x !== "undefined",
) as BaseLLM[]),
);
} catch (e) {
console.warn("Error listing models: ", e);
await Promise.all(
config.models.map(async (desc) => {
if ("title" in desc) {
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
llmLogger,
config.completionOptions,
);
if (!llm) {
return;
}
} else {
models.push(llm);
}
} else {
const llm = new CustomLLMClass({
...desc,
options: { ...desc.options, logger: llmLogger } as any,
});
if (llm.model === "AUTODETECT") {
try {
const modelNames = await llm.listModels();
const models = modelNames.map(
(modelName) =>
new CustomLLMClass({
...desc,
options: {
...desc.options,
model: modelName,
logger: llmLogger,
},
if (llm.model === "AUTODETECT") {
try {
const modelNames = await llm.listModels();
const detectedModels = await Promise.all(
modelNames.map(async (modelName) => {
return await llmFromDescription(
{
...desc,
model: modelName,
title: modelName,
},
ide.readFile.bind(ide),
uniqueId,
ideSettings,
llmLogger,
copyOf(config.completionOptions),
);
}),
);
models.push(...models);
} catch (e) {
console.warn("Error listing models: ", e);
);
models.push(
...(detectedModels.filter(
(x) => typeof x !== "undefined",
) as BaseLLM[]),
);
} catch (e) {
console.warn("Error listing models: ", e);
}
} else {
models.push(llm);
}
} else {
models.push(llm);
const llm = new CustomLLMClass({
...desc,
options: { ...desc.options, logger: llmLogger } as any,
});
if (llm.model === "AUTODETECT") {
try {
const modelNames = await llm.listModels();
const models = modelNames.map(
(modelName) =>
new CustomLLMClass({
...desc,
options: {
...desc.options,
model: modelName,
logger: llmLogger,
},
}),
);
models.push(...models);
} catch (e) {
console.warn("Error listing models: ", e);
}
} else {
models.push(llm);
}
}
}
}
}),
);
// Prepare models
for (const model of models) {
@ -353,7 +345,7 @@ async function intermediateToFinalConfig({
? config.tabAutocompleteModel
: [config.tabAutocompleteModel]
).map(async (desc) => {
if (isModelDescription(desc)) {
if ("title" in desc) {
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
@ -361,7 +353,6 @@ async function intermediateToFinalConfig({
ideSettings,
llmLogger,
config.completionOptions,
config.systemMessage,
);
if (llm?.providerName === "free-trial") {
@ -495,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);
@ -534,8 +525,16 @@ async function intermediateToFinalConfig({
rerank: newReranker ?? null,
summarize: null, // Not implemented
},
rules: [],
};
if (config.systemMessage) {
continueConfig.rules.unshift({
rule: config.systemMessage,
source: "json-systemMessage",
});
}
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
@ -610,7 +609,6 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
contextLength: llm.contextLength,
template: llm.template,
completionOptions: llm.completionOptions,
systemMessage: llm.systemMessage,
baseChatSystemMessage: llm.baseChatSystemMessage,
requestOptions: llm.requestOptions,
promptTemplates: serializePromptTemplates(llm.promptTemplates),
@ -626,7 +624,6 @@ async function finalToBrowserConfig(
): Promise<BrowserSerializedContinueConfig> {
return {
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map(
({ run, ...slashCommandDescription }) => slashCommandDescription,
@ -866,11 +863,6 @@ async function loadContinueConfigFromJson(
return { errors, config: undefined, configLoadInterrupted: true };
}
const systemPromptDotFile = await getSystemPromptDotFile(ide);
if (systemPromptDotFile) {
serialized.systemMessage = systemPromptDotFile;
}
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();

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

@ -1,80 +0,0 @@
import { ConfigJson } from "@continuedev/config-types";
import { ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { PRODUCTION_ENV } from "../../control-plane/env.js";
import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
SerializedContinueConfig,
} from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
export default class ControlPlaneProfileLoader implements IProfileLoader {
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
description: ProfileDescription;
workspaceSettings: ConfigJson | undefined;
constructor(
private readonly workspaceId: string,
private workspaceTitle: string,
private readonly controlPlaneClient: ControlPlaneClient,
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private llmLogger: ILLMLogger,
private readonly onReload: () => void,
) {
this.description = {
id: workspaceId,
profileType: "control-plane",
iconUrl: "",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
title: workspaceTitle,
errors: undefined,
uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`,
};
setInterval(async () => {
this.workspaceSettings =
await this.controlPlaneClient.getSettingsForWorkspace(
this.description.id,
);
this.onReload();
}, ControlPlaneProfileLoader.RELOAD_INTERVAL);
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const settings =
this.workspaceSettings ??
((await this.controlPlaneClient.getSettingsForWorkspace(
this.description.id,
)) as any);
const serializedConfig: SerializedContinueConfig = settings;
return await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigJson: serializedConfig,
overrideConfigYaml: undefined,
platformConfigMetadata: undefined,
profileId: this.workspaceId,
overrideConfigYamlByPath: undefined,
orgScopeId: null,
});
}
setIsActive(isActive: boolean): void {}
}

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,36 +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 { 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();
@ -88,10 +90,10 @@ export default async function doLoadConfig({
uniqueId,
llmLogger,
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
configYamlPath,
orgScopeId,
packageIdentifier,
workOsAccessToken,
});
newConfig = result.config;
errors = result.errors;
@ -120,6 +122,12 @@ export default async function doLoadConfig({
// Remove ability have undefined errors, just have an array
errors = [...(errors ?? [])];
// Add rules from .continuerules files
const { rules, errors: continueRulesErrors } =
await getWorkspaceContinueRuleDotFiles(ide);
newConfig.rules.unshift(...rules);
errors.push(...continueRulesErrors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
@ -229,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;
}
@ -958,7 +958,7 @@ declare global {
cacheBehavior?: CacheBehavior;
}
export interface EmbedOptions {
export interface JSONEmbedOptions {
apiBase?: string;
apiKey?: string;
model?: string;

View file

@ -1,14 +1,16 @@
import fs from "fs";
import os from "os";
import { ModelConfig } from "@continuedev/config-yaml";
import {
ContinueConfig,
ExperimentalModelRoles,
IDE,
ILLM,
ModelDescription,
JSONModelDescription,
PromptTemplate,
} from "../";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigFile } from "../util/paths";
@ -23,16 +25,21 @@ function stringify(obj: any, indentation?: number): string {
}
export function addModel(
model: ModelDescription,
model: JSONModelDescription,
role?: keyof ExperimentalModelRoles,
) {
editConfigFile(
(config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
if (config.models?.some((m) => stringify(m) === stringify(model))) {
return config;
}
if (config.models?.some((m: any) => m?.title === model.title)) {
model.title = `${model.title} (1)`;
const numMatches = config.models?.reduce(
(prev, curr) => (curr.title.startsWith(model.title) ? prev + 1 : prev),
0,
);
if (numMatches !== 0) {
model.title = `${model.title} (${numMatches})`;
}
config.models.push(model);
@ -51,22 +58,34 @@ export function addModel(
return config;
},
(config) => {
if (config.models?.some((m: any) => m?.title === model.title)) {
model.title = `${model.title} (1)`;
const numMatches = config.models?.reduce(
(prev, curr) =>
"name" in curr && curr.name.startsWith(model.title) ? prev + 1 : prev,
0,
);
if (numMatches !== 0) {
model.title = `${model.title} (${numMatches})`;
}
if (!config.models) {
config.models = [];
}
config.models.push({
const desc: ModelConfig = {
name: model.title,
provider: model.provider,
model: model.model,
apiKey: model.apiKey,
apiBase: model.apiBase,
defaultCompletionOptions: model.completionOptions,
});
};
if (model.systemMessage) {
desc.chatOptions = {
baseSystemMessage:
DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage,
};
}
config.models.push(desc);
return config;
},
);

View file

@ -0,0 +1,97 @@
import { BlockType, ConfigYaml } from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { IDE } from "../..";
import { joinPathsToUri } from "../../util/uri";
function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
const configYaml: ConfigYaml = {
name: `New ${blockType.slice(0, -1)}`,
version: "0.0.1",
schema: "v1",
};
switch (blockType) {
case "context":
configYaml.context = [
{
provider: "file",
},
];
break;
case "models":
configYaml.models = [
{
provider: "anthropic",
model: "claude-3-7-sonnet-latest",
apiKey: "${{ secrets.ANTHROPIC_API_KEY }}",
name: "Claude 3.7 Sonnet",
roles: ["chat", "edit"],
},
];
break;
case "rules":
configYaml.rules = ["Always give concise responses"];
break;
case "docs":
configYaml.docs = [
{
name: "New docs",
startUrl: "https://docs.continue.dev",
},
];
break;
case "prompts":
configYaml.prompts = [
{
name: "New prompt",
description: "New prompt",
prompt:
"Please write a thorough suite of unit tests for this code, making sure to cover all relevant edge cases",
},
];
break;
case "mcpServers":
configYaml.mcpServers = [
{
name: "New MCP server",
command: "npx",
args: ["-y", "<your-mcp-server>"],
env: {},
},
];
break;
}
return configYaml;
}
export async function createNewWorkspaceBlockFile(
ide: IDE,
blockType: BlockType,
): Promise<void> {
const workspaceDirs = await ide.getWorkspaceDirs();
if (workspaceDirs.length === 0) {
throw new Error(
"No workspace directories found. Make sure you've opened a folder in your IDE.",
);
}
const baseDirUri = joinPathsToUri(workspaceDirs[0], `.continue/${blockType}`);
// Find the first available filename
let counter = 0;
let fileUri: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
fileUri = joinPathsToUri(
baseDirUri,
`new-${blockType.slice(0, -1)}${suffix}.yaml`,
);
counter++;
} while (await ide.fileExists(fileUri));
await ide.writeFile(
fileUri,
YAML.stringify(getContentsForNewBlock(blockType)),
);
await ide.openFile(fileUri);
}

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,29 +1,31 @@
import fs from "node:fs";
import {
AssistantUnrolled,
BLOCK_TYPES,
ConfigResult,
ConfigValidationError,
FQSN,
isAssistantUnrolledNonNullable,
MCPServer,
ModelRole,
PlatformClient,
PackageIdentifier,
RegistryClient,
SecretResult,
unrollAssistantFromContent,
Rule,
unrollAssistant,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { dirname } from "node:path";
import {
ContinueConfig,
ExperimentalMCPOptions,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
ILLMLogger,
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";
@ -35,60 +37,108 @@ 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 { getSystemPromptDotFile } from "../getSystemPromptDotFile";
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 {
rule: rule,
source: "rules-block",
};
} else {
return {
source: "rules-block",
rule: rule.rule,
globs: rule.globs,
name: rule.name,
};
}
}
async function loadConfigYaml(
rawYaml: string,
overrideConfigYaml: AssistantUnrolled | undefined,
controlPlaneClient: ControlPlaneClient,
orgScopeId: string | null,
ideSettings: IdeSettings,
): Promise<ConfigResult<AssistantUnrolled>> {
function convertYamlMcpToContinueMcp(
server: MCPServer,
): ExperimentalMCPOptions {
return {
transport: {
type: "stdio",
command: server.command,
args: server.args ?? [],
env: server.env,
},
};
}
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,
ideSettings.enableControlServerBeta,
).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,
},
));
@ -117,32 +167,33 @@ 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 = {
slashCommands: [],
tools: [...allTools],
mcpServerStatuses: [],
systemMessage: config.rules?.join("\n"),
contextProviders: [],
modelsByRole: {
chat: [],
@ -162,6 +213,7 @@ async function configYamlToContinueConfig({
rerank: null,
summarize: null,
},
rules: [],
};
// Right now, if there are any missing packages in the config, then we will just throw an error
@ -177,8 +229,11 @@ async function configYamlToContinueConfig({
};
}
for (const rule of config.rules ?? []) {
continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
}
continueConfig.data = config.data;
continueConfig.rules = config.rules;
continueConfig.docs = config.docs?.map((doc) => ({
title: doc.name,
startUrl: doc.startUrl,
@ -186,21 +241,16 @@ async function configYamlToContinueConfig({
faviconUrl: doc.faviconUrl,
}));
continueConfig.experimental = {
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
transport: {
type: "stdio",
command: mcpServer.command,
args: mcpServer.args ?? [],
env: mcpServer.env,
},
})),
modelContextProtocolServers: config.mcpServers?.map(
convertYamlMcpToContinueMcp,
),
};
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
for (const file of promptFiles) {
promptFiles.forEach((file) => {
try {
const slashCommand = slashCommandFromPromptFileV1(
file.path,
@ -215,7 +265,7 @@ async function configYamlToContinueConfig({
message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
});
}
}
});
} catch (e) {
localErrors.push({
fatal: false,
@ -236,9 +286,9 @@ async function configYamlToContinueConfig({
});
// Models
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
try {
const llms = await llmsFromModelConfig({
model,
@ -246,7 +296,6 @@ async function configYamlToContinueConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config: continueConfig,
});
@ -366,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[];
@ -399,46 +451,39 @@ async function configYamlToContinueConfig({
return { config: continueConfig, errors: localErrors };
}
export async function loadContinueConfigFromYaml({
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
// workOsAccessToken,
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
configYamlPath,
orgScopeId,
}: {
export async function loadContinueConfigFromYaml(options: {
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
// workOsAccessToken: string | undefined;
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 {
@ -456,26 +501,9 @@ export async function loadContinueConfigFromYaml({
ideInfo,
uniqueId,
llmLogger,
platformConfigMetadata,
allowFreeTrial: true,
workOsAccessToken,
});
try {
const systemPromptDotFile = await getSystemPromptDotFile(ide);
if (systemPromptDotFile) {
if (continueConfig.systemMessage) {
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
} else {
continueConfig.systemMessage = systemPromptDotFile;
}
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`,
});
}
// Apply shared config
// TODO: override several of these values with user/org shared config
// Don't try catch this - has security implications and failure should be fatal

View file

@ -9,7 +9,6 @@ import {
} from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
const AUTODETECT = "AUTODETECT";
@ -32,14 +31,12 @@ async function modelConfigToBaseLLM({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM | undefined> {
const cls = getModelClass(model);
@ -63,8 +60,6 @@ async function modelConfigToBaseLLM({
logger: llmLogger,
uniqueId,
title: model.name,
systemMessage: config.systemMessage,
rules: config.rules,
promptTemplates: model.promptTemplates,
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
capabilities: {
@ -149,7 +144,6 @@ async function autodetectModels({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
}: {
llm: BaseLLM;
@ -158,7 +152,6 @@ async function autodetectModels({
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
try {
@ -179,7 +172,6 @@ async function autodetectModels({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
});
}),
@ -197,7 +189,6 @@ export async function llmsFromModelConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
@ -205,7 +196,6 @@ export async function llmsFromModelConfig({
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM({
@ -213,7 +203,6 @@ export async function llmsFromModelConfig({
uniqueId,
ideSettings,
llmLogger,
platformConfigMetadata,
config,
});
if (!baseLlm) {
@ -228,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":

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

@ -21,16 +21,6 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
const WORKOS_ENV_ID_PRODUCTION = "continue";
const WORKOS_ENV_ID_STAGING = "continue-staging";
export const PRODUCTION_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL:
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
CONTROL_PLANE_URL:
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
APP_URL: "https://app.continue.dev/",
};
const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/",
CONTROL_PLANE_URL: "https://api.continue.dev/",
@ -71,15 +61,11 @@ export async function getControlPlaneEnv(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<ControlPlaneEnv> {
const ideSettings = await ideSettingsPromise;
return getControlPlaneEnvSync(
ideSettings.continueTestEnvironment,
ideSettings.enableControlServerBeta,
);
return getControlPlaneEnvSync(ideSettings.continueTestEnvironment);
}
export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
enableControlServerBeta: IdeSettings["enableControlServerBeta"],
): ControlPlaneEnv {
// Note .local overrides .staging
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
@ -90,10 +76,6 @@ export function getControlPlaneEnvSync(
return STAGING_ENV;
}
if (enableControlServerBeta === true) {
return PRODUCTION_ENV;
}
const env =
ideTestEnvironment === "production"
? "hub"
@ -109,17 +91,12 @@ export function getControlPlaneEnvSync(
? STAGING_ENV
: env === "test"
? TEST_ENV
: env === "hub"
? PRODUCTION_HUB_ENV
: PRODUCTION_ENV;
: PRODUCTION_HUB_ENV;
}
export async function useHub(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<boolean> {
const ideSettings = await ideSettingsPromise;
if (ideSettings.enableControlServerBeta) {
return false;
}
return ideSettings.continueTestEnvironment !== "none";
}

View file

@ -4,7 +4,7 @@ import { v4 as uuidv4 } from "uuid";
import { CompletionProvider } from "./autocomplete/CompletionProvider";
import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
import { addModel, deleteModel } from "./config/util";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
@ -26,14 +26,20 @@ 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";
import {
ContextItemWithId,
DiffLine,
IdeSettings,
ModelDescription,
RangeInFile,
type ContextItem,
type ContextItemId,
type IDE,
type IndexingProgressUpdate,
@ -46,10 +52,12 @@ import {
setupLocalConfig,
setupQuickstartConfig,
} from "./config/onboarding";
import { MCPManagerSingleton } from "./context/mcp";
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { LLMError } from "./llm";
import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
@ -61,23 +69,29 @@ async function* streamDiffLinesGenerator(
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
): AsyncGenerator<DiffLine> {
const data = msg.data;
const llm = (await configHandler.loadConfig()).config?.selectedModelByRole
.chat;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Failed to load config");
}
const llm = config.selectedModelByRole.chat;
if (!llm) {
throw new Error("No chat model selected");
}
for await (const diffLine of streamDiffLines(
data.prefix,
data.highlighted,
data.suffix,
for await (const diffLine of streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
suffix: data.suffix,
llm,
data.input,
data.language,
false,
undefined,
)) {
rules: config.rules,
input: data.input,
language: data.language,
onlyOneInsertion: false,
overridePrompt: undefined,
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
break;
@ -164,8 +178,6 @@ export class Core {
this.configHandler.currentProfile?.profileDescription.id || null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg.id,
usingContinueForTeams: (await ideSettingsPromise)
.enableControlServerBeta,
});
// update additional submenu context providers registered via VSCode API
@ -246,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);
@ -257,9 +270,7 @@ export class Core {
stack: err.stack,
});
// Again, specifically for jetbrains to prevent duplicate error messages
// The same logic can currently be found in the webview protocol
// bc streaming errors are handled in the GUI
// just to prevent duplicate error messages in jetbrains (same logic in webview protocol)
if (
["llm/streamChat", "chatDescriber/describe"].includes(
message.messageType,
@ -271,7 +282,6 @@ export class Core {
}
});
// Special
on("abort", (msg) => {
this.abortedMessageIds.add(msg.messageId);
});
@ -300,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);
@ -323,6 +335,11 @@ export class Core {
await this.configHandler.reloadConfig();
});
on("config/addLocalWorkspaceBlock", async (msg) => {
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
await this.configHandler.reloadConfig();
});
on("config/openProfile", async (msg) => {
await this.configHandler.openConfigProfile(msg.data.profileId);
});
@ -337,7 +354,13 @@ export class Core {
});
on("config/refreshProfiles", async (msg) => {
const { selectOrgId, selectProfileId } = msg.data ?? {};
await this.configHandler.refreshAll();
if (selectOrgId) {
await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId);
} else if (selectProfileId) {
await this.configHandler.setSelectedProfileId(selectProfileId);
}
});
on("config/updateSharedConfig", async (msg) => {
@ -387,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));
@ -412,8 +440,6 @@ export class Core {
this.configHandler.currentProfile?.profileDescription.id ?? null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg.id,
usingContinueForTeams: (await ideSettingsPromise)
.enableControlServerBeta,
};
});
@ -451,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;
@ -492,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();
@ -534,10 +560,8 @@ export class Core {
}
});
// File changes
// TODO - remove remaining logic for these from IDEs where possible
on("files/changed", this.handleFilesChanged);
// File changes - TODO - remove remaining logic for these from IDEs where possible
on("files/changed", this.handleFilesChanged.bind(this));
const refreshIfNotIgnored = async (uris: string[]) => {
const toRefresh: string[] = [];
for (const uri of uris) {
@ -613,20 +637,26 @@ export class Core {
on("docs/getDetails", async (msg) => {
return await this.docsService.getDetails(msg.data.startUrl);
});
//
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,
);
@ -642,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);
}
@ -653,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");
@ -667,56 +697,65 @@ export class Core {
throw new Error(`Tool ${toolCall.function.name} not found`);
}
const llm = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!llm) {
if (!config.selectedModelByRole.chat) {
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,
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 } }) => {
const { config } = await this.configHandler.loadConfig();
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
});
if (!config) {
return false;
}
// Process state handlers
on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
markProcessAsBackgrounded(toolCallId);
});
const llm = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!llm) {
throw new Error("No chat model selected");
}
const tokens = countTokens(item.content);
if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
return true;
}
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 = config?.selectedModelByRole.chat;
if (!llm) {
throw new Error("No chat model selected");
}
const tokens = countTokens(item.content, llm.model);
if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
return true;
}
return false;
}
private handleAddAutocompleteModel(
@ -782,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 (
@ -876,7 +916,6 @@ export class Core {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
selectedModelTitle: string;
}>,
) => {
const { config } = await this.configHandler.loadConfig();
@ -994,25 +1033,23 @@ export class Core {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
for await (const update of (await this.codebaseIndexerPromise).refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
let updateToSend = { ...update };
// TODO reconsider this status overwrite?
// original goal was to not concern users with edge noncritical errors
if (update.status === "failed") {
updateToSend.status = "done";
updateToSend.desc = "Indexing complete";
updateToSend.progress = 1.0;
}
try {
for await (const update of (await this.codebaseIndexerPromise).refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index directories : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
@ -1030,22 +1067,22 @@ export class Core {
return;
}
this.indexingCancellationController = new AbortController();
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
files,
)) {
let updateToSend = { ...update };
if (update.status === "failed") {
updateToSend.status = "done";
updateToSend.desc = "Indexing complete";
updateToSend.progress = 1.0;
}
try{
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
files,
)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index files : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
@ -1055,4 +1092,19 @@ export class Core {
}
// private
handleIndexingError(e: any) {
if (e instanceof LLMError) {
// Need to report this specific error to the IDE for special handling
this.messenger.request("reportError", e);
}
// broadcast indexing error
let updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.sendIndexingErrorTelemetry(updateToSend);
}
}

View file

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

@ -2,7 +2,7 @@ import { DiffLine, ILLM } from "../..";
import { generateLines } from "../../diff/util";
import { supportedLanguages } from "../../util/treeSitter";
import { getUriFileExtension } from "../../util/uri";
import { deterministicApplyLazyEdit } from "./deterministic";
import { streamLazyApply } from "./streamLazyApply";
import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply";
@ -13,35 +13,44 @@ function canUseInstantApply(filename: string) {
export async function applyCodeBlock(
oldFile: string,
newFile: string,
newLazyFile: string,
filename: string,
llm: ILLM,
): Promise<[boolean, AsyncGenerator<DiffLine>]> {
// This was buggy, removed for now, maybe forever
// if (canUseInstantApply(filename)) {
// const diffLines = await deterministicApplyLazyEdit(
// oldFile,
// newFile,
// filename,
// );
): Promise<{
isInstantApply: boolean;
diffLinesGenerator: AsyncGenerator<DiffLine>;
}> {
if (canUseInstantApply(filename)) {
const diffLines = await deterministicApplyLazyEdit({
oldFile,
newLazyFile,
filename,
onlyFullFileRewrite: true,
});
// // Fall back to LLM method if we couldn't apply deterministically
// if (diffLines !== undefined) {
// const diffGenerator = generateLines(diffLines!);
// return [true, diffGenerator];
// }
// }
if (diffLines !== undefined) {
return {
isInstantApply: true,
diffLinesGenerator: generateLines(diffLines!),
};
}
}
// If the code block is a diff
if (isUnifiedDiffFormat(newFile)) {
if (isUnifiedDiffFormat(newLazyFile)) {
try {
const diffLines = applyUnifiedDiff(oldFile, newFile);
const diffGenerator = generateLines(diffLines!);
return [true, diffGenerator];
const diffLines = applyUnifiedDiff(oldFile, newLazyFile);
return {
isInstantApply: true,
diffLinesGenerator: generateLines(diffLines!),
};
} catch (e) {
console.error("Failed to apply unified diff", e);
}
}
return [false, streamLazyApply(oldFile, filename, newFile, llm)];
return {
isInstantApply: false,
diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm),
};
}

View file

@ -21,11 +21,11 @@ async function collectDiffs(
): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> {
const ourDiffs: DiffLine[] = [];
for (const diffLine of (await deterministicApplyLazyEdit(
for (const diffLine of (await deterministicApplyLazyEdit({
oldFile,
newFile,
newLazyFile: newFile,
filename,
)) ?? []) {
})) ?? []) {
ourDiffs.push(diffLine);
}

View file

@ -15,6 +15,11 @@ type AstReplacements = Array<{
replacementNodes: Parser.SyntaxNode[];
}>;
const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/;
export function isLazyText(text: string): boolean {
return LAZY_COMMENT_REGEX.test(text);
}
function reconstructNewFile(
oldFile: string,
newFile: string,
@ -121,11 +126,23 @@ function nodeSurroundedInLazyBlocks(
}
// TODO: If we don't have high confidence, return undefined to fall back to slower methods
export async function deterministicApplyLazyEdit(
oldFile: string,
newLazyFile: string,
filename: string,
): Promise<DiffLine[] | undefined> {
export async function deterministicApplyLazyEdit({
oldFile,
newLazyFile,
filename,
/**
* Using this as a flag to slowly reintroduce lazy applies.
* With this set, we will only attempt to deterministically apply
* when there are no lazy blocks and then just replace the whole file,
* and otherwise never use instant apply
*/
onlyFullFileRewrite = false,
}: {
oldFile: string;
newLazyFile: string;
filename: string;
onlyFullFileRewrite?: boolean;
}): Promise<DiffLine[] | undefined> {
const parser = await getParserForFile(filename);
if (!parser) {
return undefined;
@ -135,6 +152,20 @@ export async function deterministicApplyLazyEdit(
let newTree = parser.parse(newLazyFile);
let reconstructedNewFile: string | undefined = undefined;
if (onlyFullFileRewrite) {
if (!isLazyText(newTree.rootNode.text)) {
const diff = myersDiff(oldFile, newLazyFile);
if (shouldRejectDiff(diff)) {
return undefined;
}
return diff;
} else {
return undefined;
}
}
// If there is no lazy block anywhere, we add our own to the outsides
// so that large chunks of the file don't get removed
if (!findInAst(newTree.rootNode, isLazyBlock)) {
@ -198,11 +229,6 @@ export async function deterministicApplyLazyEdit(
return diff;
}
const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/;
export function isLazyLine(text: string): boolean {
return LAZY_COMMENT_REGEX.test(text);
}
function isLazyBlock(node: Parser.SyntaxNode): boolean {
// Special case for "{/* ... existing code ... */}"
if (
@ -213,7 +239,7 @@ function isLazyBlock(node: Parser.SyntaxNode): boolean {
return true;
}
return node.type.includes("comment") && isLazyLine(node.text);
return node.type.includes("comment") && isLazyText(node.text);
}
function stringsWithinLevDistThreshold(

View file

@ -1,4 +1,12 @@
import { ChatMessage, DiffLine, ILLM, Prediction } from "../";
import {
ChatMessage,
DiffLine,
ILLM,
Prediction,
RuleWithSource,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
@ -10,7 +18,9 @@ import {
} from "../autocomplete/filtering/streamTransforms/lineStream";
import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
function constructPrompt(
@ -47,16 +57,27 @@ function modelIsInept(model: string): boolean {
return !(model.includes("gpt") || model.includes("claude"));
}
export async function* streamDiffLines(
prefix: string,
highlighted: string,
suffix: string,
llm: ILLM,
input: string,
language: string | undefined,
onlyOneInsertion: boolean,
overridePrompt: ChatMessage[] | undefined,
): AsyncGenerator<DiffLine> {
export async function* streamDiffLines({
prefix,
highlighted,
suffix,
llm,
input,
language,
onlyOneInsertion,
overridePrompt,
rules,
}: {
prefix: string;
highlighted: string;
suffix: string;
llm: ILLM;
input: string;
language: string | undefined;
onlyOneInsertion: boolean;
overridePrompt: ChatMessage[] | undefined;
rules: RuleWithSource[];
}): AsyncGenerator<DiffLine> {
void Telemetry.capture(
"inlineEdit",
{
@ -78,9 +99,56 @@ export async function* streamDiffLines(
oldLines = [];
}
const prompt =
let prompt =
overridePrompt ??
constructPrompt(prefix, highlighted, suffix, llm, input, language);
// Rules will be included with edit prompt
// If any rules are present this will result in using chat instead of legacy completion
const lastUserMessage =
typeof prompt === "string"
? ({
role: "user",
content: prompt,
} as UserChatMessage)
: (findLast(
prompt,
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined);
const systemMessage = getSystemMessageWithRules({
rules,
userMessage: lastUserMessage,
baseSystemMessage: undefined,
});
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: "user",
content: prompt,
},
];
} else {
const curSysMsg = prompt.find((msg) => msg.role === "system");
if (curSysMsg) {
curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content;
} else {
// prompt.unshift({
// role: "system",
// content: systemMessage,
// });
}
}
}
const inept = modelIsInept(llm.model);
const prediction: Prediction = {

96
core/index.d.ts vendored
View file

@ -1,4 +1,8 @@
import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml";
import {
DataDestination,
ModelRole,
PromptTemplates,
} from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { LLMConfigurationStatuses } from "./llm/constants";
import { GetGhTokenArgs } from "./protocol/ide";
@ -153,6 +157,10 @@ export interface ModelInstaller {
signal: AbortSignal,
progressReporter?: (task: string, increment: number, total: number) => void,
): Promise<any>;
isInstallingModel(
modelName: string
): Promise<boolean>;
}
export type ContextProviderType = "normal" | "query" | "submenu";
@ -395,6 +403,7 @@ export interface ContextItem {
icon?: string;
uri?: ContextItemUri;
hidden?: boolean;
status?: string;
}
export interface ContextItemWithId extends ContextItem {
@ -427,6 +436,7 @@ export type ToolStatus =
| "generating"
| "generated"
| "calling"
| "errored"
| "done"
| "canceled";
@ -559,18 +569,16 @@ export interface LLMOptions {
title?: string;
uniqueId?: string;
systemMessage?: string;
baseChatSystemMessage?: string;
contextLength?: number;
maxStopWords?: number;
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;
rules?: Rule[];
apiKey?: string;
// continueProperties
@ -701,7 +709,6 @@ export interface IdeSettings {
remoteConfigServerUrl: string | undefined;
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
continueTestEnvironment: "none" | "production" | "staging" | "local";
pauseCodebaseIndexOnStart: boolean;
}
@ -967,6 +974,11 @@ export interface ToolExtras {
llm: ILLM;
fetch: FetchFunction;
tool: Tool;
toolCallId?: string;
onPartialOutput?: (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => void;
}
export interface Tool {
@ -983,6 +995,7 @@ export interface Tool {
isCurrently?: string;
hasAlready?: string;
readonly: boolean;
isInstant?: boolean;
uri?: string;
faviconUrl?: string;
group: string;
@ -1028,9 +1041,8 @@ export interface ModelDescription {
model: string;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
apiBase?: string;
apiKeyLocation?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
@ -1039,7 +1051,6 @@ export interface ModelDescription {
maxStopWords?: number;
template?: TemplateType;
completionOptions?: BaseCompletionOptions;
systemMessage?: string;
baseChatSystemMessage?: string;
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
@ -1049,7 +1060,7 @@ export interface ModelDescription {
configurationStatus?: LLMConfigurationStatuses;
}
export interface EmbedOptions {
export interface JSONEmbedOptions {
apiBase?: string;
apiKey?: string;
model?: string;
@ -1070,7 +1081,7 @@ export interface EmbedOptions {
projectId?: string;
}
export interface EmbeddingsProviderDescription extends EmbedOptions {
export interface EmbeddingsProviderDescription extends JSONEmbedOptions {
provider: string;
}
@ -1209,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"
@ -1294,11 +1306,39 @@ export interface AnalyticsConfig {
clientKey?: string;
}
export interface JSONModelDescription {
title: string;
provider: string;
model: string;
apiKey?: string;
apiBase?: string;
contextLength?: number;
maxStopWords?: number;
template?: TemplateType;
completionOptions?: BaseCompletionOptions;
systemMessage?: string;
requestOptions?: RequestOptions;
cacheBehavior?: CacheBehavior;
region?: string;
profile?: string;
modelArn?: string;
apiType?: "openai" | "azure";
apiVersion?: string;
deployment?: string;
projectId?: string;
accountId?: string;
aiGatewaySlug?: string;
useLegacyCompletionsEndpoint?: boolean;
deploymentId?: string;
}
// config.json
export interface SerializedContinueConfig {
env?: string[];
allowAnonymousTelemetry?: boolean;
models: ModelDescription[];
models: JSONModelDescription[];
systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
@ -1309,7 +1349,7 @@ export interface SerializedContinueConfig {
disableSessionTitles?: boolean;
userToken?: string;
embeddingsProvider?: EmbeddingsProviderDescription;
tabAutocompleteModel?: ModelDescription | ModelDescription[];
tabAutocompleteModel?: JSONModelDescription | JSONModelDescription[];
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
ui?: ContinueUIConfig;
reranker?: RerankerDescription;
@ -1329,11 +1369,11 @@ export type ContinueRcJson = Partial<SerializedContinueConfig> & {
export interface Config {
/** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://docs.continue.dev/telemetry */
allowAnonymousTelemetry?: boolean;
/** Each entry in this array will originally be a ModelDescription, the same object from your config.json, but you may add CustomLLMs.
/** Each entry in this array will originally be a JSONModelDescription, the same object from your config.json, but you may add CustomLLMs.
* A CustomLLM requires you only to define an AsyncGenerator that calls the LLM and yields string updates. You can choose to define either `streamCompletion` or `streamChat` (or both).
* Continue will do the rest of the work to construct prompt templates, handle context items, prune context, etc.
*/
models: (CustomLLM | ModelDescription)[];
models: (CustomLLM | JSONModelDescription)[];
/** A system message to be followed by all of your models */
systemMessage?: string;
/** The default completion options for all models */
@ -1357,8 +1397,8 @@ export interface Config {
/** The model that Continue will use for tab autocompletions. */
tabAutocompleteModel?:
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
| JSONModelDescription
| (CustomLLM | JSONModelDescription)[];
/** Options for tab autocomplete */
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
/** UI styles customization */
@ -1375,7 +1415,7 @@ export interface Config {
// in the actual Continue source code
export interface ContinueConfig {
allowAnonymousTelemetry?: boolean;
systemMessage?: string;
// systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands: SlashCommand[];
@ -1390,7 +1430,7 @@ export interface ContinueConfig {
docs?: SiteIndexingConfig[];
tools: Tool[];
mcpServerStatuses: MCPServerStatus[];
rules?: Rule[];
rules: RuleWithSource[];
modelsByRole: Record<ModelRole, ILLM[]>;
selectedModelByRole: Record<ModelRole, ILLM | null>;
data?: DataDestination[];
@ -1398,7 +1438,7 @@ export interface ContinueConfig {
export interface BrowserSerializedContinueConfig {
allowAnonymousTelemetry?: boolean;
systemMessage?: string;
// systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands: SlashCommandDescription[];
@ -1412,7 +1452,7 @@ export interface BrowserSerializedContinueConfig {
docs?: SiteIndexingConfig[];
tools: Tool[];
mcpServerStatuses: MCPServerStatus[];
rules?: Rule[];
rules: RuleWithSource[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
modelsByRole: Record<ModelRole, ModelDescription[]>;
@ -1459,4 +1499,20 @@ export type PackageDocsResult = {
export interface TerminalOptions {
reuseTerminal?: boolean;
terminalName?: string;
waitForCompletion?: boolean;
}
export interface RuleWithSource {
name?: string;
slug?: string;
source:
| "default"
| "model-chat-options"
| "rules-block"
| "json-systemMessage"
| ".continuerules";
globs?: string | string[];
rule: string;
description?: string;
ruleFile?: string;
}

View file

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

View file

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

View file

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

View file

@ -175,7 +175,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
lower.includes("pplx") ||
lower.includes("gemini") ||
lower.includes("grok") ||
lower.includes("moonshot")
lower.includes("moonshot") ||
lower.includes("mercury")
) {
return undefined;
}

View file

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

View file

@ -1,16 +1,29 @@
import { ChatHistoryItem, ChatMessage, MessagePart } from "../";
import {
ChatHistoryItem,
ChatMessage,
RuleWithSource,
TextMessagePart,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import { isUserOrToolMsg } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
const DEFAULT_SYSTEM_MESSAGE = `\
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
Always include the language and file name in the info string when you write code blocks.
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
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 }}
@ -22,6 +35,22 @@ const DEFAULT_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
@ -29,23 +58,16 @@ const DEFAULT_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[],
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
);
const msgs: ChatMessage[] = [];
msgs.push({
role: "system",
content: baseChatSystemMessage ?? DEFAULT_SYSTEM_MESSAGE,
});
for (let i = 0; i < filteredHistory.length; i++) {
const historyItem = filteredHistory[i];
@ -53,26 +75,43 @@ export function constructMessages(
// Gather context items for user messages
let content = normalizeToMessageParts(historyItem.message);
const ctxItems = historyItem.contextItems.map((ctxItem) => {
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
});
const ctxItems = historyItem.contextItems
.map((ctxItem) => {
return {
type: "text",
text: `${ctxItem.content}\n`,
} as TextMessagePart;
})
.filter((part) => !!part.text.trim());
content = [...ctxItems, ...content];
msgs.push({
...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 lastUserMsg = findLast(msgs, isUserOrToolMsg) as
| UserChatMessage
| ToolResultChatMessage
| undefined;
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
rules,
userMessage: lastUserMsg,
});
if (systemMessage.trim()) {
msgs.unshift({
role: "system",
content: systemMessage,
});
}
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const { id, ...rest } = msg as any;

View file

@ -1,13 +1,7 @@
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import {
ChatMessage,
MessageContent,
MessagePart,
UserChatMessage,
} from "../index.js";
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
import { Rule } from "@continuedev/config-yaml";
import { renderChatMessage } from "../util/messageContent.js";
import {
AsyncEncoder,
@ -15,10 +9,14 @@ import {
LlamaAsyncEncoder,
} from "./asyncEncoder.js";
import { autodetectTemplateType } from "./autodetect.js";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
import llamaTokenizer from "./llamaTokenizer.js";
import { isRuleActive } from "./rules/isRuleActive.js";
import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js";
import {
addSpaceToAnyEmptyMessages,
chatMessageIsEmpty,
flattenMessages,
isUserOrToolMsg,
messageHasToolCallId,
} from "./messages.js";
interface Encoding {
encode: Tiktoken["encode"];
decode: Tiktoken["decode"];
@ -126,29 +124,49 @@ function countTokens(
}
}
function messageHasToolCalls(msg: ChatMessage): boolean {
return msg.role === "assistant" && !!msg.toolCalls;
}
// 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;
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
const flattened: ChatMessage[] = [];
let numTokens = 12;
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
if (
flattened.length > 0 &&
flattened[flattened.length - 1].role === msg.role &&
!messageHasToolCalls(msg) &&
!messageHasToolCalls(flattened[flattened.length - 1])
) {
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
} else {
flattened.push(msg);
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 flattened;
return numTokens + 12;
}
function countChatMessageTokens(
@ -158,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(
@ -220,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,
@ -227,349 +289,35 @@ 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,
chatHistory: ChatMessage[],
contextLength: number,
tokensForCompletion: number,
): ChatMessage[] {
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;
}
return chatHistory;
}
function messageIsEmpty(message: ChatMessage): boolean {
if (typeof message.content === "string") {
return message.content.trim() === "";
}
if (Array.isArray(message.content)) {
return message.content.every(
(item) => item.type === "text" && item.text?.trim() === "",
);
}
return false;
}
function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] {
return messages.map((message) => {
if (messageIsEmpty(message)) {
message.content = " ";
}
return message;
});
}
function chatMessageIsEmpty(message: ChatMessage): boolean {
switch (message.role) {
case "system":
case "user":
return (
typeof message.content === "string" && message.content.trim() === ""
);
case "assistant":
return (
typeof message.content === "string" &&
message.content.trim() === "" &&
!message.toolCalls
);
case "thinking":
case "tool":
return false;
}
}
function addSystemMessage({
messages,
systemMessage,
originalMessages,
}: {
messages: ChatMessage[];
systemMessage: string | undefined;
originalMessages: ChatMessage[] | undefined;
}): ChatMessage[] {
if (
!(systemMessage && systemMessage.trim() !== "") &&
originalMessages?.[0]?.role !== "system"
) {
return messages;
}
let content = "";
if (originalMessages?.[0]?.role === "system") {
content = renderChatMessage(originalMessages[0]);
}
if (systemMessage && systemMessage.trim() !== "") {
const shouldAddNewLines = content !== "";
if (shouldAddNewLines) {
content += "\n\n";
}
content += systemMessage;
}
const systemChatMsg: ChatMessage = {
role: "system",
content,
};
// Insert as second to last
messages.splice(-1, 0, systemChatMsg);
return messages;
}
function getMessageStringContent(message?: UserChatMessage): string {
if (!message) {
return "";
}
if (typeof message.content === "string") {
return message.content;
}
// Handle MessagePart array
return message.content
.map((part) => {
if (part.type === "text") {
return part.text;
}
return "";
})
.join("\n");
}
const getSystemMessage = ({
userMessage,
rules,
currentModel,
}: {
userMessage?: UserChatMessage;
rules: Rule[];
currentModel: string;
}) => {
const messageStringContent = getMessageStringContent(userMessage);
const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent);
return rules
.filter((rule) => {
return isRuleActive({
rule,
activePaths: filePathsFromMessage,
currentModel,
});
})
.map((rule) => {
if (typeof rule === "string") {
return rule;
}
return rule.rule;
})
.join("\n");
};
function getLastUserMessage(
messages: ChatMessage[],
): UserChatMessage | undefined {
// Iterate backwards through messages to find the last user message
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === "user") {
return messages[i] as UserChatMessage;
}
}
return undefined;
}
/*
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,
prompt,
functions,
systemMessage,
rules,
tools,
}: {
modelName: string;
msgs: ChatMessage[] | undefined;
msgs: ChatMessage[];
contextLength: number;
maxTokens: number;
supportsImages: boolean;
prompt: string | undefined;
functions: any[] | undefined;
systemMessage: string | undefined;
rules: Rule[];
tools?: Tool[];
}): ChatMessage[] {
let msgsCopy = msgs
? msgs
.map((msg) => ({ ...msg }))
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
: [];
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
if (prompt) {
const promptMsg: ChatMessage = {
role: "user",
content: prompt,
};
msgsCopy.push(promptMsg);
}
const lastUserMessage = getLastUserMessage(msgsCopy);
msgsCopy = addSystemMessage({
messages: msgsCopy,
systemMessage:
systemMessage ??
getSystemMessage({
userMessage: lastUserMessage,
rules,
currentModel: modelName,
}),
originalMessages: msgs,
});
let functionTokens = 0;
if (functions) {
for (const func of functions) {
functionTokens += countTokens(JSON.stringify(func), modelName);
}
}
if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) {
throw new Error(
`maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`,
);
}
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
// If images not supported, convert MessagePart[] to string
if (!supportsImages) {
@ -581,20 +329,118 @@ function compileChatMessages({
}
}
const history = pruneChatHistory(
modelName,
msgsCopy,
contextLength,
functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY,
);
// Extract system message
const systemMsg = msgsCopy.find((msg) => msg.role === "system");
msgsCopy = msgsCopy.filter((msg) => msg.role !== "system");
if (history.length >= 2 && history[history.length - 2].role === "system") {
const movedSystemMessage = history.splice(-2, 1)[0];
history.unshift(movedSystemMessage);
// 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 flattenedHistory = flattenMessages(history);
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;
}

View file

@ -35,7 +35,6 @@ describe("BaseLLM", () => {
const options: LLMOptions = {
model: "gpt-3.5-turbo",
uniqueId: "testId",
systemMessage: "Test System Message",
contextLength: 1024,
completionOptions: {
model: "some-model",
@ -62,7 +61,6 @@ describe("BaseLLM", () => {
expect(instance.title).toBeDefined();
expect(instance.uniqueId).toBe("testId");
expect(instance.model).toBe("gpt-3.5-turbo");
expect(instance.systemMessage).toBe("Test System Message");
expect(instance.contextLength).toBe(1024);
expect(instance.completionOptions.maxTokens).toBe(150);
expect(instance.requestOptions).toEqual({});

View file

@ -1,4 +1,4 @@
import { ModelRole, Rule } from "@continuedev/config-yaml";
import { ModelRole } from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { findLlmInfo } from "@continuedev/llm-info";
import {
@ -40,7 +40,6 @@ import {
modelSupportsImages,
} from "./autodetect.js";
import {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_BATCH_SIZE,
@ -72,7 +71,7 @@ export class LLMError extends Error {
}
export function isModelInstaller(provider: any): provider is ModelInstaller {
return provider && typeof provider.installModel === "function";
return provider && typeof provider.installModel === "function" && typeof provider.isInstallingModel === "function";;
}
type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
@ -126,7 +125,6 @@ export abstract class BaseLLM implements ILLM {
model: string;
title?: string;
systemMessage?: string;
baseChatSystemMessage?: string;
contextLength: number;
maxStopWords?: number | undefined;
@ -149,7 +147,6 @@ export abstract class BaseLLM implements ILLM {
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
rules?: Rule[];
deployment?: string;
apiVersion?: string;
@ -195,7 +192,6 @@ export abstract class BaseLLM implements ILLM {
this.title = options.title;
this.uniqueId = options.uniqueId ?? "None";
this.systemMessage = options.systemMessage;
this.baseChatSystemMessage = options.baseChatSystemMessage;
this.contextLength =
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
@ -250,7 +246,6 @@ export abstract class BaseLLM implements ILLM {
this.accountId = options.accountId;
this.capabilities = options.capabilities;
this.roles = options.roles;
this.rules = options.rules;
this.deployment = options.deployment;
this.apiVersion = options.apiVersion;
@ -285,77 +280,18 @@ export abstract class BaseLLM implements ILLM {
return Promise.resolve([]);
}
private _compileChatMessages(
options: CompletionOptions,
messages: ChatMessage[],
functions?: any[],
) {
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(),
prompt: undefined,
functions,
systemMessage: this.systemMessage,
rules: this.rules ?? [],
});
}
private _templatePromptLikeMessages(prompt: string): string {
if (!this.templateMessages) {
return prompt;
}
// NOTE system message no longer supported here
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
const systemMessage = this.systemMessage;
if (systemMessage) {
msgs.unshift({ role: "system", content: systemMessage });
}
return this.templateMessages(msgs);
}
private _compilePromptForLog(
prompt: string,
completionOptions: CompletionOptions,
): string {
const completionOptionsLog = JSON.stringify(
{
contextLength: this.contextLength,
...completionOptions,
},
null,
2,
);
let requestOptionsLog = "";
if (this.requestOptions) {
requestOptionsLog = JSON.stringify(this.requestOptions, null, 2);
}
return (
"##### Completion options #####\n" +
completionOptionsLog +
(requestOptionsLog
? "\n\n##### Request options #####\n" + requestOptionsLog
: "") +
"\n\n##### Prompt #####\n" +
prompt
);
}
private _logEnd(
model: string,
prompt: string,
@ -920,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

@ -30,15 +30,17 @@ class Anthropic extends BaseLLM {
description: tool.function.description,
input_schema: tool.function.parameters,
})),
thinking: options.reasoning ? {
type: "enabled",
budget_tokens: options.reasoningBudgetTokens,
} : undefined,
thinking: options.reasoning
? {
type: "enabled",
budget_tokens: options.reasoningBudgetTokens,
}
: undefined,
tool_choice: options.toolChoice
? {
type: "tool",
name: options.toolChoice.function.name,
}
type: "tool",
name: options.toolChoice.function.name,
}
: undefined,
};
@ -70,19 +72,23 @@ class Anthropic extends BaseLLM {
} else if (message.role === "thinking" && !message.redactedThinking) {
return {
role: "assistant",
content: [{
type: "thinking",
thinking: message.content,
signature: message.signature
}]
content: [
{
type: "thinking",
thinking: message.content,
signature: message.signature,
},
],
};
} else if (message.role === "thinking" && message.redactedThinking) {
return {
role: "assistant",
content: [{
type: "redacted_thinking",
data: message.redactedThinking
}]
content: [
{
type: "redacted_thinking",
data: message.redactedThinking,
},
],
};
}
@ -172,11 +178,12 @@ class Anthropic extends BaseLLM {
);
}
const shouldCacheSystemMessage =
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(
const systemMessage = stripImages(
messages.filter((m) => m.role === "system")[0]?.content ?? "",
);
const shouldCacheSystemMessage = !!(
this.cacheBehavior?.cacheSystemMessage && systemMessage
);
const msgs = this.convertMessages(messages);
const response = await this.fetch(new URL("messages", this.apiBase), {
@ -195,12 +202,12 @@ class Anthropic extends BaseLLM {
messages: msgs,
system: shouldCacheSystemMessage
? [
{
type: "text",
text: this.systemMessage,
cache_control: { type: "ephemeral" },
},
]
{
type: "text",
text: systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
}),
signal,
@ -240,7 +247,11 @@ class Anthropic extends BaseLLM {
// handle redacted thinking
if (value.content_block.type === "redacted_thinking") {
console.log("redacted thinking", value.content_block.data);
yield { role: "thinking", content: "", redactedThinking: value.content_block.data };
yield {
role: "thinking",
content: "",
redactedThinking: value.content_block.data,
};
}
break;
case "content_block_delta":
@ -253,7 +264,11 @@ class Anthropic extends BaseLLM {
yield { role: "thinking", content: value.delta.thinking };
break;
case "signature_delta":
yield { role: "thinking", content: "", signature: value.delta.signature };
yield {
role: "thinking",
content: "",
signature: value.delta.signature,
};
break;
case "input_json_delta":
if (!lastToolUseId || !lastToolUseName) {

View file

@ -14,10 +14,10 @@ import {
CompletionOptions,
LLMOptions,
} from "../../index.js";
import { getSecureID } from "../utils/getSecureID.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
import { getSecureID } from "../utils/getSecureID.js";
interface ModelConfig {
formatPayload: (text: string) => any;
@ -285,10 +285,13 @@ class Bedrock extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): any {
const systemMessage = stripImages(
messages.find((m) => m.role === "system")?.content ?? "",
);
const convertedMessages = this._convertMessages(messages);
const shouldCacheSystemMessage =
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
!!systemMessage && this.cacheBehavior?.cacheSystemMessage;
const enablePromptCaching =
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
@ -305,10 +308,10 @@ class Bedrock extends BaseLLM {
return {
modelId: options.model,
messages: convertedMessages,
system: this.systemMessage
system: systemMessage
? shouldCacheSystemMessage
? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }]
: [{ text: this.systemMessage }]
? [{ text: systemMessage }, { cachePoint: { type: "default" } }]
: [{ text: systemMessage }]
: undefined,
toolConfig:
supportsTools && options.tools

View file

@ -4,7 +4,7 @@ import {
CompletionOptions,
LLMOptions,
} from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamJSON } from "../stream.js";
@ -67,6 +67,11 @@ class Cohere extends BaseLLM {
...this.requestOptions?.headers,
};
let preamble: string | undefined = undefined;
const systemMessage = messages.find((m) => m.role === "system")?.content;
if (systemMessage) {
preamble = stripImages(systemMessage);
}
const resp = await this.fetch(new URL("chat", this.apiBase), {
method: "POST",
headers,
@ -74,7 +79,7 @@ class Cohere extends BaseLLM {
...this._convertArgs(options),
message: messages.pop()?.content,
chat_history: this._convertMessages(messages),
preamble: this.systemMessage,
preamble,
}),
signal,
});

View file

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

View file

@ -1,3 +1,4 @@
import { v4 as uuidv4 } from "uuid";
import {
AssistantChatMessage,
ChatMessage,
@ -7,17 +8,18 @@ import {
TextMessagePart,
ToolCallDelta,
} from "../../index.js";
import { findLast } from "../../util/findLast.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
import {
GeminiChatContent,
GeminiChatContentPart,
GeminiChatRequestBody,
GeminiChatResponse,
GeminiGenerationConfig,
GeminiToolFunctionDeclaration,
} from "./gemini-types.js";
convertContinueToolToGeminiFunction,
} from "./gemini-types";
class Gemini extends BaseLLM {
static providerName = "gemini";
@ -155,14 +157,8 @@ class Gemini extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
// Ensure this.apiBase is used if available, otherwise use default
const apiBase =
this.apiBase ||
Gemini.defaultOptions?.apiBase ||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
const isV1API = apiBase.includes("/v1/");
const isV1API = this.apiBase?.includes("/v1/");
// Conditionally apply removeSystemMessage
const convertedMsgs = isV1API
? this.removeSystemMessage(messages)
: messages;
@ -204,20 +200,27 @@ 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;
const body: GeminiChatRequestBody = {
contents: messages
.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",
);
@ -227,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
},
@ -236,28 +240,35 @@ class Gemini extends BaseLLM {
],
};
}
const assistantMsg = {
role:
msg.role === "assistant" ? ("model" as const) : ("user" as const),
if (msg.role === "assistant") {
const assistantMsg: GeminiChatContent = {
role: "model",
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this.continuePartToGeminiPart),
};
if (msg.toolCalls) {
msg.toolCalls.forEach((toolCall) => {
if (toolCall.function?.name && toolCall.function?.arguments) {
assistantMsg.parts.push({
functionCall: {
name: toolCall.function.name,
args: JSON.parse(toolCall.function.arguments),
},
});
}
});
}
return assistantMsg;
}
return {
role: "user",
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this.continuePartToGeminiPart),
};
if (msg.role === "assistant" && msg.toolCalls) {
msg.toolCalls.forEach((toolCall) => {
if (toolCall.function?.name && toolCall.function?.arguments) {
assistantMsg.parts.push({
functionCall: {
name: toolCall.function.name,
args: JSON.parse(toolCall.function.arguments),
},
});
}
});
}
return assistantMsg;
}),
};
if (options) {
@ -266,8 +277,10 @@ class Gemini extends BaseLLM {
// https://ai.google.dev/gemini-api/docs/api-versions
if (!isV1API) {
if (this.systemMessage) {
body.systemInstruction = { parts: [{ text: this.systemMessage }] };
if (systemMessage) {
body.systemInstruction = {
parts: [{ text: stripImages(systemMessage) }],
};
}
// Convert and add tools if present
if (options.tools?.length) {
@ -276,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) {
@ -397,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
@ -489,10 +401,8 @@ class Gemini extends BaseLLM {
`models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
this.apiBase,
);
// This feels hacky to repeat code from above function but was the quickest
// way to ensure system message re-formatting isn't done if user has specified v1
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
const isV1API = apiBase.includes("/v1/");
const isV1API = !!this.apiBase?.includes("/v1/");
// Convert chat messages to contents
const body = this.prepareBody(messages, options, isV1API);

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/",
model: "mercury-editor-small-experimental",
apiBase: "https://api.inceptionlabs.ai/v1/",
model: "mercury-coder-small",
completionOptions: {
temperature: 0.0,
maxTokens: 150,
presencePenalty: 1.5,
stop: ["\n\n", "\n \n", "<|endoftext|>"],
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

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

View file

@ -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));
}
@ -288,7 +293,10 @@ class OpenAI extends BaseLLM {
// To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs
// In practice, setting this to true and asking for multiple tool calls
// leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}'
body.parallel_tool_calls = false;
// o3 does not support this
if (!body.model.startsWith("o3")) {
body.parallel_tool_calls = false;
}
}
return body;

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

@ -80,16 +80,6 @@ class Replicate extends BaseLLM {
}
}
}
// protected async *_streamChat(
// messages: ChatMessage[],
// options: CompletionOptions
// ): AsyncGenerator<ChatMessage> {
// const resp = await this.complete(
// stripImages(messages[0]?.content || ""),
// options
// );
// }
}
export default Replicate;

View file

@ -1,7 +1,7 @@
import { GoogleAuth } from "google-auth-library";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse, streamSse } from "../stream.js";
@ -11,7 +11,7 @@ import Gemini from "./Gemini.js";
class VertexAI extends BaseLLM {
static providerName = "vertexai";
declare apiBase: string;
declare vertexProvider: string;
declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown";
declare anthropicInstance: Anthropic;
declare geminiInstance: Gemini;
@ -92,13 +92,13 @@ class VertexAI extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage =
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const filteredSystemMessages : ChatMessage[] = messages.filter((m) => m.role === "system");
let systemMessage: string = "";
if(filteredSystemMessages.length > 0) {
systemMessage = renderChatMessage(filteredSystemMessages[0]);
}
const systemMessage = stripImages(
messages.filter((m) => m.role === "system")[0]?.content ?? "",
);
const shouldCacheSystemMessage = !!(
this.cacheBehavior?.cacheSystemMessage && systemMessage
);
const apiURL = new URL(
`publishers/anthropic/models/${options.model}:streamRawPredict`,
this.apiBase,
@ -118,7 +118,7 @@ class VertexAI extends BaseLLM {
? [
{
type: "text",
text: this.systemMessage,
text: systemMessage,
cache_control: { type: "ephemeral" },
},
]
@ -142,8 +142,7 @@ class VertexAI extends BaseLLM {
}
}
//Gemini
// Gemini
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions,
@ -306,7 +305,7 @@ class VertexAI extends BaseLLM {
yield (await resp.json()).predictions[0].content;
}
//Manager functions
// Manager functions
protected async *_streamChat(
messages: ChatMessage[],
@ -328,6 +327,8 @@ class VertexAI extends BaseLLM {
} else {
if (options.model.includes("bison")) {
yield* this.streamChatBison(convertedMsgs, options);
} else {
throw new Error(`Unsupported model: ${options.model}`);
}
}
}

View file

@ -1,4 +1,9 @@
import { ChatMessage, Chunk, CompletionOptions, LLMOptions } from "../../index.js";
import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
} from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
@ -139,24 +144,24 @@ class WatsonX extends BaseLLM {
}
protected async updateWatsonxToken() {
var now = new Date().getTime() / 1000;
if (
watsonxToken === undefined ||
now > watsonxToken.expiration ||
watsonxToken.token === undefined
) {
watsonxToken = await this.getBearerToken();
} else {
console.log(
`Reusing token (expires in ${
(watsonxToken.expiration - now) / 60
} mins)`,
);
}
if (watsonxToken.token === undefined) {
throw new Error("Something went wrong. Check your credentials, please.");
}
var now = new Date().getTime() / 1000;
if (
watsonxToken === undefined ||
now > watsonxToken.expiration ||
watsonxToken.token === undefined
) {
watsonxToken = await this.getBearerToken();
} else {
console.log(
`Reusing token (expires in ${
(watsonxToken.expiration - now) / 60
} mins)`,
);
}
if (watsonxToken.token === undefined) {
throw new Error("Something went wrong. Check your credentials, please.");
}
}
protected async _complete(
prompt: string,
@ -312,64 +317,60 @@ class WatsonX extends BaseLLM {
return embeddings.map((e: any) => e.embedding);
}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
if (!query || !chunks.length) {
throw new Error("Query and chunks must not be empty");
}
try {
await this.updateWatsonxToken();
const headers = {
"Content-Type": "application/json",
Authorization: `${
watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${watsonxToken.token}`,
};
const payload: any = {
inputs: chunks.map((chunk) => ({ text: chunk.content })),
query: query,
parameters: {
truncate_input_tokens: 500,
return_options: {
top_n: chunks.length
},
if (!query || !chunks.length) {
throw new Error("Query and chunks must not be empty");
}
try {
await this.updateWatsonxToken();
const headers = {
"Content-Type": "application/json",
Authorization: `${
watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${watsonxToken.token}`,
};
const payload: any = {
inputs: chunks.map((chunk) => ({ text: chunk.content })),
query: query,
parameters: {
truncate_input_tokens: 500,
return_options: {
top_n: chunks.length,
},
model_id: this.model,
project_id: this.projectId,
};
},
model_id: this.model,
project_id: this.projectId,
};
const resp = await this.fetch(
new URL(
`${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`,
),
{
method: "POST",
headers: headers,
body: JSON.stringify(payload),
},
);
const resp = await this.fetch(
new URL(`${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`),
{
method: "POST",
headers: headers,
body: JSON.stringify(payload),
},
);
if (!resp.ok) {
throw new Error(`Failed to rerank chunks: ${await resp.text()}`);
}
const data = await resp.json();
const ranking = data.results;
if (!ranking) {
throw new Error("Empty response received from Watsonx");
}
// Sort results by index to maintain original order
return ranking
.sort((a: any, b: any) => a.index - b.index)
.map((result: any) => result.score);
} catch (error) {
console.error("Error in WatsonxReranker.rerank:", error);
throw error;
if (!resp.ok) {
throw new Error(`Failed to rerank chunks: ${await resp.text()}`);
}
const data = await resp.json();
const ranking = data.results;
if (!ranking) {
throw new Error("Empty response received from Watsonx");
}
// Sort results by index to maintain original order
return ranking
.sort((a: any, b: any) => a.index - b.index)
.map((result: any) => result.score);
} catch (error) {
console.error("Error in WatsonxReranker.rerank:", error);
throw error;
}
}
}

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

@ -3,10 +3,11 @@ import {
IdeSettings,
ILLM,
ILLMLogger,
JSONModelDescription,
LLMOptions,
ModelDescription,
} from "../..";
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
@ -27,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";
@ -56,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";
@ -73,6 +76,7 @@ export const LLMClasses = [
Together,
Novita,
HuggingFaceTGI,
HuggingFaceTEIEmbeddingsProvider,
HuggingFaceInferenceAPI,
Kindo,
LlamaCpp,
@ -109,16 +113,16 @@ export const LLMClasses = [
Scaleway,
Relace,
Inception,
Voyage,
];
export async function llmFromDescription(
desc: ModelDescription,
desc: JSONModelDescription,
readFile: (filepath: string) => Promise<string>,
uniqueId: string,
ideSettings: IdeSettings,
llmLogger: ILLMLogger,
completionOptions?: BaseCompletionOptions,
systemMessage?: string,
): Promise<BaseLLM | undefined> {
const cls = LLMClasses.find((llm) => llm.providerName === desc.provider);
@ -131,9 +135,15 @@ export async function llmFromDescription(
...desc.completionOptions,
};
systemMessage = desc.systemMessage ?? systemMessage;
if (systemMessage !== undefined) {
systemMessage = await renderTemplatedString(systemMessage, readFile, {});
let baseChatSystemMessage: string | undefined = undefined;
if (desc.systemMessage !== undefined) {
baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
baseChatSystemMessage += "\n\n";
baseChatSystemMessage += await renderTemplatedString(
desc.systemMessage,
readFile,
{},
);
}
let options: LLMOptions = {
@ -145,7 +155,7 @@ export async function llmFromDescription(
finalCompletionOptions.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens,
},
systemMessage,
baseChatSystemMessage,
logger: llmLogger,
uniqueId,
};

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", () => {

94
core/llm/messages.ts Normal file
View file

@ -0,0 +1,94 @@
import { ChatMessage } from "..";
export function messageHasToolCalls(msg: ChatMessage): boolean {
return msg.role === "assistant" && !!msg.toolCalls;
}
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
const flattened: ChatMessage[] = [];
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
if (
flattened.length > 0 &&
flattened[flattened.length - 1].role === msg.role &&
!messageHasToolCalls(msg) &&
!messageHasToolCalls(flattened[flattened.length - 1])
) {
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
} else {
flattened.push(msg);
}
}
return flattened;
}
export function messageIsEmpty(message: ChatMessage): boolean {
if (typeof message.content === "string") {
return message.content.trim() === "";
}
if (Array.isArray(message.content)) {
return message.content.every(
(item) => item.type === "text" && item.text?.trim() === "",
);
}
return false;
}
// some providers don't support empty messages
export function addSpaceToAnyEmptyMessages(
messages: ChatMessage[],
): ChatMessage[] {
return messages.map((message) => {
if (messageIsEmpty(message)) {
message.content = " ";
}
return message;
});
}
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":
case "user":
return (
typeof message.content === "string" && message.content.trim() === ""
);
case "assistant":
return (
typeof message.content === "string" &&
message.content.trim() === "" &&
!message.toolCalls
);
case "thinking":
case "tool":
return false;
}
}

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

@ -0,0 +1,55 @@
import { minimatch } from "minimatch";
import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
/**
* 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,
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
}) => {
const filePathsFromMessage = userMessage
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
: [];
let systemMessage = baseSystemMessage ?? "";
for (const rule of rules) {
// 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}`;
}
}
return systemMessage;
};

View file

@ -1,59 +0,0 @@
import { isRuleActive } from "./isRuleActive";
describe("isRuleActive", () => {
const rule = {
name: "My Rule",
rule: "Do no harm",
if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}',
};
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,68 +0,0 @@
import { Rule } from "@continuedev/config-yaml";
import { compileExpression } from "filtrex";
import { minimatch } from "minimatch";
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: Rule;
activePaths: string[];
currentModel: string;
}): boolean => {
if (typeof rule === "string") {
return true;
}
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 = "";

867
core/package-lock.json generated

File diff suppressed because it is too large Load diff

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

@ -64,9 +64,6 @@ export function slashCommandFromPromptFileV1(
description,
prompt,
run: async function* (context) {
const originalSystemMessage = context.llm.systemMessage;
context.llm.systemMessage = systemMessage;
const userInput = extractUserInput(context.input, name);
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
config: context.config,
@ -86,6 +83,18 @@ export function slashCommandFromPromptFileV1(
systemMessage,
);
if (systemMessage) {
const currentSystemMsg = messages.find((msg) => msg.role === "system");
if (currentSystemMsg) {
currentSystemMsg.content = systemMessage;
} else {
messages.unshift({
role: "system",
content: systemMessage,
});
}
}
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
@ -93,8 +102,6 @@ export function slashCommandFromPromptFileV1(
)) {
yield renderChatMessage(chunk);
}
context.llm.systemMessage = originalSystemMessage;
},
};
}

View file

@ -1,9 +1,11 @@
import { ChatMessage } from "../..";
export function replaceSlashCommandWithPromptInChatHistory(
history: any[],
history: ChatMessage[],
commandName: string,
renderedPrompt: string,
systemMessage?: string,
) {
systemMessageOverride?: string,
): ChatMessage[] {
const messages = [...history];
for (let i = messages.length - 1; i >= 0; i--) {
@ -13,7 +15,12 @@ export function replaceSlashCommandWithPromptInChatHistory(
}
if (Array.isArray(content)) {
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
if (
content.some(
(part) =>
part.type === "text" && part.text?.startsWith(`/${commandName}`),
)
) {
messages[i] = updateArrayContent(
messages[i],
commandName,
@ -30,10 +37,12 @@ export function replaceSlashCommandWithPromptInChatHistory(
}
}
if (systemMessage) {
messages[0]?.role === "system"
? (messages[0].content = systemMessage)
: messages.unshift({ role: "system", content: systemMessage });
if (systemMessageOverride) {
if (messages[0]?.role === "system") {
messages[0].content = systemMessageOverride;
} else {
messages.unshift({ role: "system", content: systemMessageOverride });
}
}
return messages;

View file

@ -1,4 +1,5 @@
import {
BlockType,
ConfigResult,
DevDataLogEvent,
ModelRole,
@ -31,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";
@ -49,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": [
@ -58,6 +61,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
"config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
"config/newPromptFile": [undefined, void];
"config/ideSettingsUpdate": [IdeSettings, void];
"config/getSerializedProfileInfo": [
@ -67,12 +71,20 @@ export type ToCoreFromIdeOrWebviewProtocol = {
profileId: string | null;
organizations: SerializedOrgWithProfiles[];
selectedOrgId: string;
usingContinueForTeams: boolean;
},
];
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
"config/refreshProfiles": [undefined, void];
"config/refreshProfiles": [
(
| undefined
| {
selectOrgId?: string;
selectProfileId?: string;
}
),
void,
];
"config/openProfile": [{ profileId: string | undefined }, void];
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
"config/updateSelectedModel": [
@ -89,7 +101,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
selectedModelTitle: string;
},
ContextItemWithId[],
];
@ -144,7 +155,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"chatDescriber/describe": [
{
selectedModelTitle: string;
text: string;
},
string | undefined,
@ -191,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

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

View file

@ -14,10 +14,12 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"history/delete",
"history/load",
"history/save",
"history/clear",
"devdata/log",
"config/addModel",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/addLocalWorkspaceBlock",
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/refreshProfiles",
@ -60,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
@ -76,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,
@ -15,7 +16,6 @@ export type ToWebviewFromIdeOrCoreProtocol = {
profileId: string | null;
organizations: SerializedOrgWithProfiles[];
selectedOrgId: string | null;
usingContinueForTeams: boolean;
},
void,
];
@ -41,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,39 @@
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 "{{{ name }}}"',
isCurrently: 'creating a rule block for "{{{ name }}}"',
hasAlready: 'created a rule block for "{{{ name }}}"',
readonly: false,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.CreateRuleBlock,
description:
"Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently.",
parameters: {
type: "object",
required: ["name", "rule"],
properties: {
name: {
type: "string",
description:
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')",
},
rule: {
type: "string",
description:
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
},
globs: {
type: "string",
description:
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
},
},
},
},
};

View file

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

View file

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

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