Merge branch 'main' into instant-apply-uDiff-3684

This commit is contained in:
Nate 2025-03-08 09:12:29 -08:00
commit 46c74d6cc5
656 changed files with 25476 additions and 10091 deletions

View file

@ -0,0 +1,5 @@
## 0.0.92 - 2025-02-26
### Fixed
* Off-screen rendering to solve white flash on load and lack of changing cursor type
* OSR-related fixes for non-Mac users
* Fixes for inline edit in JetBrains

View file

@ -0,0 +1,7 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved theme matching
### Fixed
* Fixes interference between SonarQube and Continue autocomplete
* Numerous reliability improvements

View file

@ -0,0 +1,6 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved apply quality
### Fixed
* Numerous reliability improvements

View file

@ -1,5 +0,0 @@
project: extensions/intellij
kind: Fixed
body: Off-screen rendering to solve white flash on load and lack of changing cursor
type
time: 2024-10-07T18:38:20.733658-07:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Fixed
body: OSR-related fixes for non-Mac users
time: 2024-11-08T11:43:22.623155-08:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Fixed
body: Fixes for inline edit in JetBrains
time: 2024-11-08T11:47:07.953304-08:00

View file

@ -4,7 +4,7 @@ description: Generate unit tests for core utilities
Write jest tests for the provided code.
Use jest version ^29 (e.g. jest 29.7.0)
Use best practices. Be clear and consise.
Use best practices. Be clear and concise.
Aim for 100% code coverage where reasonable.
Multiple tests can be written, split up tests for best clarity and readability.
Only use typescript, and if the file/code is not typescript, warn the user.
@ -15,7 +15,7 @@ Use double quotes (or backticks if needed) for strings
The code being tested is used in IDE extensions, and it:
- accesses code workspaces through the IDE ("workspace directories")
- persists extension-related data to the the local machine of the user ("global directory"), and
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accesed via a remote "control plane" using the `ControlPlaneClient`
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accessed via a remote "control plane" using the `ControlPlaneClient`
Jest testing setup includes
- @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live.
@ -31,7 +31,7 @@ Jest testing setup includes
Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests.
IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible.
IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible.
Instead, generate actual mock files and data for operations
Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests

View file

@ -27,16 +27,17 @@ body:
- **Continue version**: v0.9.4
- **IDE version**: VSCode 1.85.1
- Model: Claude Sonnet 3.5
- config.json: `{ "models": ... }`
- Assistant configuration
value: |
- OS:
- Continue version:
- IDE version:
- Model:
- config.json:
```json
- config:
```yaml
```
OR link to assistant in Continue hub:
render: Markdown
validations:
required: false

View file

@ -7,6 +7,12 @@ name: JetBrains Release
on:
release:
types: [prereleased]
workflow_dispatch:
inputs:
publish_build:
description: "Whether or not to publish the built extension to the JetBrains marketplace"
required: true
default: false
defaults:
run:
@ -25,7 +31,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-jetbrains ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -34,7 +40,7 @@ jobs:
# Prepare and publish the plugin to JetBrains Marketplace repository
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
name: Build Plugin
runs-on: macos-latest
permissions:
@ -175,6 +181,7 @@ jobs:
# Publish the plugin to JetBrains Marketplace
- name: Publish EAP Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@ -184,6 +191,7 @@ jobs:
run: ./gradlew publishPlugin
- name: Publish Stable Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@ -233,6 +241,12 @@ jobs:
name: continue-binary-win32-x64
path: ./binary/bin/win32-x64/
- name: Upload artifact (win32-arm64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-win32-arm64
path: ./binary/bin/win32-arm64/
- name: Upload artifact (linux-arm64)
uses: actions/upload-artifact@v4
with:

View file

@ -4,6 +4,13 @@ on:
release:
types: [released]
workflow_dispatch:
inputs:
publish_build:
description: "Whether or not to publish the built extension to the VS Code marketplace"
required: true
default: false
jobs:
check_release_name:
runs-on: ubuntu-latest
@ -13,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.8.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -21,7 +28,7 @@ jobs:
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
strategy:
matrix:
include:
@ -201,6 +208,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- build
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
steps:

View file

@ -4,27 +4,19 @@ on:
pull_request:
branches:
- main
paths:
- "extensions/vscode/**"
- "core/**"
- "gui/**"
- ".github/workflows/**"
- staging
push:
branches:
- main
paths:
- "extensions/intellij/**"
- "extensions/vscode/**"
- "core/**"
- "gui/**"
- ".github/workflows/**"
- staging
jobs:
install-root:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -44,6 +36,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -71,6 +64,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -96,10 +90,11 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
install-gui:
needs: [ install-root, install-core ]
needs: [install-root, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -131,6 +126,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -157,10 +153,11 @@ jobs:
npx tsc --noEmit
binary-checks:
needs: [ install-root, install-core ]
needs: [install-root, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -193,10 +190,11 @@ jobs:
npx tsc --noEmit
install-vscode:
needs: [ install-root, install-core ]
needs: [install-root, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -230,6 +228,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -261,6 +260,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -274,10 +274,18 @@ jobs:
run: |
cd core
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true && github.actor == 'dependabot[bot]' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [ install-root, install-vscode ]
needs: [install-root, install-vscode]
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
@ -295,7 +303,13 @@ jobs:
cd extensions/vscode
npm ci
npm run e2e:compile
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then
# Exclude SSH tests for forks
FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .)
else
# Include all tests for non-forks
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
fi
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
@ -306,9 +320,10 @@ jobs:
vscode-package-extension:
runs-on: ubuntu-latest
needs: [ install-vscode, install-core ]
needs: [install-vscode, install-core]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -338,9 +353,10 @@ jobs:
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [ install-vscode, install-core ]
needs: [install-vscode, install-core]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -370,7 +386,7 @@ jobs:
path: extensions/vscode/e2e/storage
vscode-e2e-tests:
name: ${{ matrix.test_file }}"
name: ${{ matrix.test_file }} (${{ matrix.command }})
needs:
[
vscode-download-e2e-dependencies,
@ -380,12 +396,15 @@ jobs:
install-core,
]
runs-on: ubuntu-latest
# Tests requiring secrets need approval from maintainers
strategy:
fail-fast: false
matrix:
test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
command: ["e2e:ci:run", "e2e:ci:run-yaml"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -396,6 +415,14 @@ jobs:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
# We don't want to cache the Continue extension, so it is deleted at the end of the job
- uses: actions/cache@v4
id: test-extensions-cache
with:
path: extensions/vscode/e2e/.test-extensions
# package.json used as the key because that's where the download script is defined
key: vscode-test-extensions-${{ hashFiles('extensions/vscode/package.json') }}
- name: Download build artifact
uses: actions/download-artifact@v4
with:
@ -423,6 +450,7 @@ jobs:
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts
echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config
if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}
- name: Set up Xvfb
run: |
@ -432,11 +460,15 @@ jobs:
- name: Run e2e tests
run: |
cd extensions/vscode
TEST_FILE="${{ matrix.test_file }}" npm run e2e:ci:run
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
env:
DISPLAY: :99
- name: Delete continue from test extensions
run: |
cd extensions/vscode
rm -rf e2e/.test-extensions/continue*
- name: Upload e2e test screenshots
if: failure()
uses: actions/upload-artifact@v4
@ -445,10 +477,11 @@ jobs:
path: extensions/vscode/e2e/storage/screenshots
gui-tests:
needs: [ install-gui, install-core ]
needs: [install-gui, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -476,11 +509,10 @@ jobs:
npm test
jetbrains-tests:
needs: [ install-root, core-checks ]
needs: [install-root, core-checks]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: core/node_modules
@ -546,7 +578,7 @@ jobs:
with:
url: http://127.0.0.1:8082
max-attempts: 15
retry-delay: 5s
retry-delay: 30s
- name: Run tests
run: |
@ -574,4 +606,33 @@ jobs:
path: |
${{ github.workspace }}/extensions/intellij/build/reports
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
# This action at least lets us manage the list of required tests via source control
# so that creators of new jobs can add them to this list
require-all-checks-to-pass:
if: always()
runs-on: ubuntu-latest
needs:
- install-root
- install-core
- core-checks
- install-gui
- gui-checks
- binary-checks
- install-vscode
- vscode-checks
- core-tests
- vscode-get-test-file-matrix
- vscode-package-extension
- vscode-download-e2e-dependencies
- vscode-e2e-tests
- gui-tests
- jetbrains-tests
steps:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@release/v1
with:
allowed-failures:
allowed-skips:
jobs: ${{ toJSON(needs) }}

View file

@ -4,6 +4,13 @@ on:
release:
types: [prereleased]
workflow_dispatch:
inputs:
publish_build:
description: "Whether or not to publish the built extension to the VS Code marketplace"
required: true
default: false
jobs:
check_release_name:
runs-on: ubuntu-latest
@ -13,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.9.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -21,7 +28,7 @@ jobs:
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
strategy:
matrix:
include:
@ -197,6 +204,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- build
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
steps:
@ -209,8 +217,8 @@ jobs:
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
- name: Pull latest changes
run: git pull origin main
- name: Pull latest changes from release
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
# 1. Download the artifacts
- uses: actions/download-artifact@v4

View file

@ -0,0 +1,25 @@
name: "Label / close stale issues"
on:
schedule:
- cron: "30 1 * * *"
jobs:
stale:
permissions:
issues: write
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!"
stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue."
days-before-stale: 90
days-before-close: 10
days-before-pr-stale: -1
days-before-pr-close: -1
operations-per-run: 1000
stale-issue-label: "stale"
stale-pr-label: "stale"
exempt-issue-labels: "needs-triage,no-stale,high,highest"
exempt-pr-labels: "no-stale"

22
.vscode/launch.json vendored
View file

@ -20,10 +20,10 @@
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
"preLaunchTask": "vscode-extension:build",
"env": {
// "CONTROL_PLANE_ENV": "local",
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
// "staging" for the preview deployment "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
// "local" for entirely local development of control plane/proxy
// "CONTROL_PLANE_ENV": "staging"
}
},
{
@ -38,6 +38,7 @@
"internalConsoleOptions": "openOnSessionStart",
"cwd": "${workspaceFolder}/binary",
"env": {
// "CONTROL_PLANE_ENV": "test",
"CONTINUE_DEVELOPMENT": "true",
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
}
@ -137,6 +138,25 @@
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
},
{
"name": "[config-yaml] Jest Test Debugger, Current Open File",
"type": "node",
"request": "launch",
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/packages/config-yaml/node_modules/jest/bin/jest.js",
"--runInBand",
"--config",
"${workspaceRoot}/packages/config-yaml/jest.config.mjs",
"${relativeFile}"
],
"cwd": "${workspaceRoot}/packages/config-yaml",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
}
]
}

View file

@ -13,6 +13,9 @@
"args": ["-l"]
}
},
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"search.exclude": {
"**/package-lock.json": true,
@ -42,5 +45,6 @@
"extensions/.continue-debug": true
// "sync/**": true
},
"eslint.workingDirectories": ["./core"]
"eslint.workingDirectories": ["./core"],
"typescript.tsdk": "node_modules/typescript/lib"
}

85
.vscode/tasks.json vendored
View file

@ -6,16 +6,14 @@
"type": "npm",
"script": "tsc:watch",
"isBackground": true,
"problemMatcher": {
"base": "$tsc-watch",
"background": {
"activeOnStart": true,
"beginsPattern": "Starting compilation in watch mode...",
"endsPattern": "Found 0 errors"
}
"problemMatcher": ["$tsc-watch"],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"revealProblems": "onProblem"
"reveal": "always",
"panel": "new"
}
},
// Compile and bundle the extension
@ -73,7 +71,27 @@
}
]
},
// Build the React app. It gets bundled into the extension as a file resource and has a seprate build step
{
"label": "vscode-extension:package",
"dependsOn": ["vscode-extension:esbuild"],
"type": "npm",
"script": "package",
"path": "extensions/vscode",
"problemMatcher": [
{
"pattern": [
{
"regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
]
}
]
},
{
"label": "vscode-extension:continue-ui:build",
"type": "shell",
@ -186,6 +204,55 @@
"command": "node",
"args": ["${workspaceFolder}/scripts/uninstall.js"],
"problemMatcher": []
},
{
"label": "refresh-dependencies:core",
"type": "shell",
"command": "npm",
"args": ["install"],
"problemMatcher": [],
"options": {
"cwd": "${workspaceFolder}/core"
},
"presentation": {
"close": true
}
},
{
"label": "refresh-dependencies:vscode",
"type": "shell",
"command": "npm",
"args": ["install"],
"problemMatcher": [],
"options": {
"cwd": "${workspaceFolder}/extensions/vscode"
},
"presentation": {
"close": true
}
},
{
"label": "refresh-dependencies:gui",
"type": "shell",
"command": "npm",
"args": ["install"],
"problemMatcher": [],
"options": {
"cwd": "${workspaceFolder}/gui"
},
"presentation": {
"close": true
}
},
{
"label": "refresh-dependencies:all",
"dependsOn": [
"refresh-dependencies:core",
"refresh-dependencies:gui",
"refresh-dependencies:vscode"
],
"type": "shell",
"problemMatcher": []
}
]
}

View file

@ -49,7 +49,7 @@ If you find a bug, please [create an issue](https://github.com/continuedev/conti
## ✨ Suggest Enhancements
Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are
Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are:
- Create an issue
@ -128,7 +128,7 @@ nvm use
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
3. To package the extension, run `npm run package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
##### Debugging
@ -192,7 +192,7 @@ Continue has support for more than a dozen different LLM "providers", making it
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
- `providerName` - the identifier for your provider
- `providerName` - the identifier for your provider.
- At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion".
2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).

View file

@ -8,7 +8,7 @@
<div align="center">
**[Continue](https://docs.continue.dev) is the leading open-source AI code assistant. You can connect any models and any context to build custom autocomplete and chat experiences inside [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)**
**[Continue](https://docs.continue.dev) enables to developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
</div>
@ -46,7 +46,7 @@
## Actions
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases.
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases
![actions](docs/static/img/actions.gif)

16
SECURITY.md Normal file
View file

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

View file

@ -53,7 +53,7 @@ const targetToLanceDb = {
"linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
"linux-x64": "@lancedb/vectordb-linux-x64-gnu",
"win32-x64": "@lancedb/vectordb-win32-x64-msvc",
"win32-arm64": "@lancedb/vectordb-win32-x64-msvc", // they don't have a win32-arm64 build
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
};
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
@ -118,6 +118,22 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
(async () => {
// 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(
"out/package.json",
JSON.stringify(
{
name: "binary",
version: "1.0.0",
author: "Continue Dev, Inc",
license: "Apache-2.0",
},
undefined,
2,
),
);
console.log("[info] Downloading prebuilt lancedb...");
for (const target of targets) {
if (targetToLanceDb[target]) {
@ -232,9 +248,15 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
// Download and unzip prebuilt sqlite3 binary for the target
console.log("[info] Downloading node-sqlite3");
const downloadUrl = `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
target === "win32-arm64" ? "win32-ia32" : target
}.tar.gz`;
const downloadUrl =
// node-sqlite3 doesn't have a pre-built binary for win32-arm64
target === "win32-arm64"
? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz"
: `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
target
}.tar.gz`;
execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
@ -266,6 +288,9 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
fs.writeFileSync(`${targetDir}/package.json`, "");
}
// Cleanup - this is needed when running locally
fs.rmSync("out/package.json");
const pathsToVerify = [];
for (const target of targets) {
const exe = target.startsWith("win") ? ".exe" : "";

View file

@ -0,0 +1,6 @@
const path = require('path');
process.env.CONTINUE_DEVELOPMENT = true;
process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
require('./out/index.js');

View file

@ -48,13 +48,13 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.0",
"@continuedev/config-yaml": "^1.0.52",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",
"@modelcontextprotocol/sdk": "^1.0.0",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
@ -107,7 +107,7 @@
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"
"zod": "^3.24.2"
},
"devDependencies": {
"@babel/preset-env": "^7.24.7",
@ -2556,9 +2556,10 @@
}
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==",
"version": "1.7.9",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
"integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
@ -3166,10 +3167,11 @@
}
},
"node_modules/cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
@ -5135,12 +5137,13 @@
}
},
"node_modules/micromatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz",
"integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==",
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"license": "MIT",
"dependencies": {
"braces": "^3.0.2",
"braces": "^3.0.3",
"picomatch": "^2.3.1"
},
"engines": {

20
binary/prompt-logs.js Normal file
View file

@ -0,0 +1,20 @@
const fs = require('fs');
const path = require('path');
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
const logFilePath = path.join(logDirPath, "prompt.log");
if (!fs.existsSync(logDirPath)) {
fs.mkdirSync(logDirPath, { recursive: true });
}
if (!fs.existsSync(logFilePath)) {
fs.createWriteStream(logFilePath).end();
}
console.log("Watching logs at " + logFilePath)
fs.watch(logFilePath, () => {
// console.clear();
fs.createReadStream(logFilePath).pipe(process.stdout);
});

View file

@ -33,17 +33,49 @@ class IPCMessengerBase<
response &&
typeof response[Symbol.asyncIterator] === "function"
) {
for await (const update of response) {
this.send(msg.messageType, update, msg.messageId);
let next = await response.next();
while (!next.done) {
this.send(
msg.messageType,
{
done: false,
content: next.value,
status: "success",
},
msg.messageId,
);
next = await response.next();
}
this.send(msg.messageType, { done: true }, msg.messageId);
this.send(
msg.messageType,
{
done: true,
content: next.value,
status: "success",
},
msg.messageId,
);
} else {
this.send(msg.messageType, response, msg.messageId);
this.send(
msg.messageType,
{
done: true,
content: response,
status: "success",
},
msg.messageId,
);
}
} catch (e: any) {
this.send(
msg.messageType,
{ done: true, error: e.message, status: "error" },
msg.messageId,
);
console.warn(`Error running handler for "${msg.messageType}": `, e);
this._onErrorHandlers.forEach((handler) => {
handler(e);
handler(msg, e);
});
}
});
@ -62,6 +94,7 @@ class IPCMessengerBase<
}
private _unfinishedLine: string | undefined = undefined;
protected _handleData(data: Buffer) {
const d = data.toString();
const lines = d.split(/\r\n/).filter((line) => line.trim() !== "");
@ -79,9 +112,9 @@ class IPCMessengerBase<
lines.forEach((line) => this._handleLine(line));
}
private _onErrorHandlers: ((error: Error) => void)[] = [];
private _onErrorHandlers: ((message: Message, error: Error) => void)[] = [];
onError(handler: (error: Error) => void) {
onError(handler: (message: Message, error: Error) => void) {
this._onErrorHandlers.push(handler);
}
@ -169,6 +202,7 @@ export class IpcMessenger<
process.exit(1);
});
}
_sendMsg(msg: Message) {
const d = JSON.stringify(msg);
// console.log("[info] Sending message: ", d);
@ -183,7 +217,7 @@ export class CoreBinaryMessenger<
extends IPCMessengerBase<ToProtocol, FromProtocol>
implements IMessenger<ToProtocol, FromProtocol>
{
private errorHandler: (error: Error) => void = () => {};
private errorHandler: (message: Message, error: Error) => void = () => {};
private messageHandlers: Map<
keyof ToProtocol,
(message: Message<any>) => Promise<any> | any

View file

@ -41,9 +41,9 @@ export class TcpMessenger<
});
}
private _onErrorHandlers: ((error: Error) => void)[] = [];
private _onErrorHandlers: ((message: Message, error: Error) => void)[] = [];
onError(handler: (error: Error) => void) {
onError(handler: (message: Message, error: Error) => void) {
this._onErrorHandlers.push(handler);
}
@ -69,17 +69,49 @@ export class TcpMessenger<
response &&
typeof response[Symbol.asyncIterator] === "function"
) {
for await (const update of response) {
this.send(msg.messageType, update, msg.messageId);
let next = await response.next();
while (!next.done) {
this.send(
msg.messageType,
{
done: false,
content: next.value,
status: "success",
},
msg.messageId,
);
next = await response.next();
}
this.send(msg.messageType, { done: true }, msg.messageId);
this.send(
msg.messageType,
{
done: true,
content: next.value,
status: "success",
},
msg.messageId,
);
} else {
this.send(msg.messageType, response || {}, msg.messageId);
this.send(
msg.messageType,
{
done: true,
content: response,
status: "success",
},
msg.messageId,
);
}
} catch (e: any) {
this.send(
msg.messageType,
{ done: true, error: e.message, status: "error" },
msg.messageId,
);
console.warn(`Error running handler for "${msg.messageType}": `, e);
this._onErrorHandlers.forEach((handler) => {
handler(e);
handler(msg, e);
});
}
});
@ -98,6 +130,7 @@ export class TcpMessenger<
}
private _unfinishedLine: string | undefined = undefined;
private _handleData(data: Buffer) {
const d = data.toString();
const lines = d.split(/\r\n/).filter((line) => line.trim() !== "");
@ -151,6 +184,7 @@ export class TcpMessenger<
data,
});
}
request<T extends keyof FromProtocol>(
messageType: T,
data: FromProtocol[T][0],

View file

@ -134,6 +134,13 @@ export class CompletionProvider {
token: AbortSignal | undefined,
): Promise<AutocompleteOutcome | undefined> {
try {
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
);
token = controller.signal;
}
const startTime = Date.now();
const options = await this._getAutocompleteOptions();
@ -158,14 +165,6 @@ export class CompletionProvider {
return undefined;
}
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
);
token = controller.signal;
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
helper,
@ -246,6 +245,7 @@ export class CompletionProvider {
completionOptions,
cacheHit,
filepath: helper.filepath,
numLines: completion.split("\n").length,
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),

View file

@ -1,158 +0,0 @@
# Tab Autocomplete (beta)
Continue now provides support for tab autocomplete in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains IDEs](https://plugins.jetbrains.com/plugin/22707-continue/edit). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ).
## Setting up with Ollama (default)
We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
```bash
ollama run qwen2.5-coder:1.5b-base
```
Once it has been downloaded, you should begin to see completions in VS Code.
## Setting up with LM Studio
You can also set up tab-autocomplete with a local LM Studio instance by following these steps:
1. Download the latest version of LM Studio from [here](https://lmstudio.ai/)
2. Download a model (e.g. search for `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` and choose one of the options there)
3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server"
4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`); this will be used as the "model" attribute in Continue
5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model)
6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier
Example:
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5b",
"model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
"provider": "lmstudio"
}
}
```
## Setting up a custom model
All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint:
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "openai",
"model": "<MODEL_NAME>",
"apiBase": "<VLLM_ENDPOINT_URL>"
},
...
}
```
As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama:
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "deepseek-coder:6.7b-base"
},
...
}
```
If you aren't yet familiar with the available options, you can learn more in our [overview](../setup/overview.md).
### What model should I use?
If you are running the model locally, we recommend `qwen2.5-coder:1.5b`.
If you have a bit more compute, or are running a model in the cloud, you can upgrade to `qwen2.5-coder:7b`.
Regardless of what you are willing to spend, we do not recommend using GPT or Claude for autocomplete. Learn why [below](#i-want-better-completions-should-i-use-gpt-4).
## Configuration Options
The following can be configured in `config.json`:
### `tabAutocompleteModel`
This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder-3b`.
### `tabAutocompleteOptions`
This object allows you to customize the behavior of tab-autocomplete. The available options are:
- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number)
- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number)
- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number)
- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number)
- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String)
- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto".
### Full example
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
"maxPromptTokens": 400,
"prefixPercentage": 0.5
}
}
```
## Troubleshooting
### I want better completions, should I use GPT-4?
Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance.
### I'm not seeing any completions
Follow these steps to ensure that everything is set up correctly:
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar).
2. Make sure you have downloaded Ollama.
3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded.
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete.
6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains).
7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible.
### Completions are slow
Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`.
### Completions don't know about my code
We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks.
### Completions contain formatting errors
If you're seeing a common pattern of mistake that might be helpful to report, please share in Discord. We will do our best to fix it as soon as possible.
## How to turn off autocomplete
### VS Code
Click the "Continue" button in the status panel at the bottom right of the screen. The checkmark will become a "cancel" symbol and you will no longer see completions. You can click again to turn it back on.
Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete".
### JetBrains
Open Settings -> Tools -> Continue and uncheck the box for "Enable Tab Autocomplete".
### Feedback
If you're turning off autocomplete, we'd love to hear how we can improve! Please let us know in our [Discord](https://discord.gg/vapESyrFmJ) or file an issue on GitHub.

View file

@ -240,6 +240,14 @@ export const Solidity = {
endOfLine: [";"],
};
// Lua
export const Lua = {
name: "Lua",
topLevelKeywords: ["function"],
singleLineComment: "--",
endOfLine: [],
};
// YAML
export const YAML: AutocompleteLanguageInfo = {
name: "YAML",
@ -367,6 +375,8 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
yaml: YAML,
yml: YAML,
md: Markdown,
lua: Lua,
luau: Lua,
};
export function languageForFilepath(fileUri: string): AutocompleteLanguageInfo {

View file

@ -76,7 +76,6 @@ export class StreamTransformPipeline {
const timeoutValue = await Telemetry.getValueForFeatureFlag(
PosthogFeatureFlag.AutocompleteTimeout,
);
// helper.options.showWhateverWeHaveAtXMs ?? DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);

View file

@ -11,6 +11,8 @@ import {
AutocompleteSnippetType,
} from "./types";
const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled
export interface SnippetPayload {
rootPathSnippets: AutocompleteCodeSnippet[];
importDefinitionSnippets: AutocompleteCodeSnippet[];
@ -29,6 +31,27 @@ function racePromise<T>(promise: Promise<T[]>): Promise<T[]> {
return Promise.race([promise, timeoutPromise]);
}
class DiffSnippetsCache {
private cache: Map<number, any> = new Map();
private lastTimestamp: number = 0;
public set<T>(timestamp: number, value: T): T {
// Clear old cache entry if exists
if (this.lastTimestamp !== timestamp) {
this.cache.clear();
}
this.lastTimestamp = timestamp;
this.cache.set(timestamp, value);
return value;
}
public get(timestamp: number): any | undefined {
return this.cache.get(timestamp);
}
}
const diffSnippetsCache = new DiffSnippetsCache();
// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems,
// or they might separately track recently edited ranges)
async function getIdeSnippets(
@ -90,14 +113,31 @@ const getClipboardSnippets = async (
const getDiffSnippets = async (
ide: IDE,
): Promise<AutocompleteDiffSnippet[]> => {
const diff = await ide.getDiff(true);
const currentTimestamp = ide.getLastFileSaveTimestamp ?
ide.getLastFileSaveTimestamp() :
Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
return diff.map((item) => {
// Check cache first
const cached = diffSnippetsCache.get(currentTimestamp) as AutocompleteDiffSnippet[];
if (cached) {
return cached;
}
let diff: string[] = [];
try {
diff = await ide.getDiff(true);
} catch (e) {
console.error("Error getting diff for autocomplete", e);
}
return diffSnippetsCache.set(currentTimestamp, diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
});
}));
};
export const getAllSnippets = async ({
@ -122,10 +162,8 @@ export const getAllSnippets = async ({
clipboardSnippets,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
),
racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)),
racePromise(contextRetrievalService.getSnippetsFromImportDefinitions(helper)),
IDE_SNIPPETS_ENABLED ? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)) : [],
racePromise(getDiffSnippets(ide)),
racePromise(getClipboardSnippets(ide)),
]);

View file

@ -51,6 +51,8 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
};
// https://github.com/QwenLM/Qwen2.5-Coder?tab=readme-ov-file#3-file-level-code-completion-fill-in-the-middle
// This issue asks about the use of <|repo_name|> and <|file_sep|> together with <|fim_prefix|>, <|fim_suffix|> and <|fim_middle|>
// https://github.com/QwenLM/Qwen2.5-Coder/issues/343
const qwenCoderFimTemplate: AutocompleteTemplate = {
template:
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
@ -85,6 +87,11 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
snippets,
workspaceUris,
): [string, string] => {
function getFileName(snippet: { uri: string, uniquePath: string }) {
return snippet.uri.startsWith("file://") ? snippet.uniquePath : snippet.uri
}
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
return [
@ -111,14 +118,12 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
return snippet.content;
}
return `+++++ ${relativePaths[i].uri} \n${snippet.content}`;
return `+++++ ${getFileName(relativePaths[i])} \n${snippet.content}`;
})
.join("\n\n");
return [
`${otherFiles}\n\n+++++ ${
relativePaths[relativePaths.length - 1].uri
}\n${prefix}`,
`${otherFiles}\n\n+++++ ${getFileName(relativePaths[relativePaths.length - 1])}\n${prefix}`,
suffix,
];
},
@ -126,7 +131,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
return `[SUFFIX]${suffix}[PREFIX]${prefix}`;
},
completionOptions: {
stop: ["[PREFIX]", "[SUFFIX]"],
stop: ["[PREFIX]", "[SUFFIX]", "\n+++++ "],
},
};
@ -218,9 +223,8 @@ const codegeexFimTemplate: AutocompleteTemplate = {
[...snippets.map((snippet) => snippet.filepath), filepath],
workspaceUris,
);
const baseTemplate = `###PATH:${
relativePaths[relativePaths.length - 1]
}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1]
}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
if (snippets.length === 0) {
return `<|user|>\n${baseTemplate}<|assistant|>\n`;
}
@ -395,7 +399,8 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
lowerCaseModel.includes("gpt") ||
lowerCaseModel.includes("davinci-002") ||
lowerCaseModel.includes("claude") ||
lowerCaseModel.includes("granite3")
lowerCaseModel.includes("granite3") ||
lowerCaseModel.includes("granite-3")
) {
return holeFillerTemplate;
}

View file

@ -42,24 +42,100 @@ export const getSnippets = (
helper: HelperVars,
payload: SnippetPayload,
): AutocompleteSnippet[] => {
const snippets = [
...payload.diffSnippets,
...payload.clipboardSnippets,
...payload.recentlyVisitedRangesSnippets,
...shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
),
),
];
const snippets = {
"clipboard": payload.clipboardSnippets,
"recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets,
"recentlyEditedRanges": payload.recentlyEditedRangeSnippets,
"diff": payload.diffSnippets,
"base": shuffleArray(filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
)),
}
// Define snippets with their priorities
const snippetConfigs: {
key: keyof typeof snippets;
enabledOrPriority: boolean | number;
defaultPriority: number;
snippets: AutocompleteSnippet[];
}[] = [
{
key: "clipboard",
enabledOrPriority: helper.options.experimental_includeClipboard,
defaultPriority: 1,
snippets: payload.clipboardSnippets,
},
{
key: "recentlyVisitedRanges",
enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges,
defaultPriority: 2,
snippets: payload.recentlyVisitedRangesSnippets,
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
if they are visible. We should handle them separately so that we can control their priority
and whether they should be included or not. */
},
{
key: "recentlyEditedRanges",
enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges,
defaultPriority: 3,
snippets: payload.recentlyEditedRangeSnippets,
},
{
key: "diff",
enabledOrPriority: helper.options.experimental_includeDiff,
defaultPriority: 4,
snippets: payload.diffSnippets,
// TODO: diff is commonly too large, thus anything lower in priority is not included.
},
{
key: "base",
enabledOrPriority: true,
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
)),
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
// always not inlucded due to diff being commonly large
},
];
// Create a readable order of enabled snippets
const snippetOrder = snippetConfigs
.filter(({ enabledOrPriority }) => enabledOrPriority)
.map(({ key, enabledOrPriority, defaultPriority }) => ({
key,
priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority,
}))
.sort((a, b) => a.priority - b.priority);
// Log the snippet order for debugging - uncomment if needed
/* console.log(
'Snippet processing order:',
snippetOrder
.map(({ key, priority }) => `${key} (priority: ${priority})`).join("\n")
); */
// Convert configs to prioritized snippets
let prioritizedSnippets = snippetOrder
.flatMap(({ key, priority }) =>
snippets[key].map(snippet => ({ snippet, priority }))
)
.sort((a, b) => a.priority - b.priority)
.map(({ snippet }) => snippet);
// Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
// while looking at the prompts in the Continue's output
prioritizedSnippets = prioritizedSnippets.filter((snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue"));
const finalSnippets = [];
let remainingTokenCount = getRemainingTokenCount(helper);
while (remainingTokenCount > 0 && snippets.length > 0) {
const snippet = snippets.shift();
while (remainingTokenCount > 0 && prioritizedSnippets.length > 0) {
const snippet = prioritizedSnippets.shift();
if (!snippet || !isValidSnippet(snippet)) {
continue;
}

View file

@ -1,4 +1,4 @@
import { logDevData } from "../../util/devdata";
import { DataLogger } from "../../data/log";
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
import { Telemetry } from "../../util/posthog";
import { getUriFileExtension } from "../../util/uri";
@ -96,7 +96,14 @@ export class AutocompleteLoggingService {
}
private logAutocompleteOutcome(outcome: AutocompleteOutcome) {
logDevData("autocomplete", outcome);
void DataLogger.getInstance().logDevData({
name: "autocomplete",
data: {
...outcome,
useFileSuffix: true, // from outdated schema
},
});
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture(
"autocomplete",
@ -113,6 +120,7 @@ export class AutocompleteLoggingService {
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
},
true,
);

View file

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

View file

@ -9,8 +9,8 @@ export function slashFromCustomCommand(
): SlashCommand {
return {
name: customCommand.name,
description: customCommand.description,
run: async function* ({ input, llm, history, ide }) {
description: customCommand.description ?? "",
run: async function* ({ input, llm, history, ide, completionOptions }) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${customCommand.name}`)) {
@ -20,11 +20,16 @@ export function slashFromCustomCommand(
}
// Render prompt template
const promptUserInput = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
);
let promptUserInput: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
promptUserInput = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
);
} else {
promptUserInput = customCommand.prompt + "\n\n" + userInput;
}
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
@ -37,16 +42,21 @@ export function slashFromCustomCommand(
if (
Array.isArray(content) &&
content.some((part) =>
part.text?.startsWith(`/${customCommand.name}`),
content.some(
(part) =>
"text" in part && part.text?.startsWith(`/${customCommand.name}`),
)
) {
messages[i] = {
...message,
content: content.map((part) => {
return part.text?.startsWith(`/${customCommand.name}`)
? { ...part, text: promptUserInput }
: part;
if (
"text" in part &&
part.text.startsWith(`/${customCommand.name}`)
) {
return { type: "text", text: promptUserInput };
}
return part;
}),
};
break;
@ -62,6 +72,7 @@ export function slashFromCustomCommand(
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
completionOptions,
)) {
yield renderChatMessage(chunk);
}

View file

@ -2,8 +2,7 @@ import ignore from "ignore";
import type { FileType, IDE, SlashCommand } from "../..";
import {
defaultIgnoreDir,
defaultIgnoreFile,
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = {
};
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
const ig = ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(getGlobalContinueIgArray());
const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
const entries = await ide.listDir(dir);
const ignoreUri = joinPathsToUri(dir, ".gitignore");

View file

@ -10,11 +10,11 @@ import { defaultConfig } from "./default";
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.listProfiles();
expect(profiles.length).toBe(1);
expect(profiles[0].id).toBe("local");
expect(profiles?.length).toBe(1);
expect(profiles?.[0].id).toBe("local");
const currentProfile = testConfigHandler.currentProfile;
expect(currentProfile.profileId).toBe("local");
expect(currentProfile?.profileDescription.id).toBe("local");
});
test("should load the default config successfully", async () => {

View file

@ -1,7 +1,12 @@
import * as fs from "node:fs";
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
import {
ControlPlaneClient,
ControlPlaneSessionInfo,
} from "../control-plane/client.js";
import { getControlPlaneEnv, useHub } from "../control-plane/env.js";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@ -12,20 +17,20 @@ import {
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath } from "../util/paths.js";
import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js";
import { localPathToUri } from "../util/pathToUri.js";
import { ConfigResult } from "./load.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
ONBOARDING_LOCAL_MODEL_TITLE,
LOCAL_ONBOARDING_PROVIDER_TITLE,
} from "./onboarding.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
import {
ProfileDescription,
ProfileLifecycleManager,
} from "./ProfileLifecycleManager.js";
import { pathToFileURL } from "url";
export type { ProfileDescription };
@ -36,76 +41,244 @@ type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
export class ConfigHandler {
private readonly globalContext = new GlobalContext();
private additionalContextProviders: IContextProvider[] = [];
private profiles: ProfileLifecycleManager[];
private selectedProfileId: string;
private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded
private selectedProfileId: string | null = null;
private localProfileManager: ProfileLifecycleManager;
controlPlaneClient: ControlPlaneClient;
initializedPromise: Promise<void>;
constructor(
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private readonly writeLog: (text: string) => Promise<void>,
private controlPlaneClient: ControlPlaneClient,
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.writeLog = writeLog;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
);
// Set local profile as default
const localProfileLoader = new LocalProfileLoader(
ide,
ideSettingsPromise,
controlPlaneClient,
this.controlPlaneClient,
writeLog,
);
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
this.selectedProfileId = localProfileLoader.profileId;
this.localProfileManager = new ProfileLifecycleManager(
localProfileLoader,
this.ide,
);
// Always load local profile immediately in case control plane doesn't load
// Profiles are loaded asynchronously
this.initializedPromise = new Promise((resolve, reject) => {
this.init()
.then(() => {
resolve();
})
.catch((e) => {
reject(e);
});
});
}
/**
* Retrieves the titles of additional context providers that are of type "submenu".
*
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
*/
getAdditionalSubmenuContextProviders(): string[] {
return this.additionalContextProviders
.filter((provider) => provider.description.type === "submenu")
.map((provider) => provider.description.title);
}
private async init() {
try {
void this.loadConfig();
await this.fetchControlPlaneProfiles();
} catch (e) {
// If this fails, make sure at least local profile is loaded
console.error("Failed to fetch control plane profiles in init: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
}
try {
const configResult = await this.loadConfig();
this.notifyConfigListeners(configResult);
} catch (e) {
console.error("Failed to load config: ", e);
}
// Load control plane profiles
void this.fetchControlPlaneProfiles();
}
// This will be the local profile
private get fallbackProfile() {
return this.profiles[0];
}
get currentProfile() {
if (!this.selectedProfileId) {
return null;
}
// IMPORTANT
// We must fall back to null, not the first or local profiles
// Because GUI must be the source of truth for selected profile
return (
this.profiles.find((p) => p.profileId === this.selectedProfileId) ??
this.fallbackProfile
this.profiles?.find(
(p) => p.profileDescription.id === this.selectedProfileId,
) ?? null
);
}
get inactiveProfiles() {
return this.profiles.filter((p) => p.profileId !== this.selectedProfileId);
return (this.profiles ?? []).filter(
(p) => p.profileDescription.id !== this.selectedProfileId,
);
}
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
await this.ide.openFile(pathToFileURL(getConfigJsonPath()).toString());
const ideInfo = await this.ide.getIdeInfo();
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
if (fs.existsSync(configYamlPath)) {
await this.ide.openFile(localPathToUri(configYamlPath));
} else {
await this.ide.openFile(localPathToUri(getConfigJsonPath()));
}
} else {
await this.ide.openUrl(
"https://app.continue.dev/",
// `https://app.continue.dev/workspaces/${openProfileId}/chat`,
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
}
}
async listOrganizations() {
return await this.controlPlaneClient.listOrganizations();
}
async loadAssistantsForSelectedOrg() {
// Get the profiles and create their lifecycle managers
const userId = await this.controlPlaneClient.userId;
const selectedOrgId = await this.getSelectedOrgId();
let profiles: ProfileLifecycleManager[] | null = null;
if (!userId) {
// Not logged in
profiles = [this.localProfileManager];
} else {
// Logged in
const assistants =
await this.controlPlaneClient.listAssistants(selectedOrgId);
const hubProfiles = assistants.map((assistant) => {
const profileLoader = new PlatformProfileLoader(
{
...assistant.configResult,
config: assistant.configResult.config,
},
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
return new ProfileLifecycleManager(profileLoader, this.ide);
});
if (selectedOrgId === null) {
// Personal
profiles = [...hubProfiles, this.localProfileManager];
} else {
// Organization
profiles = hubProfiles;
}
}
await this.updateAvailableProfiles(profiles);
}
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
this.profiles = profiles;
// If the last selected profile is in the list choose that
// Otherwise, choose the first profile
const previouslySelectedProfileId =
await this.getPersistedSelectedProfileId();
// Check if the previously selected profile exists in the current profiles
const profileExists = profiles.some(
(profile) =>
profile.profileDescription.id === previouslySelectedProfileId,
);
const selectedProfileId = profileExists
? previouslySelectedProfileId
: (profiles[0]?.profileDescription.id ?? null);
// Notify listeners
const profileDescriptions = profiles.map(
(profile) => profile.profileDescription,
);
this.notifyProfileListeners(profileDescriptions, selectedProfileId);
await this.setSelectedProfile(selectedProfileId);
}
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
// We use this to keep track of whether we should reload the assistants
private lastFullSlugsList: FullSlug[] = [];
private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean {
if (a.length !== b.length) {
return true;
}
for (let i = 0; i < a.length; i++) {
if (a[i].ownerSlug !== b[i].ownerSlug) {
return true;
}
if (a[i].packageSlug !== b[i].packageSlug) {
return true;
}
if (a[i].versionSlug !== b[i].versionSlug) {
return true;
}
}
return false;
}
private async reloadHubAssistants() {
const selectedOrgId = await this.getSelectedOrgId();
const newFullSlugsList =
await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId);
if (newFullSlugsList) {
const shouldReload = this.fullSlugsListsDiffer(
newFullSlugsList,
this.lastFullSlugsList,
);
if (shouldReload) {
await this.loadAssistantsForSelectedOrg();
}
this.lastFullSlugsList = newFullSlugsList;
}
}
private async fetchControlPlaneProfiles() {
// Get the profiles and create their lifecycle managers
this.controlPlaneClient
.listWorkspaces()
.then(async (workspaces) => {
this.profiles = this.profiles.filter(
(profile) => profile.profileId === "local",
);
if (await useHub(this.ideSettingsPromise)) {
clearInterval(this.platformProfilesRefreshInterval);
await this.loadAssistantsForSelectedOrg();
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
// If so, we do the full (more expensive) reload
this.platformProfilesRefreshInterval = setInterval(
this.reloadHubAssistants.bind(this),
PlatformProfileLoader.RELOAD_INTERVAL,
);
} else {
try {
const workspaces = await this.controlPlaneClient.listWorkspaces();
const profiles = [this.localProfileManager];
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
@ -116,36 +289,39 @@ export class ConfigHandler {
this.writeLog,
this.reloadConfig.bind(this),
);
this.profiles.push(new ProfileLifecycleManager(profileLoader));
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
});
this.notifyProfileListeners(
this.profiles.map((profile) => profile.profileDescription),
);
// Check the last selected workspace, and reload if it isn't local
const workspaceId = await this.getWorkspaceId();
const lastSelectedWorkspaceIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId];
if (selectedWorkspaceId) {
this.selectedProfileId = selectedWorkspaceId;
await this.loadConfig();
} else {
// Otherwise we stick with local profile, and record choice
lastSelectedWorkspaceIds[workspaceId] = this.selectedProfileId;
this.globalContext.update(
"lastSelectedProfileForWorkspace",
lastSelectedWorkspaceIds,
);
}
})
.catch((e) => {
console.error(e);
});
await this.updateAvailableProfiles(profiles);
} catch (e: any) {
console.error("Failed to load profiles: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
}
}
}
async setSelectedProfile(profileId: string) {
async getPersistedSelectedProfileId(): Promise<string | null> {
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
return lastSelectedIds[workspaceId] ?? null;
}
async getSelectedOrgId(): Promise<string | null> {
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
return selectedOrgs[await this.getWorkspaceId()] ?? null;
}
async setSelectedOrgId(orgId: string | null) {
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
selectedOrgs[await this.getWorkspaceId()] = orgId;
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
}
async setSelectedProfile(profileId: string | null) {
this.selectedProfileId = profileId;
const result = await this.loadConfig();
this.notifyConfigListeners(result);
@ -170,27 +346,39 @@ export class ConfigHandler {
void this.reloadConfig();
}
updateControlPlaneSessionInfo(
async updateControlPlaneSessionInfo(
sessionInfo: ControlPlaneSessionInfo | undefined,
) {
this.controlPlaneClient = new ControlPlaneClient(
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
);
this.fetchControlPlaneProfiles().catch((e) => {
this.fetchControlPlaneProfiles().catch(async (e) => {
console.error("Failed to fetch control plane profiles: ", e);
await this.updateAvailableProfiles([this.localProfileManager]);
await this.reloadConfig();
});
}
private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = [];
private profilesListeners: ((
profiles: ProfileDescription[],
selectedProfileId: string | null,
) => void)[] = [];
onDidChangeAvailableProfiles(
listener: (profiles: ProfileDescription[]) => void,
listener: (
profiles: ProfileDescription[],
selectedProfileId: string | null,
) => void,
) {
this.profilesListeners.push(listener);
}
private notifyProfileListeners(profiles: ProfileDescription[]) {
private notifyProfileListeners(
profiles: ProfileDescription[],
selectedProfileId: string | null,
) {
for (const listener of this.profilesListeners) {
listener(profiles);
listener(profiles, selectedProfileId);
}
}
@ -207,33 +395,54 @@ export class ConfigHandler {
this.updateListeners.push(listener);
}
// TODO: this isn't right, there are two different senses in which you want to "reload"
async reloadConfig() {
// TODO: this isn't right, there are two different senses in which you want to "reload"
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
const { config, errors, configLoadInterrupted } =
await this.currentProfile.reloadConfig();
await this.currentProfile.reloadConfig(this.additionalContextProviders);
if (config) {
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
}
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
return { config, errors };
return { config, errors, configLoadInterrupted };
}
getSerializedConfig(): Promise<
async getSerializedConfig(): Promise<
ConfigResult<BrowserSerializedContinueConfig>
> {
return this.currentProfile.getSerializedConfig(
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
return await this.currentProfile.getSerializedConfig(
this.additionalContextProviders,
);
}
listProfiles(): ProfileDescription[] {
return this.profiles.map((p) => p.profileDescription);
listProfiles(): ProfileDescription[] | null {
return this.profiles?.map((p) => p.profileDescription) ?? null;
}
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
return await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
@ -243,7 +452,7 @@ export class ConfigHandler {
const { config } = await this.loadConfig();
const model = config?.models.find((m) => m.title === title);
if (!model) {
if (title === ONBOARDING_LOCAL_MODEL_TITLE) {
if (title === LOCAL_ONBOARDING_PROVIDER_TITLE) {
// Special case, make calls to Ollama before we have it in the config
const ollama = new Ollama({
model: LOCAL_ONBOARDING_CHAT_MODEL,

View file

@ -1,15 +1,33 @@
import {
ConfigResult,
ConfigValidationError,
FullSlug,
} from "@continuedev/config-yaml";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
IContextProvider,
IDE,
} from "../index.js";
import { ConfigResult, finalToBrowserConfig } from "./load.js";
import { finalToBrowserConfig } from "./load.js";
import { IProfileLoader } from "./profile/IProfileLoader.js";
export interface ProfileDescription {
fullSlug: FullSlug;
profileType: "control-plane" | "local" | "platform";
title: string;
id: string;
iconUrl: string;
errors: ConfigValidationError[] | undefined;
}
export interface OrganizationDescription {
id: string;
iconUrl: string;
name: string;
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
}
export class ProfileLifecycleManager {
@ -17,21 +35,13 @@ export class ProfileLifecycleManager {
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;
private pendingConfigPromise?: Promise<ConfigResult<ContinueConfig>>;
constructor(private readonly profileLoader: IProfileLoader) {}
get profileId() {
return this.profileLoader.profileId;
}
get profileTitle() {
return this.profileLoader.profileTitle;
}
constructor(
private readonly profileLoader: IProfileLoader,
private readonly ide: IDE,
) {}
get profileDescription(): ProfileDescription {
return {
title: this.profileTitle,
id: this.profileId,
};
return this.profileLoader.description;
}
clearConfig() {
@ -41,12 +51,14 @@ export class ProfileLifecycleManager {
}
// Clear saved config and reload
async reloadConfig(): Promise<ConfigResult<ContinueConfig>> {
async reloadConfig(
additionalContextProviders: IContextProvider[] = [],
): Promise<ConfigResult<ContinueConfig>> {
this.savedConfigResult = undefined;
this.savedBrowserConfigResult = undefined;
this.pendingConfigPromise = undefined;
return this.loadConfig([], true);
return this.loadConfig(additionalContextProviders, true);
}
async loadConfig(
@ -64,21 +76,31 @@ export class ProfileLifecycleManager {
// Set pending config promise
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
const result = await this.profileLoader.doLoadConfig();
let result: ConfigResult<ContinueConfig>;
try {
result = await this.profileLoader.doLoadConfig();
} catch (e: any) {
result = {
errors: [
{
fatal: true,
message: e.message,
},
],
config: undefined,
configLoadInterrupted: true,
};
}
if (result.config) {
// Add registered context providers
result.config.contextProviders = (
result.config.contextProviders ?? []
).concat(additionalContextProviders);
this.savedConfigResult = result;
resolve(result);
} else if (result.errors) {
reject(
`Error in config.json: ${result.errors.map((item) => item.message).join(" | ")}`,
);
}
this.savedConfigResult = result;
resolve(result);
});
// Wait for the config promise to resolve
@ -100,7 +122,10 @@ export class ProfileLifecycleManager {
config: undefined,
};
}
const serializedConfig = finalToBrowserConfig(result.config);
const serializedConfig = await finalToBrowserConfig(
result.config,
this.ide,
);
return {
...result,
config: serializedConfig,

View file

@ -5,20 +5,6 @@ import {
SlashCommandDescription,
} from "../";
export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = {
model: "claude-3-5-sonnet-latest",
provider: "anthropic",
apiKey: "",
title: "Claude 3.5 Sonnet",
};
export const DEFAULT_AUTOCOMPLETE_MODEL_CONFIG: ModelDescription = {
title: "Codestral",
provider: "mistral",
model: "codestral-latest",
apiKey: "",
};
export const FREE_TRIAL_MODELS: ModelDescription[] = [
{
title: "Claude 3.5 Sonnet (Free Trial)",
@ -93,15 +79,15 @@ export const defaultSlashCommandsJetBrains = [
];
export const defaultConfig: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
models: [],
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
data: [],
};
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
models: [],
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
data: [],
};

View file

@ -3,6 +3,11 @@ import * as fs from "fs";
import os from "os";
import path from "path";
import {
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as JSONC from "comment-json";
import * as tar from "tar";
@ -18,6 +23,7 @@ import {
EmbeddingsProviderDescription,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
ILLM,
@ -30,14 +36,16 @@ import {
import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index.js";
} from "../commands/index";
import { AllRerankers } from "../context/allRerankers";
import { MCPManagerSingleton } from "../context/mcp";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
import { useHub } from "../control-plane/env";
import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
import { BaseLLM } from "../llm";
import { llmFromDescription } from "../llm/llms";
@ -61,6 +69,7 @@ import {
getContinueDotEnv,
getEsbuildBinaryPath,
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import {
defaultContextProvidersJetBrains,
@ -69,16 +78,13 @@ import {
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
// import { isSupportedLanceDbCpuTarget } from "./util";
import { ConfigValidationError, validateConfig } from "./validation.js";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util";
import { validateConfig } from "./validation.js";
export interface ConfigResult<T> {
config: T | undefined;
errors: ConfigValidationError[] | undefined;
configLoadInterrupted: boolean;
}
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
export function resolveSerializedConfig(
filepath: string,
): SerializedContinueConfig {
let content = fs.readFileSync(filepath, "utf8");
const config = JSONC.parse(content) as unknown as SerializedContinueConfig;
if (config.env && Array.isArray(config.env)) {
@ -114,11 +120,10 @@ function loadSerializedConfig(
overrideConfigJson: SerializedContinueConfig | undefined,
ide: IDE,
): ConfigResult<SerializedContinueConfig> {
const configPath = getConfigJsonPath(ideType);
let config: SerializedContinueConfig = overrideConfigJson!;
if (!config) {
try {
config = resolveSerializedConfig(configPath);
config = resolveSerializedConfig(getConfigJsonPath(ideType));
} catch (e) {
throw new Error(`Failed to parse config.json: ${e}`);
}
@ -138,13 +143,6 @@ function loadSerializedConfig(
config.allowAnonymousTelemetry = true;
}
if (config.ui?.getChatTitles === undefined) {
config.ui = {
...config.ui,
getChatTitles: true,
};
}
if (ideSettings.remoteConfigServerUrl) {
try {
const remoteConfigJson = resolveSerializedConfig(
@ -175,10 +173,9 @@ function loadSerializedConfig(
? [...defaultSlashCommandsVscode]
: [...defaultSlashCommandsJetBrains];
// Temporarily disabling this check until we can verify the commands are accuarate
// if (!isSupportedLanceDbCpuTarget(ide)) {
// config.disableIndexing = true;
// }
if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) {
config.disableIndexing = true;
}
return { config, errors, configLoadInterrupted: false };
}
@ -229,24 +226,18 @@ function isModelDescription(
return (llm as ModelDescription).title !== undefined;
}
function isContextProviderWithParams(
export function isContextProviderWithParams(
contextProvider: CustomContextProvider | ContextProviderWithParams,
): contextProvider is ContextProviderWithParams {
return (contextProvider as ContextProviderWithParams).name !== undefined;
}
const getCodebaseProvider = async (params: any) => {
const { default: CodebaseContextProvider } = await import(
"../context/providers/CodebaseContextProvider"
);
return new CodebaseContextProvider(params);
};
/** Only difference between intermediate and final configs is the `models` array */
async function intermediateToFinalConfig(
config: Config,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -281,7 +272,7 @@ async function intermediateToFinalConfig(
{
...desc,
model: modelName,
title: `${llm.title} - ${modelName}`,
title: modelName,
},
ide.readFile.bind(ide),
uniqueId,
@ -335,6 +326,7 @@ async function intermediateToFinalConfig(
...model.requestOptions,
...config.requestOptions,
};
model.roles = model.roles ?? ["chat", "apply", "edit", "summarize"]; // Default to chat role if not specified
}
if (allowFreeTrial) {
@ -406,7 +398,7 @@ async function intermediateToFinalConfig(
new FileContextProvider({}),
// Add codebase provider if indexing is enabled
...(!config.disableIndexing
? [await getCodebaseProvider(codebaseContextParams)]
? [new CodebaseContextProvider(codebaseContextParams)]
: []),
// Add prompt files provider if enabled
...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []),
@ -444,23 +436,28 @@ async function intermediateToFinalConfig(
}
// Embeddings Provider
const embeddingsProviderDescription = config.embeddingsProvider as
| EmbeddingsProviderDescription
| undefined;
if (embeddingsProviderDescription?.provider) {
const { provider, ...options } = embeddingsProviderDescription;
function getEmbeddingsILLM(
embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
): ILLM | null {
if (!embedConfig) {
return null;
}
if ("providerName" in embedConfig) {
return embedConfig;
}
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
config.embeddingsProvider = new embeddingsProviderClass();
return new embeddingsProviderClass();
} else {
const llmOptions: LLMOptions = {
model: options.model ?? "UNSPECIFIED",
...options,
};
config.embeddingsProvider = new embeddingsProviderClass(
return new embeddingsProviderClass(
llmOptions,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
@ -469,42 +466,74 @@ async function intermediateToFinalConfig(
}),
);
}
} else {
errors.push({
fatal: false,
message: `Embeddings provider ${provider} not found. Using default`,
});
}
return null;
}
if (!config.embeddingsProvider) {
config.embeddingsProvider = new TransformersJsEmbeddingsProvider();
}
const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider);
// Reranker
if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) {
function getRerankingILLM(
rerankingConfig: ILLM | RerankerDescription | undefined,
): ILLM | null {
if (!rerankingConfig) {
return null;
}
if ("providerName" in rerankingConfig) {
return rerankingConfig;
}
const { name, params } = config.reranker as RerankerDescription;
const rerankerClass = AllRerankers[name];
if (name === "llm") {
const llm = models.find((model) => model.title === params?.modelTitle);
if (!llm) {
console.warn(`Unknown model ${params?.modelTitle}`);
errors.push({
fatal: false,
message: `Unknown reranking model ${params?.modelTitle}`,
});
return null;
} else {
config.reranker = new LLMReranker(llm);
return new LLMReranker(llm);
}
} else if (rerankerClass) {
const llmOptions: LLMOptions = {
model: "rerank-2",
...params,
};
config.reranker = new rerankerClass(llmOptions);
return new rerankerClass(llmOptions);
}
return null;
}
const newReranker = getRerankingILLM(config.reranker);
let continueConfig: ContinueConfig = {
const continueConfig: ContinueConfig = {
...config,
contextProviders,
models,
embeddingsProvider: config.embeddingsProvider as any,
tabAutocompleteModels,
reranker: config.reranker as any,
tools: allTools,
modelsByRole: {
chat: models,
edit: models,
apply: models,
summarize: models,
autocomplete: [...tabAutocompleteModels],
embed: newEmbedder ? [newEmbedder] : [],
rerank: newReranker ? [newReranker] : [],
},
selectedModelByRole: {
chat: null, // Not implemented (uses GUI defaultModel)
edit: null,
apply: null,
embed: newEmbedder ?? null,
autocomplete: null,
rerank: newReranker ?? null,
summarize: null, // Not implemented
},
};
// Apply MCP if specified
@ -526,6 +555,8 @@ async function intermediateToFinalConfig(
continueConfig,
mcpId,
abortController.signal,
"MCP Server",
server.faviconUrl,
);
if (mcpError) {
errors.push(mcpError);
@ -544,44 +575,112 @@ async function intermediateToFinalConfig(
);
}
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
if (inlineEditModel) {
const match = continueConfig.models.find(
(m) => m.title === inlineEditModel,
);
if (match) {
continueConfig.selectedModelByRole.edit = match;
continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set
} else {
errors.push({
fatal: false,
message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`,
});
}
}
const applyBlockModel = getModelByRole(
continueConfig,
"applyCodeBlock",
)?.title;
if (applyBlockModel) {
const match = continueConfig.models.find(
(m) => m.title === applyBlockModel,
);
if (match) {
continueConfig.selectedModelByRole.apply = match;
continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set
} else {
errors.push({
fatal: false,
message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`,
});
}
}
// Add transformers JS to the embed models list if not already added
if (
ideInfo.ideType === "vscode" &&
!continueConfig.modelsByRole.embed.find(
(m) => m.providerName === "transformers.js",
)
) {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
}
return { config: continueConfig, errors };
}
function finalToBrowserConfig(
function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
return {
provider: llm.providerName,
model: llm.model,
title: llm.title ?? llm.model,
apiKey: llm.apiKey,
apiBase: llm.apiBase,
contextLength: llm.contextLength,
template: llm.template,
completionOptions: llm.completionOptions,
systemMessage: llm.systemMessage,
requestOptions: llm.requestOptions,
promptTemplates: llm.promptTemplates as any,
capabilities: llm.capabilities,
roles: llm.roles,
};
}
async function finalToBrowserConfig(
final: ContinueConfig,
): BrowserSerializedContinueConfig {
ide: IDE,
): Promise<BrowserSerializedContinueConfig> {
return {
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
models: final.models.map((m) => ({
provider: m.providerName,
model: m.model,
title: m.title ?? m.model,
apiKey: m.apiKey,
apiBase: m.apiBase,
contextLength: m.contextLength,
template: m.template,
completionOptions: m.completionOptions,
systemMessage: m.systemMessage,
requestOptions: m.requestOptions,
promptTemplates: m.promptTemplates as any,
capabilities: m.capabilities,
})),
models: final.models.map(llmToSerializedModelDescription),
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map((s) => ({
name: s.name,
description: s.description,
params: s.params, //PZTODO: is this why params aren't referenced properly by slash commands?
params: s.params, // TODO: is this why params aren't referenced properly by slash commands?
})),
contextProviders: final.contextProviders?.map((c) => c.description),
disableIndexing: final.disableIndexing,
disableSessionTitles: final.disableSessionTitles,
userToken: final.userToken,
embeddingsProvider: final.embeddingsProvider?.embeddingId,
ui: final.ui,
experimental: final.experimental,
docs: final.docs,
tools: final.tools,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),
modelsByRole: Object.fromEntries(
Object.entries(final.modelsByRole).map(([k, v]) => [
k,
v.map(llmToSerializedModelDescription),
]),
) as Record<ModelRole, ModelDescription[]>, // TODO better types here
selectedModelByRole: Object.fromEntries(
Object.entries(final.selectedModelByRole).map(([k, v]) => [
k,
v ? llmToSerializedModelDescription(v) : null,
]),
) as Record<ModelRole, ModelDescription | null>, // TODO better types here
// data not included here because client doesn't need
};
}
@ -765,11 +864,11 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
return readConfigJs();
}
async function loadFullConfigNode(
async function loadContinueConfigFromJson(
ide: IDE,
workspaceConfigs: ContinueRcJson[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -783,7 +882,7 @@ async function loadFullConfigNode(
} = loadSerializedConfig(
workspaceConfigs,
ideSettings,
ideType,
ideInfo.ideType,
overrideConfigJson,
ide,
);
@ -797,11 +896,19 @@ async function loadFullConfigNode(
serialized.systemMessage = systemPromptDotFile;
}
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
// Convert serialized to intermediate config
let intermediate = await serializedToIntermediateConfig(serialized, ide);
let intermediate = await serializedToIntermediateConfig(withShared, ide);
// Apply config.ts to modify intermediate config
const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType);
const configJsContents = await buildConfigTsandReadConfigJs(
ide,
ideInfo.ideType,
);
if (configJsContents) {
try {
// Try config.ts first
@ -816,7 +923,7 @@ async function loadFullConfigNode(
"Could not load config.ts as absolute path, retrying as file url ...",
);
try {
module = await import(`file://${configJsPath}`);
module = await import(localPathToUri(configJsPath));
} catch (e) {
throw new Error("Could not load config.ts as file url either", {
cause: e,
@ -861,6 +968,7 @@ async function loadFullConfigNode(
intermediate,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -875,6 +983,6 @@ async function loadFullConfigNode(
export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadFullConfigNode,
loadContinueConfigFromJson,
type BrowserSerializedContinueConfig,
};

View file

@ -0,0 +1,208 @@
import { IDE } from "..";
import { deduplicateArray } from "../util";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigJson } from "../util/paths";
import { resolveSerializedConfig } from "./load";
import { SharedConfigSchema } from "./sharedConfig";
/*
This migration function eliminates deprecated values from the json file
And writes them to the shared config
*/
export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
const globalContext = new GlobalContext();
const currentSharedConfig = globalContext.getSharedConfig(); // for merging security concerns
try {
let config = resolveSerializedConfig(filepath);
const shareConfigUpdates: SharedConfigSchema = {};
let effected = false;
const { allowAnonymousTelemetry, ...withoutAllowTelemetry } = config;
if (allowAnonymousTelemetry !== undefined) {
if (currentSharedConfig.allowAnonymousTelemetry !== false) {
// safe merge for security
shareConfigUpdates.allowAnonymousTelemetry = allowAnonymousTelemetry;
}
config = withoutAllowTelemetry;
effected = true;
}
const { disableIndexing, ...withoutDisableIndexing } = config;
if (disableIndexing !== undefined) {
if (currentSharedConfig.disableIndexing !== true) {
// safe merge for security
shareConfigUpdates.disableIndexing = disableIndexing;
}
config = withoutDisableIndexing;
effected = true;
}
const { disableSessionTitles, ...withoutDisableSessionTitles } = config;
if (config.disableSessionTitles !== undefined) {
if (currentSharedConfig.disableSessionTitles !== true) {
// safe merge for security
shareConfigUpdates.disableSessionTitles = config.disableSessionTitles;
}
config = withoutDisableSessionTitles;
effected = true;
}
const { tabAutocompleteOptions, ...withoutAutocompleteOptions } = config;
if (tabAutocompleteOptions !== undefined) {
let migratedAutocomplete = { ...tabAutocompleteOptions };
const { useCache, ...withoutUseCache } = migratedAutocomplete;
if (useCache !== undefined) {
shareConfigUpdates.useAutocompleteCache = useCache;
migratedAutocomplete = withoutUseCache;
effected = true;
}
const { multilineCompletions, ...withoutMultiline } =
migratedAutocomplete;
if (multilineCompletions !== undefined) {
shareConfigUpdates.useAutocompleteMultilineCompletions =
multilineCompletions;
migratedAutocomplete = withoutMultiline;
effected = true;
}
const { disableInFiles, ...withoutDisableInFiles } = migratedAutocomplete;
if (disableInFiles !== undefined) {
if (currentSharedConfig.disableAutocompleteInFiles !== undefined) {
// safe merge for security
shareConfigUpdates.disableAutocompleteInFiles = deduplicateArray(
[
...currentSharedConfig.disableAutocompleteInFiles,
...disableInFiles,
],
(a, b) => a === b,
);
} else {
shareConfigUpdates.disableAutocompleteInFiles = disableInFiles;
}
shareConfigUpdates.disableAutocompleteInFiles = disableInFiles;
migratedAutocomplete = withoutDisableInFiles;
effected = true;
}
if (Object.keys(migratedAutocomplete).length > 0) {
config = {
...withoutAutocompleteOptions,
tabAutocompleteOptions: migratedAutocomplete,
};
} else {
config = withoutAutocompleteOptions;
}
}
const { experimental, ...withoutExperimental } = config;
if (experimental !== undefined) {
let migratedExperimental = { ...experimental };
const { useChromiumForDocsCrawling, ...rest10 } = migratedExperimental;
if (useChromiumForDocsCrawling !== undefined) {
shareConfigUpdates.useChromiumForDocsCrawling =
useChromiumForDocsCrawling;
migratedExperimental = rest10;
effected = true;
}
const { promptPath, ...withoutPromptPath } = migratedExperimental;
if (promptPath !== undefined) {
shareConfigUpdates.promptPath = promptPath;
migratedExperimental = withoutPromptPath;
effected = true;
}
const { readResponseTTS, ...withoutReadTTS } = migratedExperimental;
if (readResponseTTS !== undefined) {
shareConfigUpdates.readResponseTTS = readResponseTTS;
migratedExperimental = withoutReadTTS;
effected = true;
}
if (Object.keys(migratedExperimental).length > 0) {
config = {
...withoutExperimental,
experimental: migratedExperimental,
};
} else {
config = withoutExperimental;
}
}
const { ui, ...withoutUI } = config;
if (ui !== undefined) {
let migratedUI = { ...ui };
const { codeBlockToolbarPosition, ...withoutToolbarPosition } =
migratedUI;
if (codeBlockToolbarPosition !== undefined) {
shareConfigUpdates.codeBlockToolbarPosition = codeBlockToolbarPosition;
migratedUI = withoutToolbarPosition;
effected = true;
}
const { fontSize, ...withoutFontSize } = migratedUI;
if (fontSize !== undefined) {
shareConfigUpdates.fontSize = fontSize;
migratedUI = withoutFontSize;
effected = true;
}
const { codeWrap, ...withoutCodeWrap } = migratedUI;
if (codeWrap !== undefined) {
shareConfigUpdates.codeWrap = codeWrap;
migratedUI = withoutCodeWrap;
effected = true;
}
const { displayRawMarkdown, ...withoutMD } = migratedUI;
if (displayRawMarkdown !== undefined) {
shareConfigUpdates.displayRawMarkdown = displayRawMarkdown;
migratedUI = withoutMD;
effected = true;
}
const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI;
if (showChatScrollbar !== undefined) {
shareConfigUpdates.showChatScrollbar = showChatScrollbar;
migratedUI = withoutShowChatScrollbar;
effected = true;
}
// Ancient param to overwrite disableSessionTitles
if ("getChatTitles" in migratedUI) {
const { getChatTitles, ...withoutChatTitles } = migratedUI;
if (getChatTitles === false) {
shareConfigUpdates.disableSessionTitles = true;
migratedUI = withoutChatTitles;
effected = true;
}
}
if (Object.keys(migratedUI).length > 0) {
config = {
...withoutUI,
ui: migratedUI,
};
} else {
config = withoutUI;
}
}
if (effected) {
new GlobalContext().updateSharedConfig(shareConfigUpdates);
editConfigJson(() => config);
// void ide.showToast(
// "warning",
// "Migrated deprecated Continue JSON settings. Edit in the Settings Page",
// );
}
} catch (e) {
throw new Error(`Migration: Failed to parse config.json: ${e}`);
}
}

View file

@ -3,10 +3,12 @@ import { SerializedContinueConfig } from "../";
import { FREE_TRIAL_MODELS } from "./default";
export const TRIAL_FIM_MODEL = "codestral-latest";
export const ONBOARDING_LOCAL_MODEL_TITLE = "Ollama";
export const LOCAL_ONBOARDING_PROVIDER_TITLE = "Ollama";
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b-base";
export const LOCAL_ONBOARDING_FIM_TITLE = "Qwen2.5-Coder 1.5B";
export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b";
export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";
export const LOCAL_ONBOARDING_EMBEDDINGS_MODEL = "nomic-embed-text:latest";
/**
* We set the "best" chat + autocopmlete models by default
@ -35,13 +37,13 @@ export function setupLocalConfig(
...config.models.filter((model) => model.provider !== "free-trial"),
],
tabAutocompleteModel: {
title: "Qwen2.5-Coder 1.5B",
title: LOCAL_ONBOARDING_FIM_TITLE,
provider: "ollama",
model: LOCAL_ONBOARDING_FIM_MODEL,
},
embeddingsProvider: {
provider: "ollama",
model: "nomic-embed-text",
model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL,
},
};
}
@ -68,24 +70,3 @@ export function setupQuickstartConfig(
},
};
}
export function setupLocalConfigAfterFreeTrial(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: [
{
title: LOCAL_ONBOARDING_CHAT_TITLE,
provider: "ollama",
model: LOCAL_ONBOARDING_CHAT_MODEL,
},
{
title: ONBOARDING_LOCAL_MODEL_TITLE,
provider: "ollama",
model: "AUTODETECT",
},
...config.models.filter((model) => model.provider !== "free-trial"),
],
};
}

View file

@ -1,4 +1,5 @@
import { ConfigJson } from "@continuedev/config-types";
import { ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import {
@ -7,7 +8,7 @@ import {
IdeSettings,
SerializedContinueConfig,
} from "../../index.js";
import { ConfigResult } from "../load.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
@ -15,8 +16,7 @@ import { IProfileLoader } from "./IProfileLoader.js";
export default class ControlPlaneProfileLoader implements IProfileLoader {
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
readonly profileId: string;
profileTitle: string;
description: ProfileDescription;
workspaceSettings: ConfigJson | undefined;
@ -29,12 +29,24 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
private writeLog: (message: string) => Promise<void>,
private readonly onReload: () => void,
) {
this.profileId = workspaceId;
this.profileTitle = workspaceTitle;
this.description = {
id: workspaceId,
profileType: "control-plane",
iconUrl: "",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
title: workspaceTitle,
errors: undefined,
};
setInterval(async () => {
this.workspaceSettings =
await this.controlPlaneClient.getSettingsForWorkspace(this.profileId);
await this.controlPlaneClient.getSettingsForWorkspace(
this.description.id,
);
this.onReload();
}, ControlPlaneProfileLoader.RELOAD_INTERVAL);
}
@ -43,7 +55,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
const settings =
this.workspaceSettings ??
((await this.controlPlaneClient.getSettingsForWorkspace(
this.profileId,
this.description.id,
)) as any);
const serializedConfig: SerializedContinueConfig = settings;
@ -53,6 +65,8 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
this.controlPlaneClient,
this.writeLog,
serializedConfig,
undefined,
undefined,
this.workspaceId,
);

View file

@ -1,12 +1,12 @@
// ProfileHandlers manage the loading of a config, allowing us to abstract over different ways of getting to a ContinueConfig
import { ConfigResult } from "@continuedev/config-yaml";
import { ContinueConfig } from "../../index.js";
import { ConfigResult } from "../load.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
// After we have the ContinueConfig, the ConfigHandler takes care of everything else (loading models, lifecycle, etc.)
export interface IProfileLoader {
profileTitle: string;
profileId: string;
description: ProfileDescription;
doLoadConfig(): Promise<ConfigResult<ContinueConfig>>;
setIsActive(isActive: boolean): void;
}

View file

@ -1,14 +1,26 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ConfigResult } from "../load.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
export default class LocalProfileLoader implements IProfileLoader {
static ID = "local";
profileId = LocalProfileLoader.ID;
profileTitle = "Local Config";
description: ProfileDescription = {
id: LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
iconUrl: "",
title: "Local Config",
errors: undefined,
};
constructor(
private ide: IDE,
@ -18,13 +30,20 @@ export default class LocalProfileLoader implements IProfileLoader {
) {}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
return doLoadConfig(
const result = await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
undefined,
undefined,
undefined,
this.description.id,
);
this.description.errors = result.errors;
return result;
}
setIsActive(isActive: boolean): void {}

View file

@ -0,0 +1,82 @@
import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
/**
* Metadata about the package that is currently being loaded
* If this is `undefined`, it's not a config from the platform,
* could be local for example.
*/
export interface PlatformConfigMetadata {
ownerSlug: string;
packageSlug: string;
}
export default class PlatformProfileLoader implements IProfileLoader {
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
description: ProfileDescription;
constructor(
private configResult: ConfigResult<AssistantUnrolled>,
private readonly ownerSlug: string,
private readonly packageSlug: string,
private readonly iconUrl: string,
versionSlug: string,
private readonly controlPlaneClient: ControlPlaneClient,
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private writeLog: (message: string) => Promise<void>,
private readonly onReload: () => void,
) {
this.description = {
id: `${ownerSlug}/${packageSlug}`,
profileType: "platform",
fullSlug: {
ownerSlug,
packageSlug,
versionSlug,
},
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
iconUrl: this.iconUrl,
};
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (this.configResult.errors?.length) {
return {
config: undefined,
errors: this.configResult.errors,
configLoadInterrupted: false,
};
}
const results = await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
undefined,
this.configResult.config,
{
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
},
this.description.id,
);
return {
...results,
errors: [], // Don't do config validation here, it happens in admin panel
};
}
setIsActive(isActive: boolean): void {}
}

View file

@ -1,5 +1,11 @@
import fs from "fs";
import {
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import {
ContinueConfig,
ContinueRcJson,
@ -9,15 +15,17 @@ import {
} from "../../";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { controlPlaneEnv } from "../../control-plane/env.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { getConfigYamlPath } from "../../util/paths";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { ConfigResult, loadFullConfigNode } from "../load";
import { ConfigValidationError } from "../validation";
import { loadContinueConfigFromJson } from "../load";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
export default async function doLoadConfig(
ide: IDE,
@ -25,7 +33,9 @@ export default async function doLoadConfig(
controlPlaneClient: ControlPlaneClient,
writeLog: (message: string) => Promise<void>,
overrideConfigJson: SerializedContinueConfig | undefined,
workspaceId?: string,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
profileId: string,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
@ -33,33 +43,41 @@ export default async function doLoadConfig(
const ideSettings = await ideSettingsPromise;
const workOsAccessToken = await controlPlaneClient.getAccessToken();
// Migrations for old config files
// Removes
const configJsonPath = getConfigJsonPath(ideInfo.ideType);
if (fs.existsSync(configJsonPath)) {
migrateJsonSharedConfig(configJsonPath, ide);
}
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
let newConfig: ContinueConfig | undefined;
let errors: ConfigValidationError[] | undefined;
let configLoadInterrupted = false;
if (fs.existsSync(configYamlPath)) {
if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
const result = await loadContinueConfigFromYaml(
ide,
workspaceConfigs.map((c) => JSON.stringify(c)),
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
undefined,
// overrideConfigYaml, TODO
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
);
newConfig = result.config;
errors = result.errors;
configLoadInterrupted = result.configLoadInterrupted;
} else {
const result = await loadFullConfigNode(
const result = await loadContinueConfigFromJson(
ide,
workspaceConfigs,
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -70,6 +88,11 @@ export default async function doLoadConfig(
configLoadInterrupted = result.configLoadInterrupted;
}
// Rectify model selections for each role
if (newConfig) {
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
}
if (configLoadInterrupted || !newConfig) {
return { errors, config: newConfig, configLoadInterrupted: true };
}
@ -91,27 +114,31 @@ export default async function doLoadConfig(
const controlPlane = (newConfig as any).controlPlane;
const useOnPremProxy =
controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
const env = await getControlPlaneEnv(ideSettingsPromise);
let controlPlaneProxyUrl: string = useOnPremProxy
? controlPlane?.proxyUrl
: controlPlaneEnv.DEFAULT_CONTROL_PLANE_PROXY_URL;
: env.DEFAULT_CONTROL_PLANE_PROXY_URL;
if (!controlPlaneProxyUrl.endsWith("/")) {
controlPlaneProxyUrl += "/";
}
const controlPlaneProxyInfo = {
workspaceId,
profileId,
controlPlaneProxyUrl,
workOsAccessToken,
};
if (newConfig.analytics) {
await TeamAnalytics.setup(
newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all
newConfig.analytics,
uniqueId,
ideInfo.extensionVersion,
controlPlaneClient,
controlPlaneProxyInfo,
);
} else {
await TeamAnalytics.shutdown();
}
newConfig = await injectControlPlaneProxyInfo(
@ -127,21 +154,26 @@ async function injectControlPlaneProxyInfo(
config: ContinueConfig,
info: ControlPlaneProxyInfo,
): Promise<ContinueConfig> {
[...config.models, ...(config.tabAutocompleteModels ?? [])].forEach(
async (model) => {
Object.keys(config.modelsByRole).forEach((key) => {
config.modelsByRole[key as ModelRole].forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
},
);
});
});
if (config.embeddingsProvider?.providerName === "continue-proxy") {
(config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info;
}
Object.keys(config.selectedModelByRole).forEach((key) => {
const model = config.selectedModelByRole[key as ModelRole];
if (model?.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
if (config.reranker?.providerName === "continue-proxy") {
(config.reranker as ContinueProxy).controlPlaneProxyInfo = info;
}
config.models.forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
return config;
}

View file

@ -0,0 +1,67 @@
import { ModelRole } from "@continuedev/config-yaml";
import { ContinueConfig, ILLM } from "..";
import {
GlobalContext,
GlobalContextModelSelections,
} from "../util/GlobalContext";
export function rectifySelectedModelsFromGlobalContext(
continueConfig: ContinueConfig,
profileId: string,
): ContinueConfig {
const configCopy = { ...continueConfig };
const globalContext = new GlobalContext();
const currentSelectedModels = globalContext.get("selectedModelsByProfileId");
const currentForProfile: GlobalContextModelSelections =
currentSelectedModels?.[profileId] ?? {};
let fellBack = false;
// chat and summarize not implemented yet
// default chat model is stored in GUI still
const roles: ModelRole[] = [
"autocomplete",
"apply",
"edit",
"embed",
"rerank",
];
for (const role of roles) {
let newModel: ILLM | null = null;
const currentSelection = currentForProfile[role] ?? null;
if (currentSelection) {
const match = continueConfig.modelsByRole[role].find(
(m) => m.title === currentSelection,
);
if (match) {
newModel = match;
}
}
if (!newModel && continueConfig.modelsByRole[role].length > 0) {
newModel = continueConfig.modelsByRole[role][0];
}
if (!(currentSelection === (newModel?.title ?? null))) {
fellBack = true;
}
configCopy.selectedModelByRole[role] = newModel;
}
// In the case shared config wasn't respected,
// Rewrite the shared config
if (fellBack) {
globalContext.update("selectedModelsByProfileId", {
...currentSelectedModels,
[profileId]: Object.fromEntries(
Object.entries(configCopy.selectedModelByRole).map(([key, value]) => [
key,
value?.title ?? null,
]),
),
});
}
return configCopy;
}

157
core/config/sharedConfig.ts Normal file
View file

@ -0,0 +1,157 @@
import z from "zod";
import {
BrowserSerializedContinueConfig,
Config,
ContinueConfig,
SerializedContinueConfig,
} from "..";
export const sharedConfigSchema = z
.object({
// boolean fields in config.json
allowAnonymousTelemetry: z.boolean(),
disableIndexing: z.boolean(),
disableSessionTitles: z.boolean(),
// `experimental` in `ContinueConfig`
useChromiumForDocsCrawling: z.boolean(),
readResponseTTS: z.boolean(),
promptPath: z.string(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
codeBlockToolbarPosition: z.enum(["top", "bottom"]),
fontSize: z.number(),
codeWrap: z.boolean(),
displayRawMarkdown: z.boolean(),
showChatScrollbar: z.boolean(),
// `tabAutocompleteOptions` in `ContinueConfig`
useAutocompleteCache: z.boolean(),
useAutocompleteMultilineCompletions: z.enum(["always", "never", "auto"]),
disableAutocompleteInFiles: z.array(z.string()),
})
.partial();
export type SharedConfigSchema = z.infer<typeof sharedConfigSchema>;
// For security in case of damaged config file, try to salvage any security-related values
export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema {
const salvagedConfig: SharedConfigSchema = {};
if ("allowAnonymousTelemetry" in sharedConfig) {
const val = z.boolean().safeParse(sharedConfig.allowAnonymousTelemetry);
if (val.success) {
salvagedConfig.allowAnonymousTelemetry = val.data;
}
}
if ("disableIndexing" in sharedConfig) {
const val = z.boolean().safeParse(sharedConfig.disableIndexing);
if (val.success) {
salvagedConfig.disableIndexing = val.data;
}
}
if ("disableSessionTitles" in sharedConfig) {
const val = z.boolean().safeParse(sharedConfig.disableSessionTitles);
if (val.success) {
salvagedConfig.disableSessionTitles = val.data;
}
}
if ("disableAutocompleteInFiles" in sharedConfig) {
const val = sharedConfigSchema.shape.disableAutocompleteInFiles.safeParse(
sharedConfig.disableAutocompleteInFiles,
);
if (val.success) {
salvagedConfig.disableAutocompleteInFiles = val.data;
}
}
return salvagedConfig;
}
// Apply shared config to all forms of config
// - SerializedContinueConfig (config.json)
// - Config ("intermediate") - passed to config.ts
// - ContinueConfig
// - BrowserSerializedContinueConfig (final converted to be passed to GUI)
// This modify function is split into two steps
// - rectifySharedModelsFromSharedConfig - includes boolean flags like allowAnonymousTelemetry which
// must be added BEFORE config.ts and remote server config apply for JSON
// for security reasons
// - setSharedModelsFromSharedConfig - exists because of selectedModelsByRole
// Which don't exist on SerializedContinueConfig/Config types, so must be added after the fact
export function modifyAnyConfigWithSharedConfig<
T extends
| ContinueConfig
| BrowserSerializedContinueConfig
| Config
| SerializedContinueConfig,
>(continueConfig: T, sharedConfig: SharedConfigSchema): T {
const configCopy = { ...continueConfig };
configCopy.tabAutocompleteOptions = {
...configCopy.tabAutocompleteOptions,
};
if (sharedConfig.useAutocompleteCache !== undefined) {
configCopy.tabAutocompleteOptions.useCache =
sharedConfig.useAutocompleteCache;
}
if (sharedConfig.useAutocompleteMultilineCompletions !== undefined) {
configCopy.tabAutocompleteOptions.multilineCompletions =
sharedConfig.useAutocompleteMultilineCompletions;
}
if (sharedConfig.disableAutocompleteInFiles !== undefined) {
configCopy.tabAutocompleteOptions.disableInFiles =
sharedConfig.disableAutocompleteInFiles;
}
configCopy.ui = {
...configCopy.ui,
};
if (sharedConfig.codeBlockToolbarPosition !== undefined) {
configCopy.ui.codeBlockToolbarPosition =
sharedConfig.codeBlockToolbarPosition;
}
if (sharedConfig.fontSize !== undefined) {
configCopy.ui.fontSize = sharedConfig.fontSize;
}
if (sharedConfig.codeWrap !== undefined) {
configCopy.ui.codeWrap = sharedConfig.codeWrap;
}
if (sharedConfig.displayRawMarkdown !== undefined) {
configCopy.ui.displayRawMarkdown = sharedConfig.displayRawMarkdown;
}
if (sharedConfig.showChatScrollbar !== undefined) {
configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar;
}
if (sharedConfig.allowAnonymousTelemetry !== undefined) {
configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
}
if (sharedConfig.disableIndexing !== undefined) {
configCopy.disableIndexing = sharedConfig.disableIndexing;
}
if (sharedConfig.disableSessionTitles !== undefined) {
configCopy.disableSessionTitles = sharedConfig.disableSessionTitles;
}
if (sharedConfig.showSessionTabs !== undefined) {
configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs;
}
configCopy.experimental = {
...configCopy.experimental,
};
if (sharedConfig.promptPath !== undefined) {
configCopy.experimental.promptPath = sharedConfig.promptPath;
}
if (sharedConfig.useChromiumForDocsCrawling !== undefined) {
configCopy.experimental.useChromiumForDocsCrawling =
sharedConfig.useChromiumForDocsCrawling;
}
if (sharedConfig.readResponseTTS !== undefined) {
configCopy.experimental.readResponseTTS = sharedConfig.readResponseTTS;
}
return configCopy;
}

View file

@ -220,18 +220,10 @@ declare global {
export interface SiteIndexingConfig {
title: string;
startUrl: string;
rootUrl?: string;
maxDepth?: number;
faviconUrl?: string;
}
export interface SiteIndexingConfig {
startUrl: string;
rootUrl?: string;
title: string;
maxDepth?: number;
}
export interface IContextProvider {
get description(): ContextProviderDescription;
@ -580,7 +572,6 @@ declare global {
userToken: string;
enableControlServerBeta: boolean;
pauseCodebaseIndexOnStart: boolean;
enableDebugLogs: boolean;
}
export interface IDE {
@ -910,7 +901,6 @@ declare global {
export interface TabAutocompleteOptions {
disable: boolean;
useFileSuffix: boolean;
maxPromptTokens: number;
debounceDelay: number;
maxSuffixPercentage: number;
@ -955,7 +945,6 @@ declare global {
fontSize?: number;
displayRawMarkdown?: boolean;
showChatScrollbar?: boolean;
getChatTitles?: boolean;
codeWrap?: boolean;
}
@ -967,7 +956,7 @@ declare global {
fixGrammar?: string;
}
interface ModelRoles {
interface ExperimentalModelRoles {
inlineEdit?: string;
applyCodeBlock?: string;
repoMapFileSelection?: string;
@ -1035,7 +1024,7 @@ declare global {
interface ExperimentalConfig {
contextMenuPrompts?: ContextMenuConfig;
modelRoles?: ModelRoles;
modelRoles?: ExperimentalModelRoles;
defaultContext?: DefaultContextProvider[];
promptPath?: string;

View file

@ -1,4 +1,4 @@
import { execSync } from "child_process";
import fs from "fs";
import os from "os";
import {
@ -7,11 +7,13 @@ import {
IDE,
ILLM,
ModelDescription,
ModelRoles,
ExperimentalModelRoles,
} from "../";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigJson } from "../util/paths";
import { ConfigHandler } from "./ConfigHandler";
function stringify(obj: any, indentation?: number): string {
return JSON.stringify(
obj,
@ -22,19 +24,30 @@ function stringify(obj: any, indentation?: number): string {
);
}
export function addContextProvider(provider: ContextProviderWithParams) {
export function addContextProvider(provider: ContextProviderWithParams, configHandler?: ConfigHandler) {
let isAdded = false;
editConfigJson((config) => {
if (!config.contextProviders) {
config.contextProviders = [provider];
} else {
config.contextProviders = [];
}
if (!config.contextProviders.some((p) => p.name === provider.name)) {
config.contextProviders.push(provider);
isAdded = true;
}
return config;
});
if (isAdded && configHandler) {
void configHandler.reloadConfig();
}
}
export function addModel(model: ModelDescription, role?: keyof ModelRoles) {
export function addModel(
model: ModelDescription,
role?: keyof ExperimentalModelRoles,
) {
editConfigJson((config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
return config;
@ -85,7 +98,7 @@ export function deleteModel(title: string) {
});
}
export function getModelByRole<T extends keyof ModelRoles>(
export function getModelByRole<T extends keyof ExperimentalModelRoles>(
config: ContinueConfig,
role: T,
): ILLM | undefined {
@ -108,11 +121,13 @@ export function getModelByRole<T extends keyof ModelRoles>(
*
* See here for details: https://github.com/continuedev/continue/issues/940
*/
export function isSupportedLanceDbCpuTarget(ide: IDE) {
export function isSupportedLanceDbCpuTargetForLinux(ide?: IDE) {
const CPU_FEATURES_TO_CHECK = ["avx2", "fma"] as const;
const globalContext = new GlobalContext();
const globalContextVal = globalContext.get("isSupportedLanceDbCpuTarget");
const globalContextVal = globalContext.get(
"isSupportedLanceDbCpuTargetForLinux",
);
// If we've already checked the CPU target, return the cached value
if (globalContextVal !== undefined) {
@ -120,51 +135,35 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) {
}
const arch = os.arch();
const platform = os.platform();
// This check only applies to x64
//https://github.com/lancedb/lance/issues/2195#issuecomment-2057841311
if (arch !== "x64") {
globalContext.update("isSupportedLanceDbCpuTarget", true);
globalContext.update("isSupportedLanceDbCpuTargetForLinux", true);
return true;
}
try {
const cpuFlags = (() => {
switch (platform) {
case "darwin":
return execSync("sysctl -n machdep.cpu.features")
.toString()
.toLowerCase();
case "linux":
return execSync("cat /proc/cpuinfo").toString().toLowerCase();
case "win32":
return execSync("wmic cpu get caption /format:list")
.toString()
.toLowerCase();
default:
return "";
}
})();
const cpuFlags = fs.readFileSync("/proc/cpuinfo", "utf-8").toLowerCase();
const isSupportedLanceDbCpuTarget = cpuFlags
const isSupportedLanceDbCpuTargetForLinux = cpuFlags
? CPU_FEATURES_TO_CHECK.every((feature) => cpuFlags.includes(feature))
: true;
// If it's not a supported CPU target, and it's the first time we are checking,
// show a toast to inform the user that we are going to disable indexing.
if (!isSupportedLanceDbCpuTarget) {
if (!isSupportedLanceDbCpuTargetForLinux && ide) {
// We offload our async toast to `showUnsupportedCpuToast` to prevent making
// our config loading async upstream of `isSupportedLanceDbCpuTarget`
// our config loading async upstream of `isSupportedLanceDbCpuTargetForLinux`
void showUnsupportedCpuToast(ide);
}
globalContext.update(
"isSupportedLanceDbCpuTarget",
isSupportedLanceDbCpuTarget,
"isSupportedLanceDbCpuTargetForLinux",
isSupportedLanceDbCpuTargetForLinux,
);
return isSupportedLanceDbCpuTarget;
return isSupportedLanceDbCpuTargetForLinux;
} catch (error) {
// If we can't determine CPU features, default to true
return true;
@ -174,11 +173,13 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) {
async function showUnsupportedCpuToast(ide: IDE) {
const shouldOpenLink = await ide.showToast(
"warning",
"Codebase indexing is disabled due to CPU incompatibility",
"Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)",
"Learn more",
);
if (shouldOpenLink) {
void ide.openUrl("https://github.com/continuedev/continue/pull/3551");
void ide.openUrl(
"https://docs.continue.dev/troubleshooting#i-received-a-codebase-indexing-disabled---your-linux-system-lacks-required-cpu-features-avx2-fma-notification",
);
}
}

View file

@ -1,11 +1,7 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import { ModelDescription, SerializedContinueConfig } from "../";
import { Telemetry } from "../util/posthog";
export interface ConfigValidationError {
fatal: boolean;
message: string;
}
/**
* Validates a SerializedContinueConfig object to ensure all properties are correctly formed.
* @param config The configuration object to validate.

View file

@ -1,13 +1,13 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas";
import { ModelConfig, AssistantUnrolled } from "@continuedev/config-yaml";
import { SerializedContinueConfig } from "../..";
export function convertConfigJsonToConfigYaml(
configJson: SerializedContinueConfig,
): ConfigYaml {
): AssistantUnrolled {
return {
name: "Local Config",
version: "1.0.0",
models: [
...configJson.models.map(
(model): ModelConfig => ({
@ -15,16 +15,17 @@ export function convertConfigJsonToConfigYaml(
name: model.title,
// defaultCompletionOptions: model.completionOptions,
provider: model.provider,
roles: ["chat"],
roles: ["chat", "edit", "apply", "summarize"],
}),
),
// ... tabAutocompleteModels
// TODO
// tabAutocompleteModels
// embeddingsModels
// rerankModels
],
context: configJson.contextProviders?.map((provider) => ({
uses: provider.name,
with: provider.params,
provider: provider.name,
params: provider.params,
})),
};
}

View file

@ -1,14 +1,16 @@
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas";
import { AssistantUnrolled } from "@continuedev/config-yaml";
// TODO
export const defaultConfigYaml: ConfigYaml = {
export const defaultConfigYaml: AssistantUnrolled = {
models: [],
context: [],
name: "Local Config",
version: "1.0.0",
};
export const defaultConfigYamlJetBrains: ConfigYaml = {
export const defaultConfigYamlJetBrains: AssistantUnrolled = {
models: [],
context: [],
name: "Local Config",
version: "1.0.0",
};

View file

@ -1,95 +1,77 @@
import fs from "node:fs";
import path from "path";
import {
extendConfig,
fillTemplateVariables,
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
ModelRole,
parseAssistantUnrolled,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas";
import { ValidationLevel } from "@continuedev/config-yaml/dist/validation";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as YAML from "yaml";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
SlashCommand,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
import { AllRerankers } from "../../context/allRerankers";
import { MCPManagerSingleton } from "../../context/mcp";
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider";
import { ControlPlaneClient } from "../../control-plane/client";
import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders";
import FreeTrial from "../../llm/llms/FreeTrial";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import {
getConfigYamlPath,
getContinueDotEnv,
readAllGlobalPromptFiles,
} from "../../util/paths";
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { allTools } from "../../tools";
import { GlobalContext } from "../../util/GlobalContext";
import { getConfigYamlPath } from "../../util/paths";
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
import { ConfigValidationError } from "../validation.js";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { llmsFromModelConfig } from "./models";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
export interface ConfigResult<T> {
config: T | undefined;
errors: ConfigValidationError[] | undefined;
configLoadInterrupted: boolean;
}
function renderTemplateVars(configYaml: string): string {
const data: Record<string, string> = {};
// env.*
const envVars = getContinueDotEnv();
Object.entries(envVars).forEach(([key, value]) => {
data[`env.${key}`] = value;
});
// secrets.* not filled in
return fillTemplateVariables(configYaml, data);
}
function loadConfigYaml(
async function loadConfigYaml(
workspaceConfigs: string[],
ideSettings: IdeSettings,
ideType: IdeType,
rawYaml: string,
): ConfigResult<ConfigYaml> {
const renderedYaml = renderTemplateVars(rawYaml);
let config = YAML.parse(renderedYaml) as ConfigYaml;
overrideConfigYaml: AssistantUnrolled | undefined,
ide: IDE,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<AssistantUnrolled>> {
// const ideSettings = await ide.getIdeSettings();
let config =
overrideConfigYaml ??
// (ideSettings.continueTestEnvironment === "production"
// ? await clientRenderHelper(rawYaml, ide, controlPlaneClient)
// :
parseAssistantUnrolled(rawYaml);
// );
const errors = validateConfigYaml(config);
if (errors?.some((error) => error.level === ValidationLevel.Error)) {
if (errors?.some((error) => error.fatal)) {
return {
errors: errors.map((error) => ({
message: error.message,
fatal: error.level === ValidationLevel.Error,
})),
errors,
config: undefined,
configLoadInterrupted: true,
};
}
for (const workspaceConfig of workspaceConfigs) {
const rendered = renderTemplateVars(workspaceConfig);
config = extendConfig(config, YAML.parse(rendered) as ConfigYaml);
}
// Set defaults if undefined (this lets us keep config.json uncluttered for new users)
return {
config,
errors: errors.map((error) => ({
message: error.message,
fatal: error.level === ValidationLevel.Error,
fatal: error.fatal,
})),
configLoadInterrupted: false,
};
@ -113,52 +95,159 @@ async function slashCommandsFromV1PromptFiles(
}
async function configYamlToContinueConfig(
config: ConfigYaml,
config: AssistantUnrolled,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
allowFreeTrial: boolean = true,
): Promise<ContinueConfig> {
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
const continueConfig: ContinueConfig = {
slashCommands: await slashCommandsFromV1PromptFiles(ide),
slashCommands: [
...(await slashCommandsFromV1PromptFiles(ide)),
...(config.prompts?.map(slashFromCustomCommand) ?? []),
],
models: [],
tabAutocompleteModels: [],
tools: [],
embeddingsProvider: new TransformersJsEmbeddingsProvider(),
tools: allTools,
systemMessage: config.rules?.join("\n"),
experimental: {
modelContextProtocolServers: [],
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
transport: {
type: "stdio",
command: mcpServer.command,
args: mcpServer.args ?? [],
env: mcpServer.env,
},
})),
},
docs: config.docs?.map((doc) => ({
title: doc.name,
startUrl: doc.startUrl,
rootUrl: doc.rootUrl,
faviconUrl: doc.faviconUrl,
})),
contextProviders: [],
modelsByRole: {
chat: [],
edit: [],
apply: [],
embed: [],
autocomplete: [],
rerank: [],
summarize: [],
},
selectedModelByRole: {
chat: null, // not currently used - defaultModel on GUI is used
edit: null, // not currently used
apply: null,
embed: null,
autocomplete: null,
rerank: null,
summarize: null,
},
data: config.data,
};
// Models
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
if (
["chat", "summarize", "apply", "edit"].some((role: any) =>
model.roles?.includes(role),
)
) {
// Main model array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
);
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
//
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
continueConfig.models.push(...llms);
} else if (model.roles?.includes("autocomplete")) {
// Autocomplete models array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
);
continueConfig.tabAutocompleteModels?.push(...llms);
}
if (model.roles?.includes("chat")) {
continueConfig.modelsByRole.chat.push(...llms);
}
if (model.roles?.includes("summarize")) {
continueConfig.modelsByRole.summarize.push(...llms);
}
if (model.roles?.includes("apply")) {
continueConfig.modelsByRole.apply.push(...llms);
}
if (model.roles?.includes("edit")) {
continueConfig.modelsByRole.edit.push(...llms);
}
if (model.roles?.includes("autocomplete")) {
continueConfig.modelsByRole.autocomplete.push(...llms);
}
if (model.roles?.includes("embed")) {
const { provider, ...options } = model;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
continueConfig.modelsByRole.embed.push(new embeddingsProviderClass());
} else {
continueConfig.modelsByRole.embed.push(
new embeddingsProviderClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
),
);
}
} else {
errors.push({
fatal: false,
message: `Unsupported embeddings model provider found: ${provider}`,
});
}
}
if (model.roles?.includes("rerank")) {
const { provider, ...options } = model;
const rerankerClass = AllRerankers[provider];
if (rerankerClass) {
continueConfig.modelsByRole.rerank.push(
new rerankerClass(options, (url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
),
);
} else {
errors.push({
fatal: false,
message: `Unsupported reranking model provider found: ${provider}`,
});
}
}
}
// Add transformers js to the embed models in vs code if not already added
if (
ideInfo.ideType === "vscode" &&
!continueConfig.modelsByRole.embed.find(
(m) => m.providerName === "transformers.js",
)
) {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
}
if (allowFreeTrial) {
@ -179,120 +268,116 @@ async function configYamlToContinueConfig(
);
}
// TODO: Split into model roles.
// Context providers
const codebaseContextParams: IContextProvider[] =
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
{};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
new PromptFilesContextProvider({}),
];
// Context
continueConfig.contextProviders = config.context
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
({ description: { title } }) => title,
);
continueConfig.contextProviders = (config.context
?.map((context) => {
const cls = contextProviderClassFromName(context.uses) as any;
const cls = contextProviderClassFromName(context.provider) as any;
if (!cls) {
console.warn(`Unknown context provider ${context.uses}`);
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
console.warn(`Unknown context provider ${context.provider}`);
}
return undefined;
}
const instance: IContextProvider = new cls(context.with ?? {});
const instance: IContextProvider = new cls(context.params ?? {});
return instance;
})
.filter((p) => !!p) as IContextProvider[];
.filter((p) => !!p) ?? []) as IContextProvider[];
continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
// Embeddings Provider
const embedConfig = config.models?.find((model) =>
model.roles?.includes("embed"),
);
if (embedConfig) {
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
continueConfig.embeddingsProvider = new embeddingsProviderClass();
} else {
continueConfig.embeddingsProvider = new embeddingsProviderClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
);
}
}
}
// Reranker
const rerankConfig = config.models?.find((model) =>
model.roles?.includes("rerank"),
);
if (rerankConfig) {
const { provider, ...options } = rerankConfig;
const rerankerClass = AllRerankers[provider];
if (rerankerClass) {
continueConfig.reranker = new rerankerClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
);
}
if (
continueConfig.docs?.length &&
!continueConfig.contextProviders?.some(
(cp) => cp.description.title === "docs",
)
) {
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
config.mcpServers?.forEach(async (server) => {
const mcpId = server.name;
const mcpConnection = mcpManager.createConnection(mcpId, {
transport: {
type: "stdio",
args: [],
...server,
},
});
if (!mcpConnection) {
return;
}
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
2000,
);
try {
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
);
} catch (e: any) {
if (e.name !== "AbortError") {
throw e;
await Promise.all(
config.mcpServers?.map(async (server) => {
const mcpId = server.name;
const mcpConnection = mcpManager.createConnection(mcpId, {
transport: {
type: "stdio",
args: [],
...server,
},
});
if (!mcpConnection) {
return;
}
}
clearTimeout(mcpConnectionTimeout);
});
return continueConfig;
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
5000,
);
try {
const mcpError = await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
server.name,
server.faviconUrl,
);
if (mcpError) {
errors.push(mcpError);
}
} catch (e: any) {
errors.push({
fatal: false,
message: `Failed to load MCP server: ${e.message}`,
});
if (e.name !== "AbortError") {
throw e;
}
}
clearTimeout(mcpConnectionTimeout);
}) ?? [],
);
return { config: continueConfig, errors };
}
export async function loadContinueConfigFromYaml(
ide: IDE,
workspaceConfigs: string[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
overrideConfigYaml: string | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<ContinueConfig>> {
const configYamlPath = getConfigYamlPath(ideType);
const rawYaml = fs.readFileSync(configYamlPath, "utf-8");
const rawYaml =
overrideConfigYaml === undefined
? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8")
: "";
const configYamlResult = await loadConfigYaml(
workspaceConfigs,
ideSettings,
ideType,
overrideConfigYaml ?? rawYaml,
rawYaml,
overrideConfigYaml,
ide,
controlPlaneClient,
);
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
@ -303,13 +388,15 @@ export async function loadContinueConfigFromYaml(
};
}
const continueConfig = await configYamlToContinueConfig(
const { config: continueConfig, errors } = await configYamlToContinueConfig(
configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
platformConfigMetadata,
);
const systemPromptDotFile = await getSystemPromptDotFile(ide);
@ -321,11 +408,20 @@ export async function loadContinueConfigFromYaml(
}
}
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyAnyConfigWithSharedConfig(
continueConfig,
sharedConfig,
);
if (withShared.allowAnonymousTelemetry === undefined) {
withShared.allowAnonymousTelemetry = true;
}
return {
config: continueConfig,
errors: configYamlResult.errors,
config: withShared,
errors: [...(configYamlResult.errors ?? []), ...errors],
configLoadInterrupted: false,
};
}
export { type BrowserSerializedContinueConfig };

View file

@ -3,16 +3,33 @@ import { ModelConfig } from "@continuedev/config-yaml";
import { IDE, IdeSettings, LLMOptions } from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
const AUTODETECT = "AUTODETECT";
function getModelClass(
model: ModelConfig,
): (typeof LLMClasses)[number] | undefined {
return LLMClasses.find((llm) => llm.providerName === model.provider);
}
function getContinueProxyModelName(
ownerSlug: string,
packageSlug: string,
model: ModelConfig,
): string {
return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
}
async function modelConfigToBaseLLM(
model: ModelConfig,
uniqueId: string,
ideSettings: IdeSettings,
writeLog: (log: string) => Promise<void>,
platformConfigMetadata: PlatformConfigMetadata | undefined,
systemMessage: string | undefined,
): Promise<BaseLLM | undefined> {
const cls = LLMClasses.find((llm) => llm.providerName === model.provider);
const cls = getModelClass(model);
if (!cls) {
return undefined;
@ -30,8 +47,59 @@ async function modelConfigToBaseLLM(
writeLog,
uniqueId,
title: model.name,
systemMessage,
promptTemplates: model.promptTemplates,
};
if (model.embedOptions?.maxBatchSize) {
options.maxEmbeddingBatchSize = model.embedOptions.maxBatchSize;
}
if (model.embedOptions?.maxChunkSize) {
options.maxEmbeddingChunkSize = model.embedOptions.maxChunkSize;
}
// These are params that are at model config level in JSON
// But we decided to move to nested `env` in YAML
// Since types vary and we don't want to blindly spread env for now,
// Each one is handled individually here
const env = model.env ?? {};
if (
"useLegacyCompletionsEndpoint" in env &&
typeof env.useLegacyCompletionsEndpoint === "boolean"
) {
options.useLegacyCompletionsEndpoint = env.useLegacyCompletionsEndpoint;
}
if ("apiType" in env && typeof env.apiType === "string") {
options.apiType = env.apiType;
}
if ("apiVersion" in env && typeof env.apiVersion === "string") {
options.apiVersion = env.apiVersion;
}
if ("deployment" in env && typeof env.deployment === "string") {
options.deployment = env.deployment;
}
if ("deploymentId" in env && typeof env.deploymentId === "string") {
options.deploymentId = env.deploymentId;
}
if ("projectId" in env && typeof env.projectId === "string") {
options.projectId = env.projectId;
}
if ("region" in env && typeof env.region === "string") {
options.region = env.region;
}
if ("profile" in env && typeof env.profile === "string") {
options.profile = env.profile;
}
if ("modelArn" in env && typeof env.modelArn === "string") {
options.modelArn = env.modelArn;
}
if ("aiGatewaySlug" in env && typeof env.aiGatewaySlug === "string") {
options.aiGatewaySlug = env.aiGatewaySlug;
}
if ("accountId" in env && typeof env.accountId === "string") {
options.accountId = env.accountId;
}
const llm = new cls(options);
return llm;
}
@ -43,6 +111,8 @@ async function autodetectModels(
uniqueId: string,
ideSettings: IdeSettings,
writeLog: (log: string) => Promise<void>,
platformConfigMetadata: PlatformConfigMetadata | undefined,
systemMessage: string | undefined,
): Promise<BaseLLM[]> {
try {
const modelNames = await llm.listModels();
@ -57,11 +127,13 @@ async function autodetectModels(
{
...model,
model: modelName,
name: `${llm.title} - ${modelName}`,
name: modelName,
},
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
systemMessage,
);
}),
);
@ -78,12 +150,16 @@ export async function llmsFromModelConfig(
uniqueId: string,
ideSettings: IdeSettings,
writeLog: (log: string) => Promise<void>,
platformConfigMetadata: PlatformConfigMetadata | undefined,
systemMessage: string | undefined,
): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM(
model,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
systemMessage,
);
if (!baseLlm) {
return [];
@ -97,6 +173,8 @@ export async function llmsFromModelConfig(
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
systemMessage,
);
return models;
} else {

View file

@ -4,9 +4,9 @@ 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 { ConfigValidationError } from "@continuedev/config-yaml";
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { ConfigValidationError } from "../../config/validation";
import { encodeMCPToolUri } from "../../tools/callTool";
import MCPContextProvider from "../providers/MCPContextProvider";
@ -69,10 +69,14 @@ class MCPConnection {
private constructTransport(options: MCPOptions): Transport {
switch (options.transport.type) {
case "stdio":
const env: Record<string, string> = options.transport.env || {};
if (process.env.PATH !== undefined) {
env.PATH = process.env.PATH;
}
return new StdioClientTransport({
command: options.transport.command,
args: options.transport.args,
env: options.transport.env,
env,
});
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
@ -117,6 +121,8 @@ class MCPConnection {
config: ContinueConfig,
mcpId: string,
signal: AbortSignal,
name: string,
faviconUrl: string | undefined,
): Promise<ConfigValidationError | undefined> {
try {
await Promise.race([
@ -148,6 +154,7 @@ class MCPConnection {
title: resource.name,
description: resource.description,
id: resource.uri,
icon: faviconUrl,
}));
if (!config.contextProviders) {
@ -157,6 +164,7 @@ class MCPConnection {
config.contextProviders.push(
new MCPContextProvider({
submenuItems,
mcpId,
}),
);
}
@ -165,19 +173,20 @@ class MCPConnection {
if (capabilities?.tools) {
const { tools } = await this.client.listTools({}, { signal });
const continueTools: Tool[] = tools.map((tool: any) => ({
displayTitle: tool.name,
displayTitle: name + " " + tool.name,
function: {
description: tool.description,
name: tool.name,
parameters: tool.inputSchema,
},
faviconUrl,
readonly: false,
type: "function",
wouldLikeTo: `use the ${tool.name} tool`,
wouldLikeTo: `use the ${name} ${tool.name} tool`,
uri: encodeMCPToolUri(mcpId, tool.name),
}));
config.tools = [...config.tools, ...continueTools];
config.tools = [...continueTools, ...config.tools];
}
// Prompts <—> Slash commands

View file

@ -24,8 +24,12 @@ class CodeContextProvider extends BaseContextProvider {
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Assume the query is the id as returned by loadSubmenuItems
const workspaceDirs = await extras.ide.getWorkspaceDirs();
return [
await CodeSnippetsCodebaseIndex.getForId(Number.parseInt(query, 10)),
await CodeSnippetsCodebaseIndex.getForId(
Number.parseInt(query, 10),
workspaceDirs,
),
];
}

View file

@ -1,4 +1,4 @@
import { controlPlaneEnv } from "../../control-plane/env.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import {
ContextItem,
ContextProviderDescription,
@ -35,11 +35,9 @@ class ContinueProxyContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const env = await getControlPlaneEnv(args.ide.getIdeSettings());
const response = await args.fetch(
new URL(
`/proxy/context/${this.options.id}/list`,
controlPlaneEnv.CONTROL_PLANE_URL,
),
new URL(`/proxy/context/${this.options.id}/list`, env.CONTROL_PLANE_URL),
{
method: "GET",
headers: {
@ -56,10 +54,11 @@ class ContinueProxyContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
const response = await extras.fetch(
new URL(
`/proxy/context/${this.options.id}/retrieve`,
controlPlaneEnv.CONTROL_PLANE_URL,
env.CONTROL_PLANE_URL,
),
{
method: "POST",

View file

@ -4,7 +4,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../";
import { getUriPathBasename } from "../../util/uri";
import { getUriDescription } from "../../util/uri";
class CurrentFileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -23,12 +23,27 @@ class CurrentFileContextProvider extends BaseContextProvider {
if (!currentFile) {
return [];
}
const baseName = getUriPathBasename(currentFile.path);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
currentFile.path,
await extras.ide.getWorkspaceDirs(),
);
let prefix = "This is the currently open file:";
let name = baseName;
// This allows frontend to retrieve when using alt + enter or default context with slightly different copy
if (query === "non-mention-usage") {
prefix =
"The following file is currently open. Don't reference it if it's not relevant to the user's message:";
name = "Active file: " + baseName;
}
return [
{
description: currentFile.path,
content: `This is the currently open file:\n\n\`\`\`${baseName}\n${currentFile.contents}\n\`\`\``,
name: baseName,
description: last2Parts,
content: `${prefix}\n\n\`\`\`${relativePathOrBasename}\n${currentFile.contents}\n\`\`\``,
name,
uri: {
type: "file",
value: currentFile.path,

View file

@ -20,10 +20,16 @@ class DocsContextProvider extends BaseContextProvider {
displayTitle: "Docs",
description: "Type to search docs",
type: "submenu",
// Todo: consider a different renderInline so that when multiple docs are referenced in one message,
// Or the doc has an odd name unrelated to the content
// The name of the doc itself doesn't skew the embedding results
renderInlineAs: "",
};
constructor(options: any) {
super(options);
const docsService = DocsService.getSingleton();
docsService?.setGithubToken(this.options?.githubToken);
}
private async _rerankChunks(
@ -80,6 +86,7 @@ class DocsContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const nRetrieve = this.options?.nRetrieve ?? DocsContextProvider.nRetrieve;
const useReranking = this.options?.useReranking ?? true;
// Get docs service
@ -94,7 +101,7 @@ class DocsContextProvider extends BaseContextProvider {
let chunks = await docsService.retrieveChunksFromQuery(
extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
query,
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
nRetrieve,
);
if (!chunks?.length) {
return [];
@ -173,6 +180,10 @@ class DocsContextProvider extends BaseContextProvider {
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
// Skip if overridden in config
if (docs.find((d) => d.startUrl === startUrl)) {
continue;
}
submenuItemsMap.set(startUrl, {
title,
id: startUrl,

View file

@ -10,6 +10,7 @@ import { walkDirs } from "../../indexing/walkDir";
import {
getUriPathBasename,
getShortestUniqueRelativeUriPaths,
getUriDescription,
} from "../../util/uri";
const MAX_SUBMENU_ITEMS = 10_000;
@ -27,16 +28,22 @@ class FileContextProvider extends BaseContextProvider {
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Assume the query is a filepath
query = query.trim();
const content = await extras.ide.readFile(query);
const fileUri = query.trim();
const content = await extras.ide.readFile(fileUri);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
fileUri,
await extras.ide.getWorkspaceDirs(),
);
return [
{
name: query.split(/[\\/]/).pop() ?? query,
description: query,
content: `\`\`\`${query}\n${content}\n\`\`\``,
name: baseName,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``,
uri: {
type: "file",
value: query,
value: fileUri,
},
},
];

View file

@ -94,7 +94,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
});
}
private async getRemoteBranchName(
private async getRemoteBranchInfo(
extras: ContextProviderExtras,
): Promise<RemoteBranchInfo> {
const subprocess = await getSubprocess(extras);
@ -121,9 +121,16 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
const urlMatches = /:(?<project>.*).git/.exec(remoteUrl);
let urlMatches: RegExpExecArray | null;
if (/https?.*/.test(remoteUrl)) {
const pathname = new URL(remoteUrl).pathname;
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
} else {
// ssh
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
}
const project = urlMatches?.groups?.project ?? null;
const project = urlMatches?.groups?.projectPath ?? null;
return {
branch: remoteBranch,
@ -135,7 +142,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const { branch, project } = await this.getRemoteBranchName(extras);
const { branch, project } = await this.getRemoteBranchInfo(extras);
const api = await this.getApi();

View file

@ -9,6 +9,7 @@ import {
import { MCPManagerSingleton } from "../mcp";
interface MCPContextProviderOptions {
mcpId: string;
submenuItems: ContextSubmenuItem[];
}
@ -74,10 +75,10 @@ class MCPContextProvider extends BaseContextProvider {
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
return (this.options as MCPContextProviderOptions).submenuItems.map(
(item, index) => ({
(item) => ({
...item,
id: JSON.stringify({
mcpId: String(index),
mcpId: (this.options as MCPContextProviderOptions).mcpId,
uri: item.id,
}),
}),

View file

@ -3,7 +3,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { findUriInDirs, getUriPathBasename } from "../../util/uri.js";
import { getUriDescription } from "../../util/uri.js";
import { BaseContextProvider } from "../index.js";
class OpenFilesContextProvider extends BaseContextProvider {
@ -24,14 +24,17 @@ class OpenFilesContextProvider extends BaseContextProvider {
? await ide.getPinnedFiles()
: await ide.getOpenFiles();
const workspaceDirs = await extras.ide.getWorkspaceDirs();
return await Promise.all(
openFiles.map(async (filepath: string) => {
const content = await ide.readFile(filepath);
const { relativePathOrBasename, last2Parts, baseName } =
getUriDescription(filepath, workspaceDirs);
return {
description: filepath,
content: `\`\`\`${
findUriInDirs(filepath, workspaceDirs).relativePathOrBasename
}\n${await ide.readFile(filepath)}\n\`\`\``,
name: getUriPathBasename(filepath),
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``,
name: baseName,
uri: {
type: "file",
value: filepath,

View file

@ -3,7 +3,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { getUriPathBasename } from "../../util/uri.js";
import { getUriDescription } from "../../util/uri.js";
import { BaseContextProvider } from "../index.js";
class ProblemsContextProvider extends BaseContextProvider {
@ -20,10 +20,14 @@ class ProblemsContextProvider extends BaseContextProvider {
): Promise<ContextItem[]> {
const ide = extras.ide;
const problems = await ide.getProblems();
const workspaceDirs = await ide.getWorkspaceDirs();
const items = await Promise.all(
problems.map(async (problem) => {
const fileName = getUriPathBasename(problem.filepath);
const { relativePathOrBasename, baseName } = getUriDescription(
problem.filepath,
workspaceDirs,
);
const content = await ide.readFile(problem.filepath);
const lines = content.split("\n");
const rangeContent = lines
@ -35,8 +39,8 @@ class ProblemsContextProvider extends BaseContextProvider {
return {
description: "Problems in current file",
content: `\`\`\`${fileName}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
name: `Warning in ${fileName}`,
content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
name: `Warning in ${baseName}`,
};
}),
);

View file

@ -7,7 +7,6 @@ import {
IContextProvider,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { ControlPlaneClient } from "../../control-plane/client";
import { TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
@ -31,8 +30,9 @@ async function getContextProviderExtras(
ide,
ideSettingsPromise,
async (text) => {},
new ControlPlaneClient(Promise.resolve(undefined)),
Promise.resolve(undefined),
);
await configHandler.initializedPromise;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not found");
@ -42,10 +42,10 @@ async function getContextProviderExtras(
fullInput,
ide,
config,
embeddingsProvider: config.embeddingsProvider,
embeddingsProvider: config.selectedModelByRole.embed,
fetch: fetch,
llm: config.models[0],
reranker: config.reranker,
reranker: config.selectedModelByRole.rerank,
selectedCode: [],
};
}

View file

@ -7,6 +7,8 @@ import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCod
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
const DEFAULT_CHUNK_SIZE = 384;
export interface RetrievalPipelineOptions {
llm: ILLM;
config: ContinueConfig;
@ -16,13 +18,13 @@ export interface RetrievalPipelineOptions {
nFinal: number;
tags: BranchAndDir[];
filterDirectory?: string;
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
}
export interface RetrievalPipelineRunArguments {
query: string;
tags: BranchAndDir[];
filterDirectory?: string;
includeEmbeddings: boolean;
}
export interface IRetrievalPipeline {
@ -31,12 +33,21 @@ export interface IRetrievalPipeline {
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private ftsIndex = new FullTextSearchCodebaseIndex();
private lanceDbIndex: LanceDbIndex;
private lanceDbIndex: LanceDbIndex | null = null;
constructor(protected readonly options: RetrievalPipelineOptions) {
this.lanceDbIndex = new LanceDbIndex(
options.config.embeddingsProvider,
(uri) => options.ide.readFile(uri),
void this.initLanceDb();
}
private async initLanceDb() {
const embedModel = this.options.config.selectedModelByRole.embed;
if (!embedModel) {
return;
}
this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) =>
this.options.ide.readFile(uri),
);
}
@ -60,6 +71,11 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
return trigrams;
}
private escapeFtsQueryString(query: string): string {
const escapedDoubleQuotes = query.replace(/"/g, '""');
return `"${escapedDoubleQuotes}"`;
}
protected async retrieveFts(
args: RetrievalPipelineRunArguments,
n: number,
@ -69,7 +85,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
return [];
}
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
const tokens = this.escapeFtsQueryString(tokensRaw);
return await this.ftsIndex.retrieve({
n,
@ -109,7 +126,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
filepath,
contents,
maxChunkSize:
this.options.config.embeddingsProvider.maxEmbeddingChunkSize,
this.options.config.selectedModelByRole.embed
?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE,
digest: filepath,
});
@ -125,6 +143,13 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
input: string,
n: number,
): Promise<Chunk[]> {
if (!this.lanceDbIndex) {
console.warn(
"LanceDB index not available, skipping embeddings retrieval",
);
return [];
}
return this.lanceDbIndex.retrieve(
input,
n,

View file

@ -9,7 +9,7 @@ import BaseRetrievalPipeline, {
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
const { input, nFinal, filterDirectory, includeEmbeddings } = this.options;
const { input, nFinal, filterDirectory, config } = this.options;
// We give 1/4 weight to recently edited files, 1/4 to full text search,
// and the remaining 1/2 to embeddings
@ -21,7 +21,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
const embeddingsChunks = includeEmbeddings
const embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];

View file

@ -12,13 +12,12 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
private async _retrieveInitial(
args: RetrievalPipelineRunArguments,
): Promise<Chunk[]> {
const { input, nRetrieve, filterDirectory, includeEmbeddings } =
this.options;
const { input, nRetrieve, filterDirectory, config } = this.options;
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(args, nRetrieve);
const embeddingsChunks = includeEmbeddings
const embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
const recentlyEditedFilesChunks =
@ -42,7 +41,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen
retrievalResults = retrievalResults.filter(
(chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]),
(chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir,
);
}
@ -53,17 +52,18 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
}
private async _rerank(input: string, chunks: Chunk[]): Promise<Chunk[]> {
if (!this.options.config.reranker) {
throw new Error("No reranker provided");
if (!this.options.config.selectedModelByRole.rerank) {
throw new Error("No reranker set up");
}
// remove empty chunks -- some APIs fail on that
chunks = chunks.filter((chunk) => chunk.content);
let scores: number[] = await this.options.config.reranker.rerank(
input,
chunks,
);
let scores: number[] =
await this.options.config.selectedModelByRole.rerank.rerank(
input,
chunks,
);
// Filter out low-scoring results
let results = chunks;

View file

@ -2,7 +2,6 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
import { getModelByRole } from "../../config/util";
import generateRepoMap from "../../util/generateRepoMap";
import { renderChatMessage } from "../../util/messageContent";
import { getUriPathBasename } from "../../util/uri";
const SUPPORTED_MODEL_TITLE_FAMILIES = [
"claude-3",
@ -16,7 +15,7 @@ function isSupportedModel(
config: ContinueConfig,
modelTitle?: string,
): boolean {
if (config.experimental?.modelRoles?.applyCodeBlock) {
if (config.experimental?.modelRoles?.repoMapFileSelection) {
return true;
}

View file

@ -1,6 +1,5 @@
import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { getUriPathBasename } from "../../util/uri";
import { getUriDescription } from "../../util/uri";
import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils";
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline";
@ -14,26 +13,16 @@ export async function retrieveContextItemsFromEmbeddings(
options: any | undefined,
filterDirectory: string | undefined,
): Promise<ContextItem[]> {
if (!extras.embeddingsProvider) {
return [];
}
// transformers.js not supported in JetBrains IDEs right now
const isJetBrainsAndTransformersJs =
extras.embeddingsProvider.providerName ===
TransformersJsEmbeddingsProvider.providerName &&
(await extras.ide.getIdeInfo()).ideType === "jetbrains";
if (isJetBrainsAndTransformersJs) {
void extras.ide.showToast(
"warning",
"Codebase retrieval is limited when `embeddingsProvider` is empty or set to `transformers.js` in JetBrains. " +
"You can use Ollama to set up local embeddings, use our 'free-trial', " +
"or configure your own. See here to learn more: " +
"https://docs.continue.dev/customize/model-types/embeddings",
);
}
// Currently you can use codebase without an embeddings provider and it will just skip the embeddings inputs
// if (!extras.embeddingsProvider) {
// void extras.ide.showToast(
// "warning",
// "Set up an embeddings model to use this feature. Visit the docs to learn more: " +
// "https://docs.continue.dev/customize/model-roles/embeddings",
// );
// return [];
// }
const includeEmbeddings = !!extras.config.selectedModelByRole.embed;
// Get tags to retrieve for
const workspaceDirs = await extras.ide.getWorkspaceDirs();
@ -78,7 +67,6 @@ export async function retrieveContextItemsFromEmbeddings(
input: extras.fullInput,
llm: extras.llm,
config: extras.config,
includeEmbeddings: !isJetBrainsAndTransformersJs,
};
const pipeline = new pipelineType(pipelineOptions);
@ -86,16 +74,17 @@ export async function retrieveContextItemsFromEmbeddings(
tags,
filterDirectory,
query: extras.fullInput,
includeEmbeddings,
});
if (results.length === 0) {
if (extras.config.disableIndexing) {
void extras.ide.showToast("warning", "No embeddings results found.");
void extras.ide.showToast("warning", "No results found.");
return [];
} else {
void extras.ide.showToast(
"warning",
"No embeddings results found. If you think this is an error, re-index your codebase.",
"No results found. If you think this is an error, re-index your codebase.",
);
// TODO - add "re-index" option to warning message which clears and reindexes codebase
}
@ -111,18 +100,17 @@ export async function retrieveContextItemsFromEmbeddings(
...results
.sort((a, b) => a.filepath.localeCompare(b.filepath))
.map((r) => {
const basename = getUriPathBasename(r.filepath);
const name = `${basename} (${r.startLine}-${r.endLine})`;
const description = `${r.filepath}`;
const { relativePathOrBasename, last2Parts, baseName } =
getUriDescription(r.filepath, workspaceDirs);
if (basename === "package.json") {
if (baseName === "package.json") {
console.warn("Retrieval pipeline: package.json detected");
}
return {
name,
description,
content: `\`\`\`${name}\n${r.content}\n\`\`\``,
name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``,
uri: {
type: "file" as const,
value: r.filepath,

View file

@ -22,7 +22,7 @@ export interface IContinueServerClient {
connected: boolean;
url: URL | undefined;
getUserToken(): string | undefined;
getConfig(): Promise<{ configJson: string; configJs: string }>;
getConfig(): Promise<{ configJson: string }>;
getFromIndexCache<T extends ArtifactType>(
keys: string[],
artifactId: T,

View file

@ -30,7 +30,7 @@ export class ContinueServerClient implements IContinueServerClient {
return this.url !== undefined && this.userToken !== undefined;
}
public async getConfig(): Promise<{ configJson: string; configJs: string }> {
public async getConfig(): Promise<{ configJson: string }> {
const userToken = await this.userToken;
const response = await fetch(new URL("sync", this.url).href, {
method: "GET",

View file

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

View file

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

View file

@ -1,14 +1,17 @@
import { v4 as uuidv4 } from "uuid";
import { IdeSettings } from "../..";
import { getControlPlaneEnv } from "../env";
const CLIENT_ID = "client_01J0FW6XN8N2XJAECF7NE0Y65J";
// const CLIENT_ID = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; // Staging
export async function getAuthUrlForTokenPage(): Promise<string> {
export async function getAuthUrlForTokenPage(
ideSettingsPromise: Promise<IdeSettings>,
useOnboarding: boolean,
): Promise<string> {
const env = await getControlPlaneEnv(ideSettingsPromise);
const url = new URL("https://api.workos.com/user_management/authorize");
const params = {
response_type: "code",
client_id: CLIENT_ID,
redirect_uri: "https://app.continue.dev/tokens/callback",
client_id: env.WORKOS_CLIENT_ID,
redirect_uri: `${env.APP_URL}tokens/${useOnboarding ? "onboarding-" : ""}callback`,
// redirect_uri: "http://localhost:3000/tokens/callback",
state: uuidv4(),
provider: "authkit",

View file

@ -1,9 +1,17 @@
import { ConfigJson } from "@continuedev/config-types";
import {
AssistantUnrolled,
ConfigResult,
FQSN,
FullSlug,
SecretResult,
} from "@continuedev/config-yaml";
import fetch, { RequestInit, Response } from "node-fetch";
import { ModelDescription } from "../index.js";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeSettings, ModelDescription } from "../index.js";
import { controlPlaneEnv } from "./env.js";
import { getControlPlaneEnv } from "./env.js";
export interface ControlPlaneSessionInfo {
accessToken: string;
@ -25,17 +33,29 @@ export const TRIAL_PROXY_URL =
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
export class ControlPlaneClient {
private static URL = controlPlaneEnv.CONTROL_PLANE_URL;
private static ACCESS_TOKEN_VALID_FOR_MS = 1000 * 60 * 5; // 5 minutes
private lastAccessTokenRefresh = 0;
constructor(
private readonly sessionInfoPromise: Promise<
ControlPlaneSessionInfo | undefined
>,
private readonly ideSettingsPromise: Promise<IdeSettings>,
) {}
async resolveFQSNs(
fqsns: FQSN[],
orgScopeId: string | null,
): Promise<(SecretResult | undefined)[]> {
const userId = await this.userId;
if (!userId) {
throw new Error("No user id");
}
const resp = await this.request("ide/sync-secrets", {
method: "POST",
body: JSON.stringify({ fqsns, orgScopeId }),
});
return (await resp.json()) as any;
}
get userId(): Promise<string | undefined> {
return this.sessionInfoPromise.then(
(sessionInfo) => sessionInfo?.account.id,
@ -51,7 +71,9 @@ export class ControlPlaneClient {
if (!accessToken) {
throw new Error("No access token");
}
const url = new URL(path, ControlPlaneClient.URL).toString();
const env = await getControlPlaneEnv(this.ideSettingsPromise);
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
const resp = await fetch(url, {
...init,
headers: {
@ -85,6 +107,74 @@ export class ControlPlaneClient {
}
}
public async listAssistants(organizationId: string | null): Promise<
{
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
packageSlug: string;
iconUrl: string;
}[]
> {
const userId = await this.userId;
if (!userId) {
return [];
}
try {
const url = organizationId
? `ide/list-assistants?organizationId=${organizationId}`
: "ide/list-assistants";
const resp = await this.request(url, {
method: "GET",
});
return (await resp.json()) as any;
} catch (e) {
return [];
}
}
public async listOrganizations(): Promise<Array<OrganizationDescription>> {
const userId = await this.userId;
if (!userId) {
return [];
}
try {
const resp = await this.request("ide/list-organizations", {
method: "GET",
});
const { organizations } = (await resp.json()) as any;
return organizations;
} catch (e) {
return [];
}
}
public async listAssistantFullSlugs(
organizationId: string | null,
): Promise<FullSlug[] | null> {
const userId = await this.userId;
if (!userId) {
return null;
}
const url = organizationId
? `ide/list-assistant-full-slugs?organizationId=${organizationId}`
: "ide/list-assistant-full-slugs";
try {
const resp = await this.request(url, {
method: "GET",
});
const { fullSlugs } = (await resp.json()) as any;
return fullSlugs;
} catch (e) {
return null;
}
}
async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> {
const userId = await this.userId;
if (!userId) {

View file

@ -1,4 +1,8 @@
interface ControlPlaneEnv {
import * as fs from "node:fs";
import { IdeSettings } from "..";
import { getStagingEnvironmentDotFilePath } from "../util/paths";
export interface ControlPlaneEnv {
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
CONTROL_PLANE_URL: string;
AUTH_TYPE: string;
@ -21,17 +25,31 @@ const PRODUCTION_ENV: ControlPlaneEnv = {
"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",
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/",
AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
APP_URL: "https://hub.continue.dev/",
};
const STAGING_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL:
"https://control-plane-api-service-537175798139.us-central1.run.app/",
CONTROL_PLANE_URL:
"https://control-plane-api-service-537175798139.us-central1.run.app/",
AUTH_TYPE: WORKOS_CLIENT_ID_STAGING,
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/",
CONTROL_PLANE_URL: "https://api.continue-stage.tools/",
AUTH_TYPE: WORKOS_ENV_ID_STAGING,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "https://app-preview.continue.dev",
APP_URL: "https://hub.continue-stage.tools/",
};
const TEST_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/",
CONTROL_PLANE_URL: "https://api-test.continue.dev/",
AUTH_TYPE: WORKOS_ENV_ID_STAGING,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "https://app-test.continue.dev/",
};
const LOCAL_ENV: ControlPlaneEnv = {
@ -39,12 +57,61 @@ const LOCAL_ENV: ControlPlaneEnv = {
CONTROL_PLANE_URL: "http://localhost:3001/",
AUTH_TYPE: WORKOS_ENV_ID_STAGING,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "http://localhost:3000",
APP_URL: "http://localhost:3000/",
};
export const controlPlaneEnv =
process.env.CONTROL_PLANE_ENV === "local"
export async function enableHubContinueDev() {
return true;
}
export async function getControlPlaneEnv(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<ControlPlaneEnv> {
const ideSettings = await ideSettingsPromise;
return getControlPlaneEnvSync(
ideSettings.continueTestEnvironment,
ideSettings.enableControlServerBeta,
);
}
export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
enableControlServerBeta: IdeSettings["enableControlServerBeta"],
): ControlPlaneEnv {
if (fs.existsSync(getStagingEnvironmentDotFilePath())) {
return STAGING_ENV;
}
if (enableControlServerBeta === true) {
return PRODUCTION_ENV;
}
const env =
ideTestEnvironment === "production"
? "hub"
: ideTestEnvironment === "staging"
? "staging"
: ideTestEnvironment === "local"
? "local"
: process.env.CONTROL_PLANE_ENV;
return env === "local"
? LOCAL_ENV
: process.env.CONTROL_PLANE_ENV === "staging"
: env === "staging"
? STAGING_ENV
: PRODUCTION_ENV;
: env === "test"
? TEST_ENV
: env === "hub"
? PRODUCTION_HUB_ENV
: PRODUCTION_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

@ -1,7 +1,4 @@
import path from "path";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import ignore from "ignore";
import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
@ -11,51 +8,57 @@ import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import {
setupBestConfig,
setupLocalConfig,
setupLocalConfigAfterFreeTrial,
setupQuickstartConfig,
} from "./config/onboarding";
import { addContextProvider, addModel, deleteModel } from "./config/util";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { ControlPlaneClient } from "./control-plane/client";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
import { DataLogger } from "./data/log";
import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { getAllSuggestedDocs } from "./indexing/docs/suggestions";
import { defaultIgnoreFile } from "./indexing/ignore.js";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { logDevData } from "./util/devdata";
import { DevDataSqliteDb } from "./util/devdataSqlite";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import {
editConfigJson,
getConfigJsonPath,
setupInitialDotContinueDirectory,
migrateV1DevDataFiles,
} from "./util/paths";
import { localPathToUri } from "./util/pathToUri";
import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
import { type ContextItemId, type IDE, type IndexingProgressUpdate } from ".";
import {
ChatMessage,
DiffLine,
PromptLog,
type ContextItemId,
type IDE,
type IndexingProgressUpdate,
} from ".";
import { shouldIgnore } from "./indexing/shouldIgnore";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
configHandler: ConfigHandler;
codebaseIndexerPromise: Promise<CodebaseIndexer>;
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
codebaseIndexingState: IndexingProgressUpdate;
controlPlaneClient: ControlPlaneClient;
private docsService: DocsService;
private globalContext = new GlobalContext();
@ -65,10 +68,6 @@ export class Core {
private abortedMessageIds: Set<string> = new Set();
private async config() {
return (await this.configHandler.loadConfig()).config;
}
invoke<T extends keyof ToCoreProtocol>(
messageType: T,
data: ToCoreProtocol[T][0],
@ -92,7 +91,7 @@ export class Core {
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
migrateV1DevDataFiles();
this.codebaseIndexingState = {
status: "loading",
@ -100,18 +99,18 @@ export class Core {
progress: 0,
};
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
silent: true,
useOnboarding: false,
});
this.controlPlaneClient = new ControlPlaneClient(sessionInfoPromise);
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.onWrite,
this.controlPlaneClient,
sessionInfoPromise,
);
this.docsService = DocsService.createSingleton(
@ -124,14 +123,34 @@ export class Core {
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
result: serializedResult,
profileId: this.configHandler.currentProfile.profileId,
profileId:
this.configHandler.currentProfile?.profileDescription.id ?? null,
});
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
if (additionalProviders.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: additionalProviders,
});
}
});
this.configHandler.onDidChangeAvailableProfiles((profiles) =>
this.messenger.send("didChangeAvailableProfiles", { profiles }),
this.configHandler.onDidChangeAvailableProfiles(
(profiles, selectedProfileId) =>
this.messenger.send("didChangeAvailableProfiles", {
profiles,
selectedProfileId,
}),
);
// Dev Data Logger
const dataLogger = DataLogger.getInstance();
dataLogger.core = this;
dataLogger.ideInfoPromise = ideInfoPromise;
dataLogger.ideSettingsPromise = ideSettingsPromise;
// Codebase Indexer and ContinueServerClient depend on IdeSettings
let codebaseIndexerResolve: (_: any) => void | undefined;
this.codebaseIndexerPromise = new Promise(
@ -178,12 +197,10 @@ export class Core {
const getLlm = async () => {
const { config } = await this.configHandler.loadConfig();
const selected = this.globalContext.get("selectedTabAutocompleteModel");
return (
config?.tabAutocompleteModels?.find(
(model) => model.title === selected,
) ?? config?.tabAutocompleteModels?.[0]
);
if (!config) {
return undefined;
}
return config.selectedModelByRole.autocomplete ?? undefined;
};
this.completionProvider = new CompletionProvider(
this.configHandler,
@ -197,18 +214,24 @@ export class Core {
// Note, VsCode's in-process messenger doesn't do anything with this
// It will only show for jetbrains
this.messenger.onError((err) => {
console.error(err);
this.messenger.onError((message, err) => {
void Telemetry.capture("core_messenger_error", {
message: err.message,
stack: err.stack,
});
void this.ide.showToast("error", err.message);
});
on("update/selectTabAutocompleteModel", async (msg) => {
this.globalContext.update("selectedTabAutocompleteModel", msg.data);
void this.configHandler.reloadConfig();
// Again, specifically for jetbrains to prevent duplicate error messages
// The same logic can currently be found in the webview protocol
// bc streaming errors are handled in the GUI
if (
["llm/streamChat", "chatDescriber/describe"].includes(
message.messageType,
)
) {
return;
} else {
void this.ide.showToast("error", err.message);
}
});
// Special
@ -241,8 +264,8 @@ export class Core {
});
// Dev data
on("devdata/log", (msg) => {
logDevData(msg.data.tableName, msg.data.data);
on("devdata/log", async (msg) => {
void DataLogger.getInstance().logDevData(msg.data);
});
// Edit config
@ -258,10 +281,8 @@ export class Core {
});
on("config/newPromptFile", async (msg) => {
await createNewPromptFileV2(
this.ide,
(await this.config())?.experimental?.promptPath,
);
const { config } = await this.configHandler.loadConfig();
await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
await this.configHandler.reloadConfig();
});
@ -277,12 +298,46 @@ export class Core {
on("config/ideSettingsUpdate", (msg) => {
this.configHandler.updateIdeSettings(msg.data);
});
on("config/listProfiles", (msg) => {
return this.configHandler.listProfiles();
});
on("config/refreshProfiles", async (msg) => {
await this.configHandler.loadAssistantsForSelectedOrg();
});
on("config/addContextProvider", async (msg) => {
addContextProvider(msg.data);
addContextProvider(msg.data, this.configHandler);
});
on("config/updateSharedConfig", async (msg) => {
const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
await this.configHandler.reloadConfig();
return newSharedConfig;
});
on("config/updateSelectedModel", async (msg) => {
const newSelectedModels = this.globalContext.updateSelectedModel(
msg.data.profileId,
msg.data.role,
msg.data.title,
);
await this.configHandler.reloadConfig();
return newSelectedModels;
});
on("controlPlane/openUrl", async (msg) => {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
let url = `${env.APP_URL}${msg.data.path}`;
if (msg.data.orgSlug) {
url += `?org=${msg.data.orgSlug}`;
}
await this.messenger.request("openUrl", url);
});
on("controlPlane/listOrganizations", async (msg) => {
return await this.configHandler.listOrganizations();
});
// Context providers
@ -299,7 +354,7 @@ export class Core {
});
on("context/loadSubmenuItems", async (msg) => {
const config = await this.config();
const { config } = await this.configHandler.loadConfig();
if (!config) {
return [];
}
@ -316,17 +371,26 @@ export class Core {
});
on("context/getContextItems", async (msg) => {
const { name, query, fullInput, selectedCode, selectedModelTitle } =
msg.data;
const config = await this.config();
const { config } = await this.configHandler.loadConfig();
if (!config) {
return [];
}
const { name, query, fullInput, selectedCode, selectedModelTitle } =
msg.data;
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
const provider = config.contextProviders?.find(
(provider) => provider.description.title === name,
);
const provider =
config.contextProviders?.find(
(provider) => provider.description.title === name,
) ??
[
// user doesn't need these in their config.json for the shortcuts to work
// option+enter
new CurrentFileContextProvider({}),
// cmd+enter
new CodebaseContextProvider({}),
].find((provider) => provider.description.title === name);
if (!provider) {
return [];
}
@ -340,11 +404,11 @@ export class Core {
const items = await provider.getContextItems(query, {
config,
llm,
embeddingsProvider: config.embeddingsProvider,
embeddingsProvider: config.selectedModelByRole.embed,
fullInput,
ide,
selectedCode,
reranker: config.reranker,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
@ -362,10 +426,35 @@ export class Core {
id,
}));
} catch (e) {
void this.ide.showToast(
"error",
`Error getting context items from ${name}: ${e}`,
);
let knownError = false;
if (e instanceof Error) {
// After removing transformers JS embeddings provider from jetbrains
// Should no longer see this error
// if (e.message.toLowerCase().includes("embeddings provider")) {
// knownError = true;
// const toastOption = "See Docs";
// void this.ide
// .showToast(
// "error",
// `Set up an embeddings model to use @${name}`,
// toastOption,
// )
// .then((userSelection) => {
// if (userSelection === toastOption) {
// void this.ide.openUrl(
// "https://docs.continue.dev/customize/model-roles/embeddings",
// );
// }
// });
// }
}
if (!knownError) {
void this.ide.showToast(
"error",
`Error getting context items from ${name}: ${e}`,
);
}
return [];
}
});
@ -378,7 +467,8 @@ export class Core {
on("config/getSerializedProfileInfo", async (msg) => {
return {
result: await this.configHandler.getSerializedConfig(),
profileId: this.configHandler.currentProfile.profileId,
profileId:
this.configHandler.currentProfile?.profileDescription.id ?? null,
};
});
@ -395,7 +485,7 @@ export class Core {
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
) {
): AsyncGenerator<ChatMessage, PromptLog> {
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
@ -431,7 +521,7 @@ export class Core {
const chunk = next.value;
yield { content: chunk };
yield chunk;
next = await gen.next();
}
@ -448,7 +538,11 @@ export class Core {
true,
);
return { done: true, content: next.value };
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
}
on("llm/streamChat", (msg) =>
@ -458,9 +552,8 @@ export class Core {
async function* llmStreamComplete(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamComplete"][0]>,
) {
): AsyncGenerator<string, PromptLog> {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamComplete(
msg.data.prompt,
@ -482,11 +575,13 @@ export class Core {
});
break;
}
yield { content: next.value };
yield next.value;
next = await gen.next();
}
return { done: true, content: next.value };
if (!next.done) {
throw new Error("This will never happen");
}
return next.value;
}
on("llm/streamComplete", (msg) =>
@ -548,7 +643,7 @@ export class Core {
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["command/run"][0]>,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
) {
): AsyncGenerator<string> {
const {
input,
history,
@ -558,6 +653,7 @@ export class Core {
params,
historyIndex,
selectedCode,
completionOptions,
} = msg.data;
const { config } = await configHandler.loadConfig();
@ -606,6 +702,7 @@ export class Core {
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
completionOptions,
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
@ -613,7 +710,7 @@ export class Core {
break;
}
if (content) {
yield { content };
yield content;
}
}
} catch (e) {
@ -621,7 +718,6 @@ export class Core {
} finally {
clearInterval(checkActiveInterval);
}
yield { done: true, content: "" };
}
on("command/run", (msg) =>
runNodeJsSlashCommand(
@ -652,7 +748,7 @@ export class Core {
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
) {
): AsyncGenerator<DiffLine> {
const data = msg.data;
const llm = await configHandler.llmFromTitle(msg.data.modelTitle);
for await (const diffLine of streamDiffLines(
@ -662,15 +758,15 @@ export class Core {
llm,
data.input,
data.language,
false,
undefined,
)) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
break;
}
yield { content: diffLine };
yield diffLine;
}
return { done: true };
}
on("streamDiffLines", (msg) =>
@ -695,10 +791,6 @@ export class Core {
editConfigJsonCallback = setupQuickstartConfig;
break;
case "LocalAfterFreeTrial":
editConfigJsonCallback = setupLocalConfigAfterFreeTrial;
break;
case "Best":
editConfigJsonCallback = setupBestConfig;
break;
@ -734,6 +826,10 @@ export class Core {
// Codebase indexing
on("index/forceReIndex", async ({ data }) => {
const { config } = await this.configHandler.loadConfig();
if (!config || config.disableIndexing) {
return; // TODO silent in case of commands?
}
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
await codebaseIndexer.clearIndexes();
@ -791,24 +887,51 @@ export class Core {
uri.endsWith(".gitignore")
) {
// Reindex the workspaces
this.invoke("index/forceReIndex", undefined);
this.invoke("index/forceReIndex", {
shouldClearIndexes: true,
});
} else {
// Reindex the file
await this.refreshCodebaseIndexFiles([uri]);
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
// Reindex the file
const ignore = await shouldIgnore(uri, this.ide);
if (!ignore) {
await this.refreshCodebaseIndexFiles([uri]);
}
}
}
}
}
});
const refreshIfNotIgnored = async (uris: string[]) => {
const toRefresh: string[] = [];
for (const uri of uris) {
const ignore = await shouldIgnore(uri, ide);
if (!ignore) {
toRefresh.push(uri);
}
}
if (toRefresh.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
await this.refreshCodebaseIndexFiles(toRefresh);
}
}
};
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
await this.refreshCodebaseIndexFiles(data.uris);
void refreshIfNotIgnored(data.uris);
}
});
on("files/deleted", async ({ data }) => {
if (data?.uris?.length) {
await this.refreshCodebaseIndexFiles(data.uris);
void refreshIfNotIgnored(data.uris);
}
});
on("files/opened", async ({ data }) => {
@ -844,34 +967,51 @@ export class Core {
on("docs/initStatuses", async (msg) => {
void this.docsService.initStatuses();
});
on("docs/getDetails", async (msg) => {
return await this.docsService.getDetails(msg.data.startUrl);
});
//
on("didChangeSelectedProfile", (msg) => {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
on("didChangeSelectedProfile", async (msg) => {
await this.configHandler.setSelectedProfile(msg.data.id);
await this.configHandler.reloadConfig();
});
on("didChangeSelectedOrg", async (msg) => {
await this.configHandler.setSelectedOrgId(msg.data.id);
await this.configHandler.loadAssistantsForSelectedOrg();
if (msg.data.profileId) {
this.invoke("didChangeSelectedProfile", {
id: msg.data.profileId,
});
} else {
await this.configHandler.reloadConfig();
}
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
await this.configHandler.updateControlPlaneSessionInfo(
msg.data.sessionInfo,
);
});
on("auth/getAuthUrl", async (msg) => {
const url = await getAuthUrlForTokenPage();
const url = await getAuthUrlForTokenPage(
ideSettingsPromise,
msg.data.useOnboarding,
);
return { url };
});
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
const ignoreInstance = ignore().add(defaultIgnoreFile);
let rootDirectory = await this.ide.getWorkspaceDirs();
const relativeFilePath = path.relative(rootDirectory[0], filepath);
try {
if (!ignoreInstance.ignores(relativeFilePath)) {
const ignore = shouldIgnore(filepath, this.ide);
if (!ignore) {
recentlyEditedFilesCache.set(filepath, filepath);
}
} catch (e) {
if (e instanceof RangeError) {
// do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json`
} else {
console.debug("unhandled ignores error", relativeFilePath, e);
}
console.error(
`didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`,
);
}
});
@ -892,16 +1032,23 @@ export class Core {
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
const contextItems = await callTool(
tool.uri ?? tool.function.name,
tool,
JSON.parse(toolCall.function.arguments || "{}"),
{
ide: this.ide,
llm,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
},
);
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;
});
}
return { contextItems };
});
}
@ -985,6 +1132,7 @@ export class Core {
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
this.indexingCancellationController = undefined;
}
// private

View file

@ -5,8 +5,9 @@ import sqlite3 from "sqlite3";
import { DatabaseConnection } from "../indexing/refreshIndex.js";
import { getDevDataSqlitePath } from "./paths.js";
import { getDevDataSqlitePath } from "../util/paths.js";
/* The Dev Data SQLITE table is only used for local tokens generated */
export class DevDataSqliteDb {
static db: DatabaseConnection | null = null;

226
core/data/log.ts Normal file
View file

@ -0,0 +1,226 @@
import fs from "fs";
import path from "path";
import {
allDevEventNames,
DataLogLevel,
DevDataLogEvent,
devDataVersionedSchemas,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as URI from "uri-js";
import { fileURLToPath } from "url";
import { AnyZodObject } from "zod";
import { Core } from "../core.js";
import { IdeInfo, IdeSettings } from "../index.js";
import { getDevDataFilePath } from "../util/paths.js";
import { joinPathsToUri } from "../util/uri.js";
const DEFAULT_DEV_DATA_LEVEL: DataLogLevel = "all";
export const LOCAL_DEV_DATA_VERSION = "0.2.0";
export class DataLogger {
private static instance: DataLogger | null = null;
core?: Core;
ideSettingsPromise?: Promise<IdeSettings>;
ideInfoPromise?: Promise<IdeInfo>;
private constructor() {}
public static getInstance(): DataLogger {
if (DataLogger.instance === null) {
DataLogger.instance = new DataLogger();
}
return DataLogger.instance;
}
async addBaseValues(
body: Record<string, any>,
eventName: string,
schema: string,
zodSchema: AnyZodObject,
): Promise<Record<string, any>> {
const newBody = { ...body };
const ideSettings = await this.ideSettingsPromise;
const ideInfo = await this.ideInfoPromise;
if ("eventName" in zodSchema.shape) {
newBody.eventName = eventName;
}
if ("timestamp" in zodSchema.shape) {
newBody.timestamp = new Date().toISOString();
}
if ("schema" in zodSchema.shape) {
newBody.schema = schema;
}
if ("userAgent" in zodSchema.shape) {
newBody.userAgent = ideInfo
? `${ideInfo.name}/${ideInfo.version} (Continue/${ideInfo.extensionVersion})`
: "Unknown/Unknown (Continue/Unknown)";
}
if ("selectedProfileId" in zodSchema.shape) {
newBody.selectedProfileId =
this.core?.configHandler.currentProfile?.profileDescription.id ?? "";
}
if ("userId" in zodSchema.shape) {
newBody.userId = ideSettings?.userToken ?? "";
}
return newBody;
}
async logDevData(event: DevDataLogEvent) {
// Local logs (always on for all levels)
try {
const filepath: string = getDevDataFilePath(
event.name,
LOCAL_DEV_DATA_VERSION,
);
const localSchema =
devDataVersionedSchemas[LOCAL_DEV_DATA_VERSION]["all"][event.name];
if (!localSchema) {
throw new Error(
`Schema ${LOCAL_DEV_DATA_VERSION} doesn't exist at level "all"`,
);
}
const eventDataWithBaseValues = await this.addBaseValues(
event.data,
event.name,
LOCAL_DEV_DATA_VERSION,
localSchema,
);
const parsed = localSchema?.safeParse(eventDataWithBaseValues);
if (parsed?.success) {
fs.writeFileSync(filepath, `${JSON.stringify(parsed.data)}\n`, {
flag: "a",
});
}
} catch (error) {
console.error("Error logging local dev data:", error);
}
// Remote logs
const config = (await this.core?.configHandler.loadConfig())?.config;
if (config?.data?.length) {
await Promise.allSettled(
config.data.map(async (dataConfig) => {
try {
// First extract the data schema based on the version and level
const { schema } = dataConfig;
const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
// Skip event if `events` is specified and does not include the event
const events = dataConfig.events ?? allDevEventNames;
if (!events.includes(event.name)) {
return;
}
const versionSchemas = devDataVersionedSchemas[schema];
if (!versionSchemas) {
throw new Error(
`Attempting to log dev data to non-existent version ${schema}`,
);
}
const levelSchemas = versionSchemas[level];
if (!levelSchemas) {
throw new Error(
`Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
);
}
const zodSchema = levelSchemas[event.name];
if (!zodSchema) {
throw new Error(
`Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
);
}
const eventDataWithBaseValues = await this.addBaseValues(
event.data,
event.name,
schema,
zodSchema,
);
const parsed = zodSchema.safeParse(eventDataWithBaseValues);
if (!parsed.success) {
throw new Error(
`Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
);
}
const uriComponents = URI.parse(dataConfig.destination);
// Send to remote server
if (
uriComponents.scheme === "https" ||
uriComponents.scheme === "http"
) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (dataConfig.apiKey) {
headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
}
// For events going to Continue, overwrite the access token
if (
uriComponents.host?.endsWith(".continue.dev") ||
uriComponents.host === "continue.dev"
) {
//
const accessToken =
await this.core?.configHandler.controlPlaneClient.getAccessToken();
headers["Authorization"] = `Bearer ${accessToken}`;
}
const profileId =
this.core?.configHandler.currentProfile?.profileDescription
.id ?? "";
const response = await fetchwithRequestOptions(
dataConfig.destination,
{
method: "POST",
headers,
body: JSON.stringify({
name: event.name,
data: parsed.data,
schema,
level,
profileId,
}),
},
dataConfig.requestOptions,
);
if (!response.ok) {
throw new Error(
`Post request failed. ${response.status}: ${response.statusText}`,
);
}
} else if (uriComponents.scheme === "file") {
// Write to jsonc file for local file URIs
const dirUri = joinPathsToUri(dataConfig.destination, schema);
const dirPath = fileURLToPath(dirUri);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
const filepath = path.join(dirPath, `${event.name}.jsonl`);
const jsonLine = JSON.stringify(event.data);
fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
} else {
throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
}
} catch (error) {
console.error(
`Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
);
}
}),
);
}
}
}

View file

@ -19,7 +19,8 @@ export async function applyCodeBlock(
llm: ILLM,
fastLlm: ILLM,
): Promise<[boolean, AsyncGenerator<DiffLine>]> {
if (canUseInstantApply(filename)) {
// This was buggy, removed for now, maybe forever
if (false && canUseInstantApply(filename)) {
const diffLines = await deterministicApplyLazyEdit(
oldFile,
newFile,

View file

@ -54,7 +54,8 @@ export async function* streamDiffLines(
llm: ILLM,
input: string,
language: string | undefined,
onlyOneInsertion?: boolean,
onlyOneInsertion: boolean,
overridePrompt: ChatMessage[] | undefined,
): AsyncGenerator<DiffLine> {
void Telemetry.capture(
"inlineEdit",
@ -80,14 +81,9 @@ export async function* streamDiffLines(
// Trim end of oldLines, otherwise we have trailing \r on every line for CRLF files
oldLines = oldLines.map((line) => line.trimEnd());
const prompt = constructPrompt(
prefix,
highlighted,
suffix,
llm,
input,
language,
);
const prompt =
overridePrompt ??
constructPrompt(prefix, highlighted, suffix, llm, input, language);
const inept = modelIsInept(llm.model);
const prediction: Prediction = {

153
core/index.d.ts vendored
View file

@ -1,6 +1,6 @@
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
interface Window {
ide?: "vscode";
@ -60,7 +60,7 @@ export interface IndexingStatus {
progress: number;
description: string;
status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending";
embeddingsProviderId: string;
embeddingsProviderId?: string;
isReindexing?: boolean;
debugInfo?: string;
title: string;
@ -94,6 +94,8 @@ export interface ILLM extends LLMOptions {
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
deployment?: string;
apiVersion?: string;
@ -161,6 +163,10 @@ export interface ILLM extends LLMOptions {
): string | ChatMessage[];
}
export interface ModelInstaller {
installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise<any>;
}
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
@ -177,8 +183,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
export interface ContextProviderExtras {
config: ContinueConfig;
fullInput: string;
embeddingsProvider: ILLM;
reranker: ILLM | undefined;
embeddingsProvider: ILLM | null;
reranker: ILLM | null;
llm: ILLM;
ide: IDE;
selectedCode: RangeInFile[];
@ -223,16 +229,18 @@ export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
export interface SiteIndexingConfig {
title: string;
startUrl: string;
rootUrl?: string;
maxDepth?: number;
faviconUrl?: string;
useLocalCrawling?: boolean;
rootUrl?: string; // Currently only used by preindexed docs
}
export interface SiteIndexingConfig {
export interface DocsIndexingDetails {
startUrl: string;
rootUrl?: string;
title: string;
maxDepth?: number;
config: SiteIndexingConfig;
indexingStatus: IndexingStatus | undefined;
chunks: Chunk[];
isPreIndexedDoc: boolean;
}
export interface IContextProvider {
@ -306,11 +314,17 @@ export interface CompletionOptions extends BaseCompletionOptions {
export type ChatMessageRole = "user" | "assistant" | "system" | "tool";
export interface MessagePart {
type: "text" | "imageUrl";
text?: string;
imageUrl?: { url: string };
}
export type TextMessagePart = {
type: "text";
text: string;
};
export type ImageMessagePart = {
type: "imageUrl";
imageUrl: { url: string };
};
export type MessagePart = TextMessagePart | ImageMessagePart;
export type MessageContent = string | MessagePart[];
@ -425,6 +439,13 @@ interface ToolCallState {
output?: ContextItem[];
}
interface Reasoning {
active: boolean;
text: string;
startAt: number;
endAt?: number;
}
export interface ChatHistoryItem {
message: ChatMessage;
contextItems: ContextItemWithId[];
@ -435,6 +456,7 @@ export interface ChatHistoryItem {
isGatheringContext?: boolean;
checkpoint?: Checkpoint;
isBeforeCheckpoint?: boolean;
reasoning?: Reasoning;
}
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@ -460,9 +482,18 @@ export interface LLMOptions {
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
aiGatewaySlug?: string;
// continueProperties
apiKeyLocation?: string;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
aiGatewaySlug?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
useLegacyCompletionsEndpoint?: boolean;
@ -483,17 +514,16 @@ export interface LLMOptions {
profile?: string;
modelArn?: string;
// AWS and GCP Options
// AWS and VertexAI Options
region?: string;
// GCP Options
capabilities?: ModelCapability;
// GCP and Watsonx Options
// VertexAI and Watsonx Options
projectId?: string;
// IBM watsonx Options
deploymentId?: string;
env?: Record<string, string | number | boolean>;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
@ -517,7 +547,7 @@ export interface CustomLLMWithOptionals {
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
) => AsyncGenerator<ChatMessage | string>;
listModels?: (
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => Promise<string[]>;
@ -582,8 +612,8 @@ export interface IdeSettings {
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
continueTestEnvironment: "none" | "production" | "staging" | "local";
pauseCodebaseIndexOnStart: boolean;
enableDebugLogs: boolean;
}
export interface FileStats {
@ -655,6 +685,10 @@ export interface IDE {
}
>;
getLastFileSaveTimestamp?(): number;
updateLastFileSaveTimestamp?(): void;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
@ -683,6 +717,11 @@ export interface IDE {
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
// Secret Storage
readSecrets(keys: string[]): Promise<Record<string, string>>;
writeSecrets(secrets: { [key: string]: string }): Promise<void>;
// LSP
gotoDefinition(location: Location): Promise<RangeInFile[]>;
@ -703,6 +742,7 @@ export interface ContinueSDK {
selectedCode: RangeInFile[];
config: ContinueConfig;
fetch: FetchFunction;
completionOptions?: LLMFullCompletionOptions;
}
export interface SlashCommand {
@ -820,7 +860,7 @@ export interface SlashCommandDescription {
export interface CustomCommand {
name: string;
prompt: string;
description: string;
description?: string;
}
export interface Prediction {
@ -837,6 +877,7 @@ export interface ToolExtras {
ide: IDE;
llm: ILLM;
fetch: FetchFunction;
tool: Tool;
}
export interface Tool {
@ -852,6 +893,14 @@ export interface Tool {
wouldLikeTo: string;
readonly: boolean;
uri?: string;
faviconUrl?: string;
}
interface ToolChoice {
type: "function";
function: {
name: string;
};
}
export interface BaseCompletionOptions {
@ -871,10 +920,12 @@ export interface BaseCompletionOptions {
stream?: boolean;
prediction?: Prediction;
tools?: Tool[];
toolChoice?: ToolChoice;
}
export interface ModelCapability {
uploadImage?: boolean;
tools?: boolean;
}
export interface ModelDescription {
@ -882,7 +933,14 @@ export interface ModelDescription {
provider: string;
model: string;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
contextLength?: number;
maxStopWords?: number;
template?: TemplateType;
@ -890,8 +948,9 @@ export interface ModelDescription {
systemMessage?: string;
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
}
export interface EmbedOptions {
@ -902,15 +961,16 @@ export interface EmbedOptions {
apiType?: string;
apiVersion?: string;
requestOptions?: RequestOptions;
maxChunkSize?: number;
maxBatchSize?: number;
maxEmbeddingChunkSize?: number;
maxEmbeddingBatchSize?: number;
// AWS options
profile?: string;
// AWS and GCP Options
// AWS and VertexAI Options
region?: string;
// GCP and Watsonx Options
// VertexAI and Watsonx Options
projectId?: string;
}
@ -925,7 +985,6 @@ export interface RerankerDescription {
export interface TabAutocompleteOptions {
disable: boolean;
useFileSuffix: boolean;
maxPromptTokens: number;
debounceDelay: number;
maxSuffixPercentage: number;
@ -941,6 +1000,11 @@ export interface TabAutocompleteOptions {
disableInFiles?: string[];
useImports?: boolean;
showWhateverWeHaveAtXMs?: number;
// true = enabled, false = disabled, number = enabled with priority
experimental_includeClipboard: boolean | number;
experimental_includeRecentlyVisitedRanges: boolean | number;
experimental_includeRecentlyEditedRanges: boolean | number;
experimental_includeDiff: boolean | number;
}
export interface StdioOptions {
@ -964,6 +1028,7 @@ export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
export interface MCPOptions {
transport: TransportOptions;
faviconUrl?: string;
}
export interface ContinueUIConfig {
@ -971,8 +1036,8 @@ export interface ContinueUIConfig {
fontSize?: number;
displayRawMarkdown?: boolean;
showChatScrollbar?: boolean;
getChatTitles?: boolean;
codeWrap?: boolean;
showSessionTabs?: boolean;
}
export interface ContextMenuConfig {
@ -983,10 +1048,10 @@ export interface ContextMenuConfig {
fixGrammar?: string;
}
export interface ModelRoles {
export interface ExperimentalModelRoles {
repoMapFileSelection?: string;
inlineEdit?: string;
applyCodeBlock?: string;
repoMapFileSelection?: string;
}
export type EditStatus =
@ -1051,7 +1116,7 @@ export type DefaultContextProvider = ContextProviderWithParams & {
export interface ExperimentalConfig {
contextMenuPrompts?: ContextMenuConfig;
modelRoles?: ModelRoles;
modelRoles?: ExperimentalModelRoles;
defaultContext?: DefaultContextProvider[];
promptPath?: string;
@ -1076,7 +1141,7 @@ export interface ExperimentalConfig {
}
export interface AnalyticsConfig {
type: string;
provider: string;
url?: string;
clientKey?: string;
}
@ -1103,6 +1168,7 @@ export interface SerializedContinueConfig {
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
data?: DataDestination[];
}
export type ConfigMergeType = "merge" | "overwrite";
@ -1155,6 +1221,7 @@ export interface Config {
experimental?: ExperimentalConfig;
/** Analytics configuration */
analytics?: AnalyticsConfig;
data?: DataDestination[];
}
// in the actual Continue source code
@ -1169,15 +1236,15 @@ export interface ContinueConfig {
disableSessionTitles?: boolean;
disableIndexing?: boolean;
userToken?: string;
embeddingsProvider: ILLM;
tabAutocompleteModels?: ILLM[];
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
ui?: ContinueUIConfig;
reranker?: ILLM;
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
modelsByRole: Record<ModelRole, ILLM[]>;
selectedModelByRole: Record<ModelRole, ILLM | null>;
data?: DataDestination[];
}
export interface BrowserSerializedContinueConfig {
@ -1191,13 +1258,15 @@ export interface BrowserSerializedContinueConfig {
disableIndexing?: boolean;
disableSessionTitles?: boolean;
userToken?: string;
embeddingsProvider?: string;
ui?: ContinueUIConfig;
reranker?: RerankerDescription;
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
modelsByRole: Record<ModelRole, ModelDescription[]>;
selectedModelByRole: Record<ModelRole, ModelDescription | null>;
}
// DOCS SUGGESTIONS AND PACKAGE INFO
@ -1235,9 +1304,9 @@ export type PackageDocsResult = {
} & (
| { error: string; details?: never }
| { details: PackageDetailsSuccess; error?: never }
);
);
export interface TerminalOptions {
reuseTerminal?: boolean,
terminalName?: string,
reuseTerminal?: boolean;
terminalName?: string;
}

View file

@ -28,7 +28,12 @@ import type {
IndexTag,
IndexingProgressUpdate,
} from "../";
import { getLastNPathParts, getUriPathBasename } from "../util/uri";
import {
findUriInDirs,
getLastNPathParts,
getLastNUriRelativePathParts,
getUriPathBasename,
} from "../util/uri";
type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
@ -347,14 +352,19 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
}
}
static async getForId(id: number): Promise<ContextItem> {
static async getForId(
id: number,
workspaceDirs: string[],
): Promise<ContextItem> {
const db = await SqliteDb.get();
const row = await db.get("SELECT * FROM code_snippets WHERE id = ?", [id]);
const last2Parts = getLastNUriRelativePathParts(workspaceDirs, row.path, 2);
const { relativePathOrBasename } = findUriInDirs(row.path, workspaceDirs);
return {
name: row.title,
description: getLastNPathParts(row.path, 2),
content: `\`\`\`${getUriPathBasename(row.path)}\n${row.content}\n\`\`\``,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${row.content}\n\`\`\``,
uri: {
type: "file",
value: row.path,

View file

@ -14,12 +14,12 @@ import {
} from "../test/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { pathToFileURL } from "node:url";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
import { walkDir } from "./walkDir.js";
import { localPathToUri } from "../util/pathToUri.js";
jest.useFakeTimers();
@ -159,7 +159,7 @@ describe("CodebaseIndexer", () => {
test("should have created index folder with all necessary files", async () => {
const exists = await testIde.fileExists(
pathToFileURL(getIndexSqlitePath()).toString(),
localPathToUri(getIndexSqlitePath()),
);
expect(exists).toBe(true);
});

View file

@ -5,8 +5,8 @@ import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
@ -15,6 +15,7 @@ import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import {
CodebaseIndex,
IndexResultType,
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
import { walkDirAsync } from "./walkDir.js";
@ -80,24 +81,66 @@ export class CodebaseIndexer {
return [];
}
const indexes = [
const embeddingsModel = config.selectedModelByRole.embed;
if (!embeddingsModel) {
return [];
}
const indexes: CodebaseIndex[] = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
this.continueServerClient,
config.embeddingsProvider.maxEmbeddingChunkSize,
embeddingsModel.maxEmbeddingChunkSize,
), // Chunking must come first
new LanceDbIndex(
config.embeddingsProvider,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
),
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
];
const lanceDbIndex = await LanceDbIndex.create(
embeddingsModel,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
);
if (lanceDbIndex) {
indexes.push(lanceDbIndex);
}
indexes.push(
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
);
return indexes;
}
private totalIndexOps(results: RefreshIndexResults): number {
return (
results.compute.length +
results.del.length +
results.addTag.length +
results.removeTag.length
);
}
private singleFileIndexOps(
results: RefreshIndexResults,
lastUpdated: PathAndCacheKey[],
filePath: string,
): [RefreshIndexResults, PathAndCacheKey[]] {
const filterFn = (item: PathAndCacheKey) => item.path === filePath;
const compute = results.compute.filter(filterFn);
const del = results.del.filter(filterFn);
const addTag = results.addTag.filter(filterFn);
const removeTag = results.removeTag.filter(filterFn);
const newResults = {
compute,
del,
addTag,
removeTag,
};
const newLastUpdated = lastUpdated.filter(filterFn);
return [newResults, newLastUpdated];
}
public async refreshFile(
file: string,
workspaceDirs: string[],
@ -115,26 +158,28 @@ export class CodebaseIndexer {
const repoName = await this.ide.getRepoName(foundInDir);
const indexesToBuild = await this.getIndexesToBuild();
const stats = await this.ide.getFileStats([file]);
const filePath = Object.keys(stats)[0];
for (const index of indexesToBuild) {
const tag = {
directory: foundInDir,
branch,
artifactId: index.artifactId,
};
const [results, lastUpdated, markComplete] =
const [fullResults, fullLastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
// since this is only a single file update / save we do not want to actualy remove anything, we just want to recompute for our single file
results.removeTag = [];
results.addTag = [];
results.del = [];
const [results, lastUpdated] = this.singleFileIndexOps(
fullResults,
fullLastUpdated,
filePath,
);
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
if (results.compute.length === 0) {
if (this.totalIndexOps(results) + lastUpdated.length === 0) {
continue;
}
@ -415,11 +460,7 @@ export class CodebaseIndexer {
(filepath) => this.ide.readFile(filepath),
repoName,
);
const totalOps =
results.compute.length +
results.del.length +
results.addTag.length +
results.removeTag.length;
const totalOps = this.totalIndexOps(results);
let completedOps = 0;
// Don't update if nothing to update. Some of the indices might do unnecessary setup work

View file

@ -97,13 +97,15 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
await db.run(`
DELETE FROM fts WHERE rowid IN (
SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ?
)
`,[item.path, item.cacheKey]);
await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
item.path,
item.cacheKey,
]);
await db.run("DELETE FROM fts WHERE path = ?", [item.path]);
await markComplete([item], IndexResultType.Delete);
}
}

View file

@ -3,15 +3,15 @@ import lance from "vectordb";
import { testConfigHandler, testIde } from "../test/fixtures";
import { getLanceDbPath } from "../util/paths";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import {
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "./test/indexing";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
jest.useFakeTimers();
@ -30,12 +30,15 @@ describe.skip("ChunkCodebaseIndex", () => {
if (!mockConfig) {
throw new Error("Failed to load config");
}
if (!mockConfig.selectedModelByRole.embed) {
throw new Error("No embeddings model selected");
}
index = new LanceDbIndex(
mockConfig.embeddingsProvider,
index = (await LanceDbIndex.create(
mockConfig.selectedModelByRole.embed,
testIde.readFile.bind(testIde),
testContinueServerClient,
);
))!;
sqliteDb = await SqliteDb.get();
lanceDb = await lance.connect(getLanceDbPath());

View file

@ -1,30 +1,30 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { RunResult } from "sqlite3";
import { v4 as uuidv4 } from "uuid";
import lance, { Table } from "vectordb";
import { IContinueServerClient } from "../continueServer/interface.js";
import { isSupportedLanceDbCpuTargetForLinux } from "../config/util";
import { IContinueServerClient } from "../continueServer/interface";
import {
BranchAndDir,
Chunk,
ILLM,
IndexTag,
IndexingProgressUpdate,
} from "../index.js";
import { getLanceDbPath, migrate } from "../util/paths.js";
} from "../index";
import { getLanceDbPath, migrate } from "../util/paths";
import { getUriPathBasename } from "../util/uri";
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import { chunkDocument, shouldChunk } from "./chunk/chunk";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
CodebaseIndex,
IndexResultType,
MarkCompleteCallback,
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
import { getUriPathBasename } from "../util/uri.js";
} from "./types";
import type * as LanceType from "vectordb";
// LanceDB converts to lowercase, so names must all be lowercase
interface LanceDbRow {
uuid: string;
path: string;
@ -38,16 +38,53 @@ type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] };
type ChunkMap = Map<string, ItemWithChunks>;
export class LanceDbIndex implements CodebaseIndex {
private static lance: typeof LanceType | null = null;
relativeExpectedTime: number = 13;
get artifactId(): string {
return `vectordb::${this.embeddingsProvider.embeddingId}`;
return `vectordb::${this.embeddingsProvider?.embeddingId}`;
}
constructor(
/**
* Factory method for creating LanceDbIndex instances.
*
* We dynamically import LanceDB only when supported to avoid native module loading errors
* on incompatible platforms. LanceDB has CPU-specific native dependencies that can crash
* the application if loaded on unsupported architectures.
*
* See isSupportedLanceDbCpuTargetForLinux() for platform compatibility details.
*/
static async create(
embeddingsProvider: ILLM,
readFile: (filepath: string) => Promise<string>,
continueServerClient?: IContinueServerClient,
): Promise<LanceDbIndex | null> {
if (!isSupportedLanceDbCpuTargetForLinux()) {
return null;
}
try {
this.lance = await import("vectordb");
return new LanceDbIndex(
embeddingsProvider,
readFile,
continueServerClient,
);
} catch (err) {
console.error("Failed to load LanceDB:", err);
return null;
}
}
private constructor(
private readonly embeddingsProvider: ILLM,
private readonly readFile: (filepath: string) => Promise<string>,
private readonly continueServerClient?: IContinueServerClient,
) {}
) {
if (!LanceDbIndex.lance) {
throw new Error("LanceDB not initialized");
}
}
tableNameForTag(tag: IndexTag) {
return tagToString(tag).replace(/[^\w-_.]/g, "");
@ -97,12 +134,10 @@ export class LanceDbIndex implements CodebaseIndex {
);
const embeddings = await this.getEmbeddings(allChunks);
// Remove undefined embeddings and their corresponding chunks
for (let i = embeddings.length - 1; i >= 0; i--) {
if (embeddings[i] === undefined) {
const chunk = allChunks[i];
const chunks = chunkMap.get(chunk.filepath)?.chunks;
if (chunks) {
const index = chunks.findIndex((c) => c === chunk);
if (index !== -1) {
@ -142,6 +177,9 @@ export class LanceDbIndex implements CodebaseIndex {
item: PathAndCacheKey,
content: string,
): Promise<Chunk[]> {
if (!this.embeddingsProvider) {
return [];
}
const chunks: Chunk[] = [];
const chunkParams = {
@ -163,6 +201,9 @@ export class LanceDbIndex implements CodebaseIndex {
}
private async getEmbeddings(chunks: Chunk[]): Promise<number[][]> {
if (!this.embeddingsProvider) {
return [];
}
try {
return await this.embeddingsProvider.embed(chunks.map((c) => c.content));
} catch (err) {
@ -204,6 +245,7 @@ export class LanceDbIndex implements CodebaseIndex {
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const lance = LanceDbIndex.lance!;
const sqliteDb = await SqliteDb.get();
await this.createSqliteCacheTable(sqliteDb);
@ -211,15 +253,13 @@ export class LanceDbIndex implements CodebaseIndex {
const lanceDb = await lance.connect(getLanceDbPath());
const existingLanceTables = await lanceDb.tableNames();
let lanceTable: Table<number[]> | undefined = undefined;
let lanceTable: LanceType.Table<number[]> | undefined = undefined;
let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName);
// Compute
const addComputedLanceDbRows = async (
pathAndCacheKeys: PathAndCacheKey[],
computedRows: LanceDbRow[],
) => {
// Create table if needed, add computed rows
if (lanceTable) {
if (computedRows.length > 0) {
await lanceTable.add(computedRows);
@ -235,11 +275,9 @@ export class LanceDbIndex implements CodebaseIndex {
needToCreateLanceTable = false;
}
// Mark item complete
await markComplete(pathAndCacheKeys, IndexResultType.Compute);
};
// Check remote cache
if (this.continueServerClient?.connected) {
try {
const keys = results.compute.map(({ cacheKey }) => cacheKey);
@ -249,7 +287,6 @@ export class LanceDbIndex implements CodebaseIndex {
repoName,
);
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
// Get path for cacheKey
const path = results.compute.find(
(item) => item.cacheKey === cacheKey,
)?.path;
@ -261,7 +298,6 @@ export class LanceDbIndex implements CodebaseIndex {
continue;
}
// Build LanceDbRow objects
const rows: LanceDbRow[] = [];
for (const chunk of chunks) {
const row = {
@ -288,7 +324,6 @@ export class LanceDbIndex implements CodebaseIndex {
await addComputedLanceDbRows([{ cacheKey, path }], rows);
}
// Remove items that don't need to be recomputed
results.compute = results.compute.filter(
(item) => !resp.files[item.cacheKey],
);
@ -310,12 +345,10 @@ export class LanceDbIndex implements CodebaseIndex {
await addComputedLanceDbRows(results.compute, dbRows);
let accumulatedProgress = 0;
// Add tag - retrieve the computed info from lance sqlite cache
for (const { path, cacheKey } of results.addTag) {
const stmt = await sqliteDb.prepare(
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND artifact_id = ?",
cacheKey,
path,
this.artifactId,
);
const cachedItems = await stmt.all();
@ -354,7 +387,6 @@ export class LanceDbIndex implements CodebaseIndex {
};
}
// Delete or remove tag - remove from lance table)
if (!needToCreateLanceTable) {
const toDel = [...results.removeTag, ...results.del];
@ -363,7 +395,6 @@ export class LanceDbIndex implements CodebaseIndex {
}
for (const { path, cacheKey } of toDel) {
// This is where the aforementioned lowercase conversion problem shows
await lanceTable.delete(
`cachekey = '${cacheKey}' AND path = '${path}'`,
);
@ -379,7 +410,6 @@ export class LanceDbIndex implements CodebaseIndex {
await markComplete(results.removeTag, IndexResultType.RemoveTag);
// Delete - also remove from sqlite cache
for (const { path, cacheKey } of results.del) {
await sqliteDb.run(
"DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
@ -409,7 +439,7 @@ export class LanceDbIndex implements CodebaseIndex {
n: number,
directory: string | undefined,
vector: number[],
db: any, /// lancedb.Connection
db: any,
): Promise<LanceDbRow[]> {
const tableName = this.tableNameForTag(tag);
const tableNames = await db.tableNames();
@ -421,7 +451,6 @@ export class LanceDbIndex implements CodebaseIndex {
const table = await db.openTable(tableName);
let query = table.search(vector);
if (directory) {
// seems like lancedb is only post-filtering, so have to return a bunch of results and slice after
query = query.where(`path LIKE '${directory}%'`).limit(300);
} else {
query = query.limit(n);
@ -436,6 +465,10 @@ export class LanceDbIndex implements CodebaseIndex {
tags: BranchAndDir[],
filterDirectory: string | undefined,
): Promise<Chunk[]> {
const lance = LanceDbIndex.lance!;
if (!this.embeddingsProvider) {
return [];
}
const [vector] = await this.embeddingsProvider.embed([query]);
const db = await lance.connect(getLanceDbPath());

View file

@ -8,6 +8,7 @@ import Gemini from "../llm/llms/Gemini.js";
import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js";
import LMStudio from "../llm/llms/LMStudio.js";
import Mistral from "../llm/llms/Mistral.js";
import NCompass from "../llm/llms/NCompass.js";
import Nebius from "../llm/llms/Nebius.js";
import Nvidia from "../llm/llms/Nvidia.js";
import Ollama from "../llm/llms/Ollama.js";
@ -39,6 +40,7 @@ export const allEmbeddingsProviders: Record<
gemini: Gemini,
"continue-proxy": ContinueProxy,
deepinfra: DeepInfra,
ncompass: NCompass,
nvidia: Nvidia,
voyage: Voyage,
mistral: Mistral,

View file

@ -80,9 +80,9 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
`
INSERT INTO chunk_tags (chunkId, tag)
SELECT id, ? FROM chunks
WHERE cacheKey = ? AND path = ?
WHERE cacheKey = ?
`,
[tagString, item.cacheKey, item.path],
[tagString, item.cacheKey],
);
await markComplete([item], IndexResultType.AddTag);
accumulatedProgress += 1 / results.addTag.length / 4;
@ -158,7 +158,8 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
chunkId INTEGER NOT NULL,
FOREIGN KEY (chunkId) REFERENCES chunks (id)
FOREIGN KEY (chunkId) REFERENCES chunks (id),
UNIQUE (tag, chunkId)
)`);
}

View file

@ -1,142 +0,0 @@
import os from "os";
import { jest } from "@jest/globals";
import { ContinueConfig } from "../..";
import { testConfigHandler } from "../../test/fixtures";
import FileSystemIde from "../../util/filesystem";
import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler";
import preIndexedDocs from "./preIndexedDocs";
// Temporary workaround until we have better caching of Chromium
// download between test runs
const TIMEOUT_MS = 1_000_000_000;
// Overwrite the Chromium download path to `os.tmpdir()`
// so that we don't delete the Chromium install between tests
ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() };
// Skipped until we have a better way to cache Chromium installs
// between tests and in CI
describe.skip("DocsCrawler", () => {
const NUM_PAGES_TO_CRAWL = 5;
let config: ContinueConfig;
let mockIde: FileSystemIde;
let chromiumInstaller;
let docsCrawler: DocsCrawler;
beforeAll(async () => {
const result = await testConfigHandler.loadConfig();
config = result.config!;
mockIde = new FileSystemIde(process.cwd());
chromiumInstaller = new ChromiumInstaller(mockIde, config);
docsCrawler = new DocsCrawler(mockIde, config);
// Make sure we have Chromium pulled down before beginning tests
await chromiumInstaller.install();
}, TIMEOUT_MS);
function crawlTest(
urls: string[],
numPagesToCrawl: number = NUM_PAGES_TO_CRAWL,
) {
const numUrlsToTest = 5;
const randomUrls = urls
.sort(() => 0.5 - Math.random())
.slice(0, numUrlsToTest);
randomUrls.forEach((url) => {
it(
`Crawl test for ${url}`,
async () => {
const crawlResults: PageData[] = [];
for await (const page of docsCrawler.crawl(
new URL(url),
NUM_PAGES_TO_CRAWL,
)) {
crawlResults.push(page);
}
expect(crawlResults.length).toBeGreaterThanOrEqual(numPagesToCrawl);
},
TIMEOUT_MS,
);
});
}
describe("GitHub Crawler", () => {
const repoUrl =
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
let crawlResults: PageData[];
beforeAll(async () => {
crawlResults = [];
for await (const page of docsCrawler.crawl(new URL(repoUrl))) {
crawlResults.push(page);
}
}, TIMEOUT_MS);
test("finds expected markdown files", async () => {
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
true,
);
expect(
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
).toBe(true);
});
test("html includes the correct content", async () => {
const doc = crawlResults.find((page) =>
page.path.endsWith("docs-depth-1.md"),
);
expect(doc?.content.includes("Test body")).toBe(true);
expect(doc?.content.includes("Test H2 Header")).toBe(true);
});
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
false,
);
});
});
describe("Chromium Crawler", () => {
let shouldUseChromiumSpy: any;
beforeAll(() => {
shouldUseChromiumSpy = jest
.spyOn(docsCrawler as any, "shouldUseChromium")
.mockReturnValue(true);
});
afterAll(() => {
shouldUseChromiumSpy.mockRestore();
});
describe("Pre-indexed Docs", () => {
crawlTest(Object.keys(preIndexedDocs));
});
describe("Running list of common sites", () => {
crawlTest([
"https://docs.nestjs.com/",
"https://go.dev/doc/",
"https://clickhouse.com/docs",
"https://www.tensorflow.org/api_docs",
// "https://www.rust-lang.org/learn", TODO: This is failing
"https://docs.anthropic.com/en/docs",
]);
});
});
describe("Cheerio Crawler", () => {
crawlTest(["https://amplified.dev/"], 1);
});
});

View file

@ -1,100 +0,0 @@
import { URL } from "node:url";
// @ts-ignore
// @prettier-ignore
import { ContinueConfig, IDE } from "../..";
import CheerioCrawler from "./crawlers/CheerioCrawler";
import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler";
import { DefaultCrawler } from "./crawlers/DefaultCrawler";
import GitHubCrawler from "./crawlers/GitHubCrawler";
export type PageData = {
url: string;
path: string;
content: string;
};
class DocsCrawler {
private readonly MAX_REQUESTS_PER_CRAWL = 1000;
private readonly GITHUB_HOST = "github.com";
private readonly chromiumInstaller: ChromiumInstaller;
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config);
}
private shouldUseChromium() {
return (
this.config.experimental?.useChromiumForDocsCrawling &&
this.chromiumInstaller.isInstalled()
);
}
async *crawl(
startUrl: URL,
maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL,
): AsyncGenerator<PageData, undefined, undefined> {
if (startUrl.host === this.GITHUB_HOST) {
yield* new GitHubCrawler(startUrl).crawl();
return;
}
try {
const pageData = await new DefaultCrawler(startUrl).crawl();
if (pageData.length > 0) {
yield* pageData;
return;
}
} catch (e) {
console.error("Default crawler failed, trying backup: ", e);
}
if (this.shouldUseChromium()) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
let didCrawlSinglePage = false;
for await (const pageData of new CheerioCrawler(
startUrl,
maxRequestsPerCrawl,
).crawl()) {
yield pageData;
didCrawlSinglePage = true;
}
// We assume that if we failed to crawl a single page,
// it was due to an error that using Chromium can resolve
const shouldProposeUseChromium =
!didCrawlSinglePage &&
this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure();
if (shouldProposeUseChromium) {
const didInstall =
await this.chromiumInstaller.proposeAndAttemptInstall(
startUrl.toString(),
);
if (didInstall) {
void this.ide.showToast(
"info",
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
);
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
}
}
}
}
}
export default DocsCrawler;
export {
CheerioCrawler,
ChromiumCrawler,
ChromiumInstaller,
GitHubCrawler,
};

View file

@ -2,9 +2,7 @@
* @jest-environment jsdom
*/
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { SiteIndexingConfig } from "../../index.js";
import FreeTrial from "../../llm/llms/FreeTrial.js";
import FileSystemIde from "../../util/filesystem.js";
import { editConfigJson } from "../../util/paths.js";
@ -37,27 +35,21 @@ describe.skip("DocsService Integration Tests", () => {
beforeEach(async () => {
ide = new FileSystemIde(process.cwd());
const ideSettingsPromise = Promise.resolve({
remoteConfigSyncPeriod: 60,
userToken: "",
enableControlServerBeta: false,
continueTestEnvironment: "none" as const,
pauseCodebaseIndexOnStart: false,
ideSettings: {} as any,
enableDebugLogs: false,
remoteConfigServerUrl: "",
});
configHandler = new ConfigHandler(
ide,
Promise.resolve({
remoteConfigSyncPeriod: 60,
userToken: "",
enableControlServerBeta: false,
pauseCodebaseIndexOnStart: false,
ideSettings: {} as any,
enableDebugLogs: false,
remoteConfigServerUrl: "",
}),
ideSettingsPromise,
async () => {},
new ControlPlaneClient(
Promise.resolve({
accessToken: "",
account: {
id: "",
label: "",
},
}),
),
Promise.resolve(undefined),
);
docsService = DocsService.createSingleton(configHandler, ide);
@ -105,28 +97,28 @@ describe.skip("DocsService Integration Tests", () => {
expect(retrievedChunks.length).toBe(0);
});
test("Reindexes when changing embeddings provider", async () => {
const originalEmbeddingsProvider =
await docsService.getEmbeddingsProvider();
// test("Reindexes when changing embeddings provider", async () => {
// const originalEmbeddingsProvider =
// await docsService.getEmbeddingsProvider();
// Change embeddings provider
editConfigJson((config) => ({
...config,
embeddingsProvider: {
provider: FreeTrial.providerName,
},
}));
// // Change embeddings provider
// editConfigJson((config) => ({
// ...config,
// embeddingsProvider: {
// provider: FreeTrial.providerName,
// },
// }));
await getReloadedConfig();
// await getReloadedConfig();
const newEmbeddingsProvider = await docsService.getEmbeddingsProvider();
// const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
// Verify reindexing
const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
const [newMockVector] = await newEmbeddingsProvider.embed(["test"]);
// // Verify reindexing
// const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
// const [newMockVector] = await provider.embed(["test"]);
expect(originalVector).not.toEqual(newMockVector);
});
// expect(originalVector).not.toEqual(newMockVector);
// });
test("Handles pulling down and adding pre-indexed docs", async () => {
const preIndexedDoc = Object.values(preIndexedDocs)[0];

File diff suppressed because it is too large Load diff

View file

@ -2,9 +2,9 @@ import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { Chunk } from "../../";
import { cleanFragment, cleanHeader } from "../chunk/markdown";
import { cleanFragment, cleanHeader, markdownChunker } from "../chunk/markdown";
import { type PageData } from "./DocsCrawler";
import { type PageData } from "./crawlers/DocsCrawler";
export type ArticleComponent = {
title: string;
@ -18,6 +18,11 @@ export type Article = {
article_components: ArticleComponent[];
};
export type ArticleWithChunks = {
article: Article;
chunks: Chunk[];
};
function breakdownArticleComponent(
url: string,
article: ArticleComponent,
@ -99,78 +104,111 @@ function breakdownArticleComponent(
return chunks.filter((c) => c.content.trim().length > 20);
}
export function chunkArticle(
articleResult: Article,
maxChunkSize: number,
): Chunk[] {
let chunks: Chunk[] = [];
function chunkArticle(article: Article, maxChunkSize: number): Chunk[] {
const chunks: Chunk[] = [];
for (const article of articleResult.article_components) {
for (const component of article.article_components) {
const articleChunks = breakdownArticleComponent(
articleResult.url,
article,
articleResult.subpath,
article.url,
component,
article.subpath,
maxChunkSize,
);
chunks = [...chunks, ...articleChunks];
chunks.push(...articleChunks);
}
return chunks;
}
function extractTitlesAndBodies(html: string): ArticleComponent[] {
const dom = new JSDOM(html);
const document = dom.window.document;
const titles = Array.from(document.querySelectorAll("h2"));
const result = titles.map((titleElement) => {
const title = titleElement.textContent || "";
let body = "";
let nextSibling = titleElement.nextElementSibling;
while (nextSibling && nextSibling.tagName !== "H2") {
body += nextSibling.textContent || "";
nextSibling = nextSibling.nextElementSibling;
}
return { title, body };
});
return result;
}
export function stringToArticle(
url: string,
html: string,
subpath: string,
): Article | undefined {
export async function htmlPageToArticleWithChunks(
page: PageData,
maxChunkSize: number,
): Promise<ArticleWithChunks | undefined> {
try {
const html = page.content;
const subpath = page.path;
const url = page.url;
const dom = new JSDOM(html);
const reader = new Readability(dom.window.document);
const article = reader.parse();
const readability = reader.parse();
if (!readability) {
console.error("Docs indexing: Error getting readability for URL", url);
if (!article) {
return undefined;
}
const article_components = extractTitlesAndBodies(article.content);
const title = readability.title || subpath;
return {
const titles = Array.from(dom.window.document.querySelectorAll("h2"));
const article_components =
titles.length > 0
? titles.map((titleElement) => {
const title = titleElement.textContent || "";
let body = "";
let nextSibling = titleElement.nextElementSibling;
while (nextSibling && nextSibling.tagName !== "H2") {
body += nextSibling.textContent || "";
nextSibling = nextSibling.nextElementSibling;
}
return { title, body };
})
: [
{
title: title,
body: readability.textContent,
},
];
const article = {
url,
subpath,
title: article.title,
title: title,
article_components,
};
return {
article,
chunks: chunkArticle(article, maxChunkSize),
};
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;
}
}
export function pageToArticle(page: PageData): Article | undefined {
export async function markdownPageToArticleWithChunks(
page: PageData,
maxChunkSize: number,
): Promise<ArticleWithChunks | undefined> {
try {
return stringToArticle(page.url, page.content, page.path);
let index = 0;
const chunks: Chunk[] = [];
const chunker = markdownChunker(page.content, maxChunkSize, 1);
for await (const chunk of chunker) {
const fullUrl = new URL(page.url);
fullUrl.hash = `#${cleanFragment(chunk.otherMetadata?.title)}`;
chunks.push({
...chunk,
index,
filepath: fullUrl.toString(),
digest: fullUrl.toString(),
});
index++;
}
return {
article: {
url: page.url,
subpath: page.path,
article_components: [], // TODO: markdown chunker just skips this for now since not used outside, only for html chunker
title: chunks[0]?.otherMetadata?.title || page.path,
},
chunks,
};
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;
console.error(`Docs indexing: failed to chunk markdown from ${page.url}`);
}
}

View file

@ -2,7 +2,7 @@ import { URL } from "node:url";
import * as cheerio from "cheerio";
import { PageData } from "../DocsCrawler";
import { PageData } from "./DocsCrawler";
export default class CheerioCrawler {
private readonly IGNORE_PATHS_ENDING_IN = [
@ -21,23 +21,18 @@ export default class CheerioCrawler {
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
private readonly maxDepth: number,
) {}
async *crawl(): AsyncGenerator<PageData> {
yield* this.crawlPage(this.startUrl);
}
private async *crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
let currentPageCount = 0;
console.log(
`[${
(this.constructor as any).name
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
}] Starting crawl from: ${this.startUrl} - Max Depth: ${this.maxDepth}`,
);
const { baseUrl, basePath } = this.splitUrl(url);
const { baseUrl, basePath } = this.splitUrl(this.startUrl);
let paths: { path: string; depth: number }[] = [
{ path: basePath, depth: 0 },
@ -63,11 +58,16 @@ export default class CheerioCrawler {
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
yield { url: url.toString(), path, content: html };
if (html !== "" && depth <= this.maxDepth) {
yield { url: this.startUrl.toString(), path, content: html };
currentPageCount++;
if (currentPageCount >= this.maxRequestsPerCrawl) {
console.log("Crawl completed - max requests reached");
return;
}
}
if (depth < maxDepth) {
if (depth < this.maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 });

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