Merge branch 'main' into venice

This commit is contained in:
Nate 2025-04-29 12:52:20 -07:00
commit a9ec23896f
1097 changed files with 57650 additions and 23727 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

@ -5,4 +5,5 @@ docs/docs/languages
.vscode/
.archive/
**/*.scm
**/*.diff
**/*.diff
.continue/

1
.github/CODEOWNERS vendored Normal file
View file

@ -0,0 +1 @@
* @continuedev/continue-code-reviewers

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

@ -4,12 +4,13 @@
## Checklist
- [] I've read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md)
- [] The relevant docs, if any, have been updated or created
- [] The relevant tests, if any, have been updated or created
## Screenshots
[ For visual changes, include screenshots. ]
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
## Testing instructions

70
.github/workflows/auto-release.yml vendored Normal file
View file

@ -0,0 +1,70 @@
name: Create Automatic Release
on:
push:
branches:
- nate/auto-main-release-draft
schedule:
- cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday
workflow_dispatch: # Keep manual trigger option
jobs:
create-vscode-release:
runs-on: ubuntu-latest
permissions:
contents: write # Needed for creating releases
steps:
- uses: actions/checkout@v4
- name: Get version from package.json
id: get_version
run: |
# Read version from package.json and add -vscode suffix
version=$(node -p "require('./extensions/vscode/package.json').version")
new_version="v${version}-vscode"
echo "New version will be: $new_version"
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
- name: Create Release
env:
GH_TOKEN: ${{ github.token }}
run: |
# Create a new draft release with auto-generated release notes
gh release create "$NEW_VERSION" \
--generate-notes \
--title "$NEW_VERSION" \
--draft \
--latest \
--prerelease
create-jetbrains-release:
runs-on: ubuntu-latest
permissions:
contents: write # Needed for creating releases
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get version from gradle.properties
id: get_version
run: |
# Read version from gradle.properties and add -jetbrains suffix
version=$(grep '^pluginVersion=' extensions/intellij/gradle.properties | cut -d'=' -f2)
new_version="v${version}-jetbrains"
echo "New version will be: $new_version"
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
- name: Create Release
env:
GH_TOKEN: ${{ github.token }}
run: |
# Create a new draft release with auto-generated release notes
gh release create "$NEW_VERSION" \
--generate-notes \
--title "$NEW_VERSION" \
--draft \
--latest \
--prerelease

View file

@ -31,12 +31,58 @@ 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
fi
bump-version:
runs-on: ubuntu-latest
needs:
- check_release_name
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
pull-requests: write
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
- name: Set up Git
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
- name: Create PR branch
run: |
BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)"
git checkout -b $BRANCH_NAME
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
- name: Bump version in gradle.properties
run: |
cd extensions/intelllij
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
with:
token: ${{ secrets.CI_GITHUB_TOKEN }}
commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
body: |
Automated PR to bump the JetBrains extension version after successful pre-release publication.
- Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }}
branch: ${{ env.BRANCH_NAME }}
base: main
delete-branch: true
# Prepare and publish the plugin to JetBrains Marketplace repository
build:
needs: check_release_name
@ -54,7 +100,7 @@ jobs:
ref: ${{ github.event.release.tag_name }}
- name: Import Apple certificate
uses: apple-actions/import-codesign-certs@v3
uses: apple-actions/import-codesign-certs@v5
with:
keychain: ${{ github.run_id }}
keychain-password: ${{ github.run_id }}
@ -121,6 +167,21 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build and check config-yaml
run: |
cd ../../packages/config-yaml
npm i
npx tsc --noEmit
# Tests are currently failing, commenting out for now
# npm test
npm run build
# npm install core
- name: Install core node_modules
run: |
@ -420,7 +481,7 @@ jobs:
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2024.3.2
uses: JetBrains/qodana-action@v2025.1.0
with:
cache-default-branch-only: true

View file

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

View file

@ -1,5 +1,6 @@
name: PR checks
# PR Checks run on all PRs to the main branch and must pass before merging.
on:
pull_request:
branches:
@ -29,6 +30,62 @@ jobs:
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
install-config-yaml:
needs: install-root
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Install config-yaml dependencies
if: steps.config-yaml-cache.outputs.cache-hit != 'true'
run: |
cd packages/config-yaml
npm ci
config-yaml-checks:
needs: install-config-yaml
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build and check config-yaml
run: |
cd packages/config-yaml
npx tsc --noEmit
# Tests are currently failing, commenting out for now
# npm test
npm run build
install-core:
needs: install-root
runs-on: ubuntu-latest
@ -58,7 +115,7 @@ jobs:
npm ci
core-checks:
needs: install-core
needs: [install-core, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -79,6 +136,17 @@ jobs:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Type check and lint
run: |
cd core
@ -88,7 +156,7 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
install-gui:
needs: [install-root, install-core]
needs: [install-root, install-core, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -113,6 +181,17 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Install gui dependencies
if: steps.gui-cache.outputs.cache-hit != 'true'
run: |
@ -145,13 +224,24 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Type check
run: |
cd gui
npx tsc --noEmit
binary-checks:
needs: [install-root, install-core]
needs: [install-root, install-core, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -176,6 +266,17 @@ jobs:
path: binary/node_modules
key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Install binary dependencies
if: steps.binary-cache.outputs.cache-hit != 'true'
run: |
@ -188,7 +289,7 @@ jobs:
npx tsc --noEmit
install-vscode:
needs: [install-root, install-core]
needs: [install-root, install-core, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -213,6 +314,17 @@ jobs:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Install vscode dependencies
if: steps.vscode-cache.outputs.cache-hit != 'true'
run: |
@ -247,14 +359,26 @@ jobs:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Type check and lint
run: |
cd extensions/vscode
npm run write-build-timestamp
npx tsc --noEmit
npm run lint
core-tests:
needs: install-core
needs: [install-core, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -268,12 +392,23 @@ jobs:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Run core tests
run: |
cd core
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }}
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 }}
@ -281,9 +416,33 @@ jobs:
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
package-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Install dependencies
run: |
cd packages/config-yaml
npm ci
- name: Run config-yaml tests
run: |
cd packages/config-yaml
npm test
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode]
needs: [install-root, install-vscode, install-config-yaml]
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
@ -295,13 +454,30 @@ jobs:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Get test files
id: vscode-get-test-file-matrix
run: |
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
@ -312,7 +488,7 @@ jobs:
vscode-package-extension:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [install-vscode, install-core, install-config-yaml]
steps:
- uses: actions/checkout@v4
@ -332,6 +508,17 @@ jobs:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Package extension
run: |
cd extensions/vscode
@ -345,7 +532,7 @@ jobs:
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [install-vscode, install-core, install-config-yaml]
steps:
- uses: actions/checkout@v4
@ -365,6 +552,17 @@ jobs:
path: extensions/vscode/e2e/storage
key: ${{ runner.os }}-vscode-storage-${{ hashFiles('extensions/vscode/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Download Dependencies
if: steps.storage-cache.outputs.cache-hit != 'true'
run: |
@ -378,7 +576,7 @@ jobs:
path: extensions/vscode/e2e/storage
vscode-e2e-tests:
name: ${{ matrix.test_file }} (${{ matrix.command }})
name: ${{ matrix.test_file || 'unknown' }} (${{ matrix.command }})
needs:
[
vscode-download-e2e-dependencies,
@ -386,6 +584,7 @@ jobs:
vscode-package-extension,
install-vscode,
install-core,
install-config-yaml,
]
runs-on: ubuntu-latest
# Tests requiring secrets need approval from maintainers
@ -407,6 +606,13 @@ 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
key: CONSTANT
- name: Download build artifact
uses: actions/download-artifact@v4
with:
@ -419,6 +625,17 @@ jobs:
name: vscode-e2e-dependencies
path: extensions/vscode/e2e/storage
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Fix VSCode binary permissions
run: |
chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code
@ -434,7 +651,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 }}
if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}
- name: Set up Xvfb
run: |
@ -444,10 +661,15 @@ jobs:
- name: Run e2e tests
run: |
cd extensions/vscode
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || 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
@ -455,8 +677,29 @@ jobs:
name: e2e-failure-screenshots
path: extensions/vscode/e2e/storage/screenshots
- name: Sanitize test file name
id: sanitize_filename
if: always()
run: |
FILENAME="${{ matrix.test_file }}"
SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion
echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT
- name: Find e2e log file
if: always()
run: |
echo "Searching for e2e.log file..."
find $GITHUB_WORKSPACE -name "e2e.log" -type f
- name: Upload e2e logs
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
path: extensions/vscode/e2e.log
gui-tests:
needs: [install-gui, install-core]
needs: [install-gui, install-core, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -476,6 +719,17 @@ jobs:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Install GUI dependencies
if: steps.gui-cache.outputs.cache-hit != 'true'
run: cd gui && npm ci
@ -488,7 +742,7 @@ jobs:
npm test
jetbrains-tests:
needs: [install-root, core-checks]
needs: [install-root, core-checks, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -497,6 +751,17 @@ jobs:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Setup Java
uses: actions/setup-java@v4.5.0
with:
@ -601,17 +866,18 @@ jobs:
- install-vscode
- vscode-checks
- core-tests
- package-tests
- vscode-get-test-file-matrix
- vscode-package-extension
- vscode-download-e2e-dependencies
- vscode-e2e-tests
- gui-tests
- jetbrains-tests
- config-yaml-checks
- install-config-yaml
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

@ -1,4 +1,4 @@
name: Publish Preview Extension
name: Publish Pre-release Extension
on:
release:
@ -20,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
@ -207,6 +207,7 @@ jobs:
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
pull-requests: write
steps:
# 0. Setup git
- name: Checkout
@ -217,8 +218,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
@ -242,12 +243,44 @@ jobs:
cd extensions/vscode
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
# 4. Update the package.json version and push changes
# 4. Create PR with version bump
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Create PR branch
run: |
BRANCH_NAME="chore/bump-vscode-version-$(date +%Y%m%d-%H%M%S)"
git checkout -b $BRANCH_NAME
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
- name: Bump version in package.json
run: |
cd extensions/vscode
npm version patch --no-git-tag-version
VERSION=$(node -p "require('./package.json').version")
echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
with:
token: ${{ secrets.CI_GITHUB_TOKEN }}
commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
title: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
body: |
Automated PR to bump the VS Code extension version after successful pre-release publication.
- Bumped version in extensions/vscode/package.json to ${{ env.NEW_VERSION }}
branch: ${{ env.BRANCH_NAME }}
base: main
delete-branch: true
# 5. Update version in package.json
# - name: Update version in package.json
# run: |
# cd extensions/vscode
# npm version patch
# - name: Commit changes
# run: |
# git config --local user.email "action@github.com"

View file

@ -0,0 +1,46 @@
name: Release @continuedev/config-yaml
on:
push:
branches:
- main
paths:
- "packages/config-yaml/**"
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Install dependencies
run: |
cd packages/config-yaml
npm ci
- name: Build
run: |
cd packages/config-yaml
npm run build
- name: Run tests
run: |
cd packages/config-yaml
npm test
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
cd packages/config-yaml
npx semantic-release

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"

View file

@ -0,0 +1,124 @@
name: Create VS Code main release draft
on:
schedule:
# Runs at 7 AM PST (15:00 UTC) every Friday
- cron: "0 15 * * 5"
workflow_dispatch:
# Allows manual triggering
jobs:
version-bump:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch all history and tags
- name: Setup GitHub CLI
run: |
gh auth login --with-token <<< "${{ github.token }}"
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Find and process version tags
run: |
echo "Starting version bump process..."
# Find last v1.1.x-vscode tag that's at least 6 days old
CURRENT_TIMESTAMP=$(date +%s)
SIX_DAYS_AGO=$((CURRENT_TIMESTAMP - 6*24*60*60))
echo "Current timestamp: $(date -d @${CURRENT_TIMESTAMP})"
echo "Six days ago: $(date -d @${SIX_DAYS_AGO})"
echo "Looking for v1.1.x-vscode tags..."
git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:iso)' refs/tags | grep 'v1\.1\.[0-9]\+-vscode' || echo "No matching tags found"
LAST_1_1_TAG=$(git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:unix)' refs/tags \
| grep 'v1\.1\.[0-9]\+-vscode' \
| while read tag timestamp; do
if [ $timestamp -le $SIX_DAYS_AGO ]; then
echo ${tag% *}
break
fi
done)
echo "Selected v1.1.x tag: $LAST_1_1_TAG"
if [ -z "$LAST_1_1_TAG" ]; then
echo "::error::No suitable v1.1.x-vscode tag found"
exit 1
fi
# Find last v1.0.y-vscode tag
echo "Looking for v1.0.y-vscode tags..."
git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' || echo "No matching tags found"
LAST_1_0_TAG=$(git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' | head -n1)
echo "Selected v1.0.y tag: $LAST_1_0_TAG"
if [ -z "$LAST_1_0_TAG" ]; then
echo "::error::No v1.0.y-vscode tag found"
exit 1
fi
# Extract the y number and increment it
Y_NUMBER=$(echo $LAST_1_0_TAG | sed 's/v1\.0\.\([0-9]\+\)-vscode/\1/')
NEXT_Y=$((Y_NUMBER + 1))
NEW_BRANCH="v1.0.${NEXT_Y}-vscode"
NEW_VERSION="1.0.${NEXT_Y}"
echo "Current Y number: $Y_NUMBER"
echo "Next Y number: $NEXT_Y"
echo "New branch name: $NEW_BRANCH"
echo "New version: $NEW_VERSION"
# Create new branch from the v1.1.x tag
echo "Creating new branch from $LAST_1_1_TAG..."
git checkout $LAST_1_1_TAG
git checkout -b $NEW_BRANCH
# Update the version in package.json
echo "Current package.json version:"
cat extensions/vscode/package.json | grep version
echo "Updating version in package.json..."
jq ".version = \"$NEW_VERSION\"" extensions/vscode/package.json > temp.json && mv temp.json extensions/vscode/package.json
echo "New package.json version:"
cat extensions/vscode/package.json | grep version
# Configure git
echo "Configuring git..."
git config user.name "GitHub Actions Bot"
git config user.email "actions@github.com"
# Commit and push changes
echo "Committing changes..."
git add extensions/vscode/package.json
git commit -m "Bump VS Code extension to ${NEW_VERSION}"
echo "Pushing branch to origin..."
git push origin $NEW_BRANCH
# Add release creation
echo "Creating draft release..."
gh release create "${NEW_BRANCH}" \
--title "${NEW_BRANCH}" \
--generate-notes \
--draft \
--latest \
--notes-start-tag "${LAST_1_0_TAG}"
echo "Version bump process completed successfully!"
- name: Check for errors
if: failure()
run: |
echo "::error::Failed to process version tags and create new branch"
echo "Last few lines of git log:"
git log -n 5 --oneline
echo "Current git status:"
git status
echo "Current branches:"
git branch -a

17
.gitignore vendored
View file

@ -83,16 +83,6 @@ ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
@ -157,15 +147,20 @@ Icon?
notes.md
manual-testing-sandbox/.idea/**
manual-testing-sandbox/.continue/**
extensions/intellij/.idea/**
**/.idea/workspace.xml
**/.idea/usage.statistics.xml
**/.idea/shelf/
**/.idea/inspectionProfiles/Project_Default.xml
**/.idea/php.xml
extensions/intellij/bin
extensions/.continue-debug/
*.vsix
.continuerules
.continuerules
**/.continue/assistants/

3
.idea/compiler.xml generated
View file

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

1
.idea/gradle.xml generated
View file

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

View file

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

1
.node-version Normal file
View file

@ -0,0 +1 @@
20.19.0

2
.nvmrc
View file

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

View file

@ -14,4 +14,5 @@ gui/dist
**/.continueignore
CHANGELOG.md
**/continue_tutorial.py
**/node_modules
**/node_modules
**/CODEOWNERS

19
.vscode/launch.json vendored
View file

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

36
.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",

View file

@ -20,13 +20,14 @@
- [Debugging](#debugging)
- [JetBrains](#jetbrains)
- [Our Git Workflow](#our-git-workflow)
- [Testing](#testing)
- [Development workflow](#development-workflow)
- [Formatting](#formatting)
- [Writing Slash Commands](#writing-slash-commands)
- [Writing Context Providers](#writing-context-providers)
- [Testing](#testing)
- [Review Process](#review-process)
- [Getting help](#getting-help)
- [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
- [Adding an LLM Provider](#adding-an-llm-provider)
- [Adding Models](#adding-models)
- [Adding Pre-indexed Documentation](#adding-pre-indexed-documentation)
- [📐 Continue Architecture](#-continue-architecture)
- [Continue VS Code Extension](#continue-vs-code-extension)
- [Continue JetBrains Extension](#continue-jetbrains-extension)
@ -95,11 +96,13 @@ This will start a local server and you can see the documentation rendered in you
## 🧑‍💻 Contributing Code
We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the process as welcoming and straightforward as possible.
### Environment Setup
#### Pre-requisites
You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
```bash
nvm use
@ -128,7 +131,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
@ -140,51 +143,41 @@ Similarly, any changes to `core` or `extensions/vscode` will be automatically in
#### JetBrains
See the [`CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBrains extension.
See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBrains extension.
### Our Git Workflow
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v0.9.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v0.8.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by <http://releaseflow.org>.
### Testing
### Development workflow
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you resolve the issue before we merge.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned with the project direction.
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
- Write or update tests for new functionality
- Update relevant documentation in the `docs` folder
- Open a PR against the `main` branch. Make sure to fill in the PR template
### Formatting
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
### Writing Slash Commands
### Testing
The slash command interface, defined in [core/index.d.ts](./core/index.d.ts), requires you to define a `name` (the text that will be typed to invoke the command), a `description` (the text that will be shown in the slash command menu), and a `run` function that will be called when the command is invoked. The `run` function is an async generator that yields the content to be displayed in the chat. The `run` function is passed a `ContinueSDK` object that can be used to interact with the IDE, call the LLM, and see the chat history, among a few other utilities.
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge.
```ts
export interface SlashCommand {
name: string;
description: string;
params?: { [key: string]: any };
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
}
```
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
There are many example of slash commands in [core/commands/slash](./core/commands/slash) that we recommend borrowing from. Once you've created your new `SlashCommand` in this folder, also be sure to complete the following:
### Review Process
- Add your command to the array in [core/commands/slash/index.ts](./core/commands/slash/index.ts)
- Add your command to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what commands are available for your provider when they are editing `config.json`. If there are any parameters that your command accepts, you should also follow existing examples in adding them to the JSON Schema.
- **Initial Review** - A maintainer will be assigned as primary reviewer
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is maintainable and follows our patterns.
- **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
### Writing Context Providers
### Getting help
A `ContextProvider` is a Continue plugin that lets type '@' to quickly select documents as context for the language model. The `IContextProvider` interface is defined in [`core/index.d.ts`](./core/index.d.ts), but all built-in context providers extend [`BaseContextProvider`](./core/context/index.ts).
Join [#contribute on Discord](https://discord.gg/vapESyrFmJ) to engage with maintainers and other contributors.
Before defining your context provider, determine which "type" you want to create. The `"query"` type will show a small text input when selected, giving the user the chance to enter something like a Google search query for the [`GoogleContextProvider`](./core/context/providers/GoogleContextProvider.ts). The `"submenu"` type will open up a submenu of items that can be searched through and selected. Examples are the [`GitHubIssuesContextProvider`](./core/context/providers/GitHubIssuesContextProvider.ts) and the [`DocsContextProvider`](./core/context/providers/DocsContextProvider.ts). The `"normal"` type will just immediately add the context item. Examples include the [`DiffContextProvider`](./core/context/providers/DiffContextProvider.ts) and the [`OpenFilesContextProvider`](./core/context/providers/OpenFilesContextProvider.ts).
After you've written your context provider, make sure to complete the following:
- Add it to the array of context providers in [core/context/providers/index.ts](./core/context/providers/index.ts)
- Add it to the `ContextProviderName` type in [core/index.d.ts](./core/index.d.ts)
- Add it to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). If there are any parameters that your context provider accepts, you should also follow existing examples in adding them to the JSON Schema.
## Contribtuing new LLM Providers/Models
### Adding an LLM Provider
@ -212,17 +205,13 @@ While any model that works with a supported provider can be used with Continue,
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
### Adding Pre-indexed Documentation
Continue's @docs context provider lets you easily reference entire documentation sites and then uses embeddings to add the most relevant pages to context. To make the experience as smooth as possible, we pre-index many of the most popular documentation sites. If you'd like to add new documentation to this list, just add an object to the list in [preIndexedDocs.ts](./core/indexing/docs/preIndexedDocs.ts). `startUrl` is where the crawler will start and `rootUrl` will filter out any pages not on that site and under the path of `rootUrl`.
## 📐 Continue Architecture
Continue consists of 2 parts that are split so that it can be extended to work in other IDEs as easily as possible:
1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs.
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/ideProtocol.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/VsCodeIde.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
### Continue VS Code Extension

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 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>
@ -44,11 +44,11 @@
![edit](docs/static/img/edit.gif)
## Actions
## Agent
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases.
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![actions](docs/static/img/actions.gif)
![agent](docs/static/img/agent.gif)
</div>
@ -58,7 +58,7 @@ Learn about how to install and use Continue in the docs [here](https://continue.
## Contributing
Check out the [contribution ideas board](https://github.com/orgs/continuedev/projects/2), read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ)
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
## License

View file

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

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

@ -41,20 +41,20 @@
},
"../core": {
"name": "@continuedev/core",
"version": "1.0.13",
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.28",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@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",
@ -67,6 +67,7 @@
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
"filtrex": "^3.1.0",
"follow-redirects": "^1.15.5",
"google-auth-library": "^9.14.2",
"handlebars": "^4.7.8",
@ -105,15 +106,16 @@
"web-tree-sitter": "^0.21.0",
"win-ca": "^3.5.1",
"wink-nlp-utils": "^2.1.0",
"winston": "^3.17.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"
"zod": "^3.24.2"
},
"devDependencies": {
"@babel/preset-env": "^7.24.7",
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@types/diff": "^5.2.2",
"@types/diff": "^7.0.1",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
@ -128,17 +130,18 @@
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"cross-env": "^7.0.3",
"esbuild": "0.24.0",
"esbuild": "0.17.19",
"eslint": "^8",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"ts-jest": "^29.1.1"
"ts-jest": "^29.1.1",
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"node_modules/@75lb/deep-merge": {
@ -2084,9 +2087,10 @@
}
},
"node_modules/@octokit/endpoint": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.5.tgz",
"integrity": "sha512-ekqR4/+PCLkEBF6qgj8WqJfvDq65RH85OAgrtnVp1mSxaXF03u2xW/hUdweGS5654IlC0wkNYC18Z50tSYTAFw==",
"version": "9.0.6",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz",
"integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==",
"license": "MIT",
"dependencies": {
"@octokit/types": "^13.1.0",
"universal-user-agent": "^6.0.0"
@ -2153,12 +2157,13 @@
}
},
"node_modules/@octokit/request": {
"version": "8.4.0",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.0.tgz",
"integrity": "sha512-9Bb014e+m2TgBeEJGEbdplMVWwPmL1FPtggHQRkV+WVsMggPtEkLKPlcVYm/o8xKLkpJ7B+6N8WfQMtDLX2Dpw==",
"version": "8.4.1",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz",
"integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==",
"license": "MIT",
"dependencies": {
"@octokit/endpoint": "^9.0.1",
"@octokit/request-error": "^5.1.0",
"@octokit/endpoint": "^9.0.6",
"@octokit/request-error": "^5.1.1",
"@octokit/types": "^13.1.0",
"universal-user-agent": "^6.0.0"
},
@ -2167,9 +2172,10 @@
}
},
"node_modules/@octokit/request-error": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.0.tgz",
"integrity": "sha512-GETXfE05J0+7H2STzekpKObFe765O5dlAKUTLNGeH+x47z7JjXHfsHKo5z21D/o/IOZTUEI6nyWyR+bZVP/n5Q==",
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz",
"integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==",
"license": "MIT",
"dependencies": {
"@octokit/types": "^13.1.0",
"deprecation": "^2.0.0",
@ -6404,10 +6410,11 @@
}
},
"node_modules/tar-fs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
"integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
"dev": true,
"license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",

View file

@ -23,6 +23,7 @@
"scripts": {
"test": "jest",
"build": "node build.js",
"rebuild": "node build.js --esbuild-only",
"build:darwin-x64": "node build.js --os darwin-x64"
},
"license": "Apache-2.0",

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

@ -1,6 +1,7 @@
process.env.IS_BINARY = "true";
import { Command } from "commander";
import { Core } from "core/core";
import { LLMLogFormatter } from "core/llm/logFormatter";
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
import { IMessenger } from "core/protocol/messenger";
import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths";
@ -33,9 +34,8 @@ program.action(async () => {
const ide = new IpcIde(messenger);
const promptLogsPath = getPromptLogsPath();
new Core(messenger, ide, async (text) => {
fs.appendFileSync(promptLogsPath, text + "\n\n");
});
const core = new Core(messenger, ide);
new LLMLogFormatter(core.llmLogger, fs.createWriteStream(promptLogsPath));
console.log("[binary] Core started");
} catch (e) {

View file

@ -234,15 +234,17 @@ describe("Test Suite", () => {
result: { config },
} = await messenger.request("config/getSerializedProfileInfo", undefined);
expect(config!.models.some((m) => m.title === model.title)).toBe(true);
expect(config!.modelsByRole.chat.some((m) => m.title === model.title)).toBe(
true,
);
await messenger.request("config/deleteModel", { title: model.title });
const {
result: { config: configAfterDelete },
} = await messenger.request("config/getSerializedProfileInfo", undefined);
expect(configAfterDelete!.models.some((m) => m.title === model.title)).toBe(
false,
);
expect(
configAfterDelete!.modelsByRole.chat.some((m) => m.title === model.title),
).toBe(false);
});
it("should make an LLM completion", async () => {

View file

@ -5,8 +5,18 @@
"project": "./tsconfig.json"
},
"rules": {
"quotes": ["warn", "double", {}],
"quotes": ["off", "double", {}],
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-floating-promises": "warn"
"@typescript-eslint/no-floating-promises": "off",
"import/order": "off",
"curly": "off",
"@typescript-eslint/semi": "off",
"eqeqeq": "error",
"complexity": ["error", { "max": 36 }],
"max-lines-per-function": ["error", { "max": 500 }],
"max-statements": ["error", { "max": 108 }],
"max-depth": ["error", { "max": 6 }],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-params": ["error", { "max": 8 }]
}
}

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();
@ -147,6 +154,10 @@ export class CompletionProvider {
return undefined;
}
if (llm.promptTemplates?.autocomplete) {
options.template = llm.promptTemplates.autocomplete as string;
}
const helper = await HelperVars.create(
input,
options,
@ -158,14 +169,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,

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

@ -5,6 +5,7 @@ import {
getParserForFile,
getQueryForFile,
} from "../../util/treeSitter";
import { findUriInDirs } from "../../util/uri";
interface FileInfo {
imports: { [key: string]: RangeInFileWithContents[] };
@ -44,7 +45,15 @@ export class ImportDefinitionsService {
let fileContents: string | undefined = undefined;
try {
fileContents = await this.ide.readFile(filepath);
const { foundInDir } = findUriInDirs(
filepath,
await this.ide.getWorkspaceDirs(),
);
if (!foundInDir) {
return null;
} else {
fileContents = await this.ide.readFile(filepath);
}
} catch (err) {
// File removed
return null;

View file

@ -88,7 +88,6 @@ export class RootPathContextService {
default:
// const type = node.type;
// console.log(getSyntaxTreeString(node));
// debugger;
query = await getQueryForFile(
filepath,
@ -165,7 +164,6 @@ export class RootPathContextService {
)) {
const key = RootPathContextService.keyFromNode(parentKey, astNode);
// const type = astNode.type;
// debugger;
const foundInCache = this.cache.get(key);
const newSnippets =

View file

@ -1,5 +1,4 @@
import { streamLines } from "../../../diff/util";
import { PosthogFeatureFlag, Telemetry } from "../../../util/posthog";
import { HelperVars } from "../../util/HelperVars";
import { stopAtStartOf, stopAtStopTokens } from "./charStream";
@ -73,9 +72,7 @@ export class StreamTransformPipeline {
fullStop,
);
const timeoutValue = await Telemetry.getValueForFeatureFlag(
PosthogFeatureFlag.AutocompleteTimeout,
);
const timeoutValue = helper.options.showWhateverWeHaveAtXMs;
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);

View file

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

View file

@ -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,6 +113,17 @@ const getClipboardSnippets = async (
const getDiffSnippets = async (
ide: IDE,
): Promise<AutocompleteDiffSnippet[]> => {
const currentTimestamp = ide.getLastFileSaveTimestamp ?
ide.getLastFileSaveTimestamp() :
Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
// Check cache first
const cached = diffSnippetsCache.get(currentTimestamp) as AutocompleteDiffSnippet[];
if (cached) {
return cached;
}
let diff: string[] = [];
try {
diff = await ide.getDiff(true);
@ -97,12 +131,13 @@ const getDiffSnippets = async (
console.error("Error getting diff for autocomplete", e);
}
return diff.map((item) => {
return diffSnippetsCache.set(currentTimestamp, diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
});
}));
};
export const getAllSnippets = async ({
@ -127,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

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

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

View file

@ -39,20 +39,28 @@ export class AutocompleteLruCache {
// If the query is "co" and we have "c" -> "ontinue" in the cache,
// we should return "ntinue" as the completion.
// Have to make sure we take the key with shortest length
const result = await this.db.get(
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
truncateSqliteLikePattern(prefix),
);
// Validate that the cached compeltion is a valid completion for the prefix
if (result && result.value.startsWith(prefix.slice(result.key.length))) {
await this.db.run(
"UPDATE cache SET timestamp = ? WHERE key = ?",
Date.now(),
prefix,
const truncatedPrefix = truncateSqliteLikePattern(prefix);
try {
const result = await this.db.get(
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
truncatedPrefix,
);
// And then truncate so we aren't writing something that's already there
return result.value.slice(prefix.length - result.key.length);
// Validate that the cached completion is a valid completion for the prefix
if (
result &&
result.value.startsWith(truncatedPrefix.slice(result.key.length))
) {
await this.db.run(
"UPDATE cache SET timestamp = ? WHERE key = ?",
Date.now(),
truncatedPrefix,
);
// And then truncate so we aren't writing something that's already there
return result.value.slice(truncatedPrefix.length - result.key.length);
}
} catch (e) {
// catches e.g. old SQLITE LIKE OR GLOB PATTERN TOO COMPLEX
console.error(e);
}
return undefined;
@ -60,13 +68,15 @@ export class AutocompleteLruCache {
async put(prefix: string, completion: string) {
const release = await this.mutex.acquire();
const truncatedPrefix = truncateSqliteLikePattern(prefix);
try {
await this.db.run("BEGIN TRANSACTION");
try {
const result = await this.db.get(
"SELECT key FROM cache WHERE key = ?",
prefix,
truncatedPrefix,
);
if (result) {
@ -74,7 +84,7 @@ export class AutocompleteLruCache {
"UPDATE cache SET value = ?, timestamp = ? WHERE key = ?",
completion,
Date.now(),
prefix,
truncatedPrefix,
);
} else {
const count = await this.db.get(
@ -89,7 +99,7 @@ export class AutocompleteLruCache {
await this.db.run(
"INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)",
prefix,
truncatedPrefix,
completion,
Date.now(),
);

View file

@ -0,0 +1,65 @@
import {
processTestCase,
type CompletionTestCase,
} from "./completionTestUtils";
describe("processTestCase utility", () => {
it("processes simple console.log completion", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur||till|)",
completion: "\"foo,\", bar",
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "\"foo,\", bar",
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: "\"foo,\", bar",
},
});
});
it("processes simple console.log completion with overwriting", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur|)|till|",
completion: "\"foo,\", bar);",
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "\"foo,\", bar);",
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: "\"foo,\", bar);",
range: {
start: "console.log(".length,
end: "console.log()".length,
},
},
});
});
it("partially applying completion", () => {
const testCase: CompletionTestCase = {
original: "|cur||till|fetch(\"https://example.com\");",
completion: "await fetch(\"https://example.com\");",
appliedCompletion: "await ",
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "await fetch(\"https://example.com\");",
currentText: "fetch(\"https://example.com\");",
cursorPosition: 0,
},
expectedResult: {
completionText: "await ",
},
});
});
});

View file

@ -0,0 +1,91 @@
export interface CompletionTestCase {
original: string; // Text with |cur| and |till| markers
completion: string; // Text to insert/overwrite
appliedCompletion?: string | null;
cursorMarker?: string;
tillMarker?: string;
}
export interface ProcessedTestCase {
input: {
lastLineOfCompletionText: string;
currentText: string;
cursorPosition: number;
};
expectedResult: {
completionText: string;
range?: {
start: number;
end: number;
};
};
}
/**
* Transforms human-readable test case into input and expected results.
*
* - `original`: Your original text with |cur| marking where the cursor is before completion,
* and |till| marking where the cursor should be after accepting completion (and this is
* the end of the actual applied completion)
* - `completion`: LLM completion output
* - `appliedCompletion` (optional): part of the LLM completion output that is actually applied
* (written between |cur| and |till| in the original)
*
* For example, you have this line:
*
* console.log("<cursor here>");
*
* and expect it to be completed this way:
*
* console.log("foo: ", bar<cursor here>);
*
* with your completion coming from LLM being: `'foo: ", bar<cursor here>);'`
*
* Your input to this function should be:
* - original: `'console.log("|cur|"|till|);'`
* - completion: `'foo: ", bar);'`
* - appliedCompletion: `'foo: ", bar'`
*
* Output: input and expected output of {@link core/autocomplete/util/processSingleLineCompletion/processSingleLineCompletion|processSingleLineCompletion()}
*
*/
export function processTestCase({
original,
completion,
appliedCompletion = null,
cursorMarker = "|cur|",
tillMarker = "|till|",
}: CompletionTestCase): ProcessedTestCase {
// Validate cursor marker
if (!original.includes(cursorMarker)) {
throw new Error("Cursor marker not found in original text");
}
const cursorPos = original.indexOf(cursorMarker);
original = original.replace(cursorMarker, "");
let tillPos = original.indexOf(tillMarker);
if (tillPos < 0) {
tillPos = cursorPos;
} else {
original = original.replace(tillMarker, "")
}
// Calculate currentText based on what's between cursor and till marker
const currentText = original.substring(cursorPos);
return {
input: {
lastLineOfCompletionText: completion,
currentText,
cursorPosition: cursorPos,
},
expectedResult: {
completionText: appliedCompletion || completion,
range: cursorPos === tillPos ? undefined : {
start: cursorPos,
end: tillPos,
},
},
};
}

View file

@ -0,0 +1,97 @@
import { processTestCase } from "./completionTestUtils";
import { processSingleLineCompletion } from "./processSingleLineCompletion";
describe("processSingleLineCompletion", () => {
it("should handle simple end of line completion", () => {
const testCase = processTestCase({
original: "console.log(|cur|",
completion: "\"Hello, world!\")",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it("should handle midline insert repeating the end of line", () => {
const testCase = processTestCase({
original: "console.log(|cur|);|till|",
completion: "\"Hello, world!\");",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
const testCase = processTestCase({
original: "console.log(|cur|)|till|",
completion: "\"Hello, world!\");",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it("should handle simple midline insert", () => {
const testCase = processTestCase({
original: "console.log(|cur|)",
completion: "\"Hello, world!\"",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it("should handle complex dif with addition in the beginning", () => {
const testCase = processTestCase({
original: "console.log(|cur||till|, \"param1\", )", // TODO
completion: "\"Hello world!\", \"param1\", param1);",
appliedCompletion: "\"Hello world!\""
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
it("should handle simple insertion even with random equality", () => {
const testCase = processTestCase({
original: "print(f\"Foobar length: |cur||till|\")",
completion: "{len(foobar)}",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
});

View file

@ -0,0 +1,92 @@
import * as Diff from "diff";
interface SingleLineCompletionResult {
completionText: string;
range?: {
start: number;
end: number;
};
}
interface DiffType {
count?: number;
added?: boolean;
removed?: boolean;
value: string;
}
function diffPatternMatches(
diffs: DiffType[],
pattern: DiffPartType[],
): boolean {
if (diffs.length !== pattern.length) {
return false;
}
for (let i = 0; i < diffs.length; i++) {
const diff = diffs[i];
const diffPartType: DiffPartType =
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
if (diffPartType !== pattern[i]) {
return false;
}
}
return true;
}
type DiffPartType = "+" | "-" | "=";
export function processSingleLineCompletion(
lastLineOfCompletionText: string,
currentText: string,
cursorPosition: number
): SingleLineCompletionResult | undefined {
const diffs: DiffType[] = Diff.diffWords(currentText, lastLineOfCompletionText);
if (diffPatternMatches(diffs, ["+"])) {
// Just insert, we're already at the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
if (
diffPatternMatches(diffs, ["+", "="]) ||
diffPatternMatches(diffs, ["+", "=", "+"])
) {
// The model repeated the text after the cursor to the end of the line
return {
completionText: lastLineOfCompletionText,
range: {
start: cursorPosition,
end: currentText.length + cursorPosition,
},
};
}
if (
diffPatternMatches(diffs, ["+", "-"]) ||
diffPatternMatches(diffs, ["-", "+"])
) {
// We are midline and the model just inserted without repeating to the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
// For any other diff pattern, just use the first added part if available
if (diffs[0]?.added) {
return {
completionText: diffs[0].value,
};
}
// Default case: treat as simple insertion
return {
completionText: lastLineOfCompletionText,
};
}

View file

@ -1,5 +1,7 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
import { renderChatMessage } from "../util/messageContent";
import SlashCommands from "./slash";
@ -7,66 +9,62 @@ import SlashCommands from "./slash";
export function slashFromCustomCommand(
customCommand: CustomCommand,
): SlashCommand {
const commandName = customCommand.name.startsWith("/")
? customCommand.name.substring(1)
: customCommand.name;
return {
name: customCommand.name,
name: commandName,
description: customCommand.description ?? "",
run: async function* ({ input, llm, history, ide }) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${customCommand.name}`)) {
userInput = userInput
.slice(customCommand.name.length + 1, userInput.length)
.trimStart();
}
prompt: customCommand.prompt,
run: async function* ({
input,
llm,
history,
ide,
completionOptions,
config,
selectedCode,
fetch,
}) {
// Render prompt template
const promptUserInput = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
);
let renderedPrompt: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
renderedPrompt = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input },
);
} else {
const renderedPromptFile = await renderPromptFileV2(
customCommand.prompt,
{
config,
llm,
ide,
selectedCode,
fetch,
fullInput: input,
embeddingsProvider: config.modelsByRole.embed[0],
reranker: config.modelsByRole.rerank[0],
},
);
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
const { role, content } = message;
if (role !== "user") {
continue;
}
if (
Array.isArray(content) &&
content.some(
(part) =>
"text" in part && part.text?.startsWith(`/${customCommand.name}`),
)
) {
messages[i] = {
...message,
content: content.map((part) => {
if (
"text" in part &&
part.text.startsWith(`/${customCommand.name}`)
) {
return { type: "text", text: promptUserInput };
}
return part;
}),
};
break;
} else if (
typeof content === "string" &&
content.startsWith(`/${customCommand.name}`)
) {
messages[i] = { ...message, content: promptUserInput };
break;
}
renderedPrompt = renderedPromptFile[1];
}
// Replaces slash command messages with the rendered prompt
// which INCLUDES the input
const messages = replaceSlashCommandWithPromptInChatHistory(
history,
commandName,
renderedPrompt,
undefined,
);
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
completionOptions,
)) {
yield renderChatMessage(chunk);
}

View file

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

View file

@ -1,5 +1,6 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
import { ChatMessage, SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
export function constructMcpSlashCommand(
@ -17,13 +18,13 @@ export function constructMcpSlashCommand(
const userInput = context.input.split(" ").slice(1).join(" ");
if (args) {
args.forEach((arg, i) => {
argsObject[arg] = userInput;
argsObject[arg] = ""; // userInput
});
}
const result = await client.getPrompt({ name, arguments: argsObject });
const messages: ChatMessage[] = result.messages.map((msg) => {
const mcpMessages: PromptMessage[] = result.messages;
const messages: ChatMessage[] = mcpMessages.map((msg) => {
if (msg.content.type !== "text") {
throw new Error(
"Continue currently only supports text prompts through MCP",
@ -35,9 +36,32 @@ export function constructMcpSlashCommand(
};
});
if (messages.length === 0) {
yield "The MCP prompt returned no messages";
return;
}
if (userInput) {
const lastMessage = messages.at(-1);
if (!lastMessage || lastMessage.role !== "user") {
messages.push({
role: "user",
content: userInput,
});
} else {
let newContent = renderChatMessage(lastMessage);
if (newContent) {
newContent += "\n\n";
}
newContent += userInput;
lastMessage.content = newContent;
}
}
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
context.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

@ -1,6 +1,7 @@
import { v4 as uuidv4 } from "uuid";
import { ContextItemWithId, RangeInFileWithContents } from "../";
import { findUriInDirs, getUriPathBasename } from "../util/uri";
import { v4 as uuidv4 } from "uuid";
export function rifWithContentsToContextItem(
rif: RangeInFileWithContents,
@ -33,13 +34,18 @@ export function ctxItemToRifWithContents(
): RangeInFileWithContents {
let startLine = 0;
let endLine = 0;
let adjustLines = linesOffByOne ? 1 : 0;
const nameSplit = item.name.split("(");
if (nameSplit.length > 1) {
const lines = nameSplit[1].split(")")[0].split("-");
startLine = Number.parseInt(lines[0], 10) - (linesOffByOne ? 1 : 0);
endLine = Number.parseInt(lines[1], 10) - (linesOffByOne ? 1 : 0);
startLine = Number.parseInt(lines[0], 10);
if (startLine === 0) {
adjustLines = 0; // safety to make sure doesn't go negative
}
startLine -= adjustLines;
endLine = Number.parseInt(lines[1], 10) - adjustLines;
}
const rif: RangeInFileWithContents = {

View file

@ -9,9 +9,9 @@ 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");
const profiles = testConfigHandler.currentOrg.profiles;
expect(profiles?.length).toBe(1);
expect(profiles?.[0].profileDescription.id).toBe("local");
const currentProfile = testConfigHandler.currentProfile;
expect(currentProfile?.profileDescription.id).toBe("local");
@ -19,7 +19,9 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should load the default config successfully", async () => {
const result = await testConfigHandler.loadConfig();
expect(result.config!.models.length).toBe(defaultConfig.models.length);
expect(result.config!.modelsByRole.chat.length).toBe(
defaultConfig.models?.length,
);
});
test.skip("should add a system message from config.ts", async () => {

View file

@ -1,338 +1,323 @@
import * as fs from "node:fs";
import {
AssistantUnrolled,
ConfigResult,
FullSlug,
} from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { ConfigResult } from "@continuedev/config-yaml";
import {
ControlPlaneClient,
ControlPlaneSessionInfo,
} from "../control-plane/client.js";
import { getControlPlaneEnv, useHub } from "../control-plane/env.js";
import { getControlPlaneEnv } from "../control-plane/env.js";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
IContextProvider,
IDE,
IdeSettings,
ILLM,
ILLMLogger,
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js";
import { localPathToUri } from "../util/pathToUri.js";
import { logger } from "../util/logger.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
LOCAL_ONBOARDING_PROVIDER_TITLE,
} from "./onboarding.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
ASSISTANTS,
getAllDotContinueYamlFiles,
LoadAssistantFilesOptions,
} from "./loadLocalAssistants.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
import {
OrganizationDescription,
OrgWithProfiles,
ProfileDescription,
ProfileLifecycleManager,
SerializedOrgWithProfiles,
} from "./ProfileLifecycleManager.js";
import { clientRenderHelper } from "./yaml/clientRender.js";
export type { ProfileDescription };
type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
// Separately manages saving/reloading each profile
export class ConfigHandler {
controlPlaneClient: ControlPlaneClient;
private readonly globalContext = new GlobalContext();
private additionalContextProviders: IContextProvider[] = [];
private profiles: ProfileLifecycleManager[];
private selectedProfileId: string | null;
private selectedOrgId: string | null;
private localProfileManager: ProfileLifecycleManager;
private globalLocalProfileManager: ProfileLifecycleManager;
private organizations: OrgWithProfiles[] = [];
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles;
constructor(
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private readonly writeLog: (text: string) => Promise<void>,
private controlPlaneClient: ControlPlaneClient,
private llmLogger: ILLMLogger,
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.writeLog = writeLog;
// Set local profile as default
const localProfileLoader = new LocalProfileLoader(
ide,
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
controlPlaneClient,
writeLog,
);
this.localProfileManager = new ProfileLifecycleManager(
localProfileLoader,
// This profile manager will always be available
this.globalLocalProfileManager = new ProfileLifecycleManager(
new LocalProfileLoader(
ide,
ideSettingsPromise,
this.controlPlaneClient,
this.llmLogger,
),
this.ide,
);
this.profiles = [this.localProfileManager];
this.selectedProfileId = localProfileLoader.description.id;
this.selectedOrgId = null;
void this.init();
// Just to be safe, always force a default personal org with local profile manager
this.currentProfile = this.globalLocalProfileManager;
const personalOrg: OrgWithProfiles = {
currentProfile: this.globalLocalProfileManager,
profiles: [this.globalLocalProfileManager],
...this.PERSONAL_ORG_DESC,
};
this.currentOrg = personalOrg;
this.organizations = [personalOrg];
void this.cascadeInit();
}
private async init() {
// Always load local profile immediately in case control plane doesn't load
try {
await this.loadConfig();
} catch (e) {
console.error("Failed to load config: ", e);
private workspaceDirs: string[] | null = null;
async getWorkspaceId() {
if (!this.workspaceDirs) {
this.workspaceDirs = await this.ide.getWorkspaceDirs();
}
return this.workspaceDirs.join("&");
}
async getProfileKey(orgId: string) {
const workspaceId = await this.getWorkspaceId();
const lastSelectedOrgIds =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const selectedOrgId = lastSelectedOrgIds[workspaceId];
// We want to set the org ID before fetching control plane profiles
if (selectedOrgId) {
this.selectedOrgId = selectedOrgId;
}
// Load control plane profiles
void this.fetchControlPlaneProfiles();
return `${workspaceId}:::${orgId}`;
}
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.profileDescription.id === this.selectedProfileId,
) ?? null
);
}
private async cascadeInit() {
this.workspaceDirs = null; // forces workspace dirs reload
get inactiveProfiles() {
return this.profiles.filter(
(p) => p.profileDescription.id !== this.selectedProfileId,
);
}
const orgs = await this.getOrgs();
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
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 {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
}
}
private async loadPlatformProfiles() {
// Get the profiles and create their lifecycle managers
this.controlPlaneClient
.listAssistants(this.selectedOrgId)
.then(async (assistants) => {
const hubProfiles = await Promise.all(
assistants.map(async (assistant) => {
let renderedConfig: AssistantUnrolled | undefined = undefined;
if (assistant.configResult.config) {
renderedConfig = await clientRenderHelper(
{
ownerSlug: assistant.ownerSlug,
packageSlug: assistant.packageSlug,
},
YAML.stringify(assistant.configResult.config),
this.ide,
this.controlPlaneClient,
);
}
const profileLoader = new PlatformProfileLoader(
{ ...assistant.configResult, config: renderedConfig },
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
);
this.profiles =
this.selectedOrgId === null
? [this.localProfileManager, ...hubProfiles]
: hubProfiles;
this.notifyProfileListeners(
this.profiles.map((profile) => profile.profileDescription),
);
// Check the last selected workspace, and reload if it isn't local
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const selectedProfileId = lastSelectedIds[workspaceId];
if (selectedProfileId) {
this.selectedProfileId = selectedProfileId;
await this.loadConfig();
} else {
// Otherwise we stick with local profile, and record choice
lastSelectedIds[workspaceId] = this.selectedProfileId;
this.globalContext.update(
"lastSelectedProfileForWorkspace",
lastSelectedIds,
);
}
})
.catch((e) => {
console.error("Failed to list assistants: ", e);
});
}
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 fetchControlPlaneProfiles() {
if (await useHub(this.ideSettingsPromise)) {
clearInterval(this.platformProfilesRefreshInterval);
await this.loadPlatformProfiles();
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
// If so, we do the full (more expensive) reload
this.platformProfilesRefreshInterval = setInterval(async () => {
const newFullSlugsList =
await this.controlPlaneClient.listAssistantFullSlugs(
this.selectedOrgId,
);
if (newFullSlugsList) {
const shouldReload = this.fullSlugsListsDiffer(
newFullSlugsList,
this.lastFullSlugsList,
);
if (shouldReload) {
await this.loadPlatformProfiles();
}
this.lastFullSlugsList = newFullSlugsList;
}
}, PlatformProfileLoader.RELOAD_INTERVAL);
} else {
this.controlPlaneClient
.listWorkspaces()
.then(async (workspaces) => {
this.profiles = [this.localProfileManager];
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
this.profiles.push(
new ProfileLifecycleManager(profileLoader, this.ide),
);
});
this.notifyProfileListeners(
this.profiles.map((profile) => profile.profileDescription),
);
// Check the last selected workspace, and reload if it isn't local
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const selectedProfileId = lastSelectedIds[workspaceId];
if (selectedProfileId) {
this.selectedProfileId = selectedProfileId;
await this.loadConfig();
} else {
// Otherwise we stick with local profile, and record choice
lastSelectedIds[workspaceId] = this.selectedProfileId;
this.globalContext.update(
"lastSelectedProfileForWorkspace",
lastSelectedIds,
);
}
})
.catch((e) => {
console.error(e);
});
}
}
async setSelectedOrgId(orgId: string | null) {
this.selectedOrgId = orgId;
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
selectedOrgs[await this.getWorkspaceId()] = orgId;
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
const currentSelection = selectedOrgs[workspaceId];
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
selectedOrg = fallback;
}
}
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig();
}
async setSelectedProfile(profileId: string | null) {
this.selectedProfileId = profileId;
const result = await this.loadConfig();
this.notifyConfigListeners(result);
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
selectedProfiles[await this.getWorkspaceId()] = profileId;
this.globalContext.update(
"lastSelectedProfileForWorkspace",
selectedProfiles,
private async getOrgs(): Promise<OrgWithProfiles[]> {
const userId = await this.controlPlaneClient.userId;
if (userId) {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const personalHubOrg = await this.getPersonalHubOrg();
const hubOrgs = await Promise.all(
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
);
return [...hubOrgs, personalHubOrg];
} else {
return [await this.getLocalOrg()];
}
}
getSerializedOrgs(): SerializedOrgWithProfiles[] {
return this.organizations.map((org) => ({
iconUrl: org.iconUrl,
id: org.id,
name: org.name,
slug: org.slug,
profiles: org.profiles.map((profile) => profile.profileDescription),
selectedProfileId: org.currentProfile?.profileDescription.id || null,
}));
}
private async getHubProfiles(orgScopeId: string | null) {
const assistants = await this.controlPlaneClient.listAssistants(orgScopeId);
return await Promise.all(
assistants.map(async (assistant) => {
const profileLoader = await PlatformProfileLoader.create({
configResult: {
...assistant.configResult,
config: assistant.configResult.config,
},
ownerSlug: assistant.ownerSlug,
packageSlug: assistant.packageSlug,
iconUrl: assistant.iconUrl,
versionSlug: assistant.configResult.config?.version ?? "latest",
controlPlaneClient: this.controlPlaneClient,
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
llmLogger: this.llmLogger,
rawYaml: assistant.rawYaml,
orgScopeId: orgScopeId,
});
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
);
}
// A unique ID for the current workspace, built from folder names
private async getWorkspaceId(): Promise<string> {
const dirs = await this.ide.getWorkspaceDirs();
return dirs.join("&");
private async getNonPersonalHubOrg(
org: OrganizationDescription,
): Promise<OrgWithProfiles> {
const localProfiles = await this.getLocalProfiles({
includeGlobal: false,
includeWorkspace: true,
});
const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
return this.rectifyProfilesForOrg(org, profiles);
}
// Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed
updateIdeSettings(ideSettings: IdeSettings) {
private PERSONAL_ORG_DESC: OrganizationDescription = {
iconUrl: "",
id: "personal",
name: "Personal",
slug: undefined,
};
private async getPersonalHubOrg() {
const localProfiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
const hubProfiles = await this.getHubProfiles(null);
const profiles = [...hubProfiles, ...localProfiles];
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
}
private async getLocalOrg() {
const localProfiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
}
private async rectifyProfilesForOrg(
org: OrganizationDescription,
profiles: ProfileLifecycleManager[],
): Promise<OrgWithProfiles> {
const profileKey = await this.getProfileKey(org.id);
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const currentSelection = selectedProfiles[profileKey];
const firstNonLocal = profiles.find(
(profile) => profile.profileDescription.profileType !== "local",
);
const fallback =
firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
let currentProfile: ProfileLifecycleManager | null;
if (!currentSelection) {
currentProfile = fallback;
} else {
const match = profiles.find(
(profile) => profile.profileDescription.id === currentSelection,
);
if (match) {
currentProfile = match;
} else {
currentProfile = fallback;
}
}
if (currentProfile) {
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[profileKey]: selectedProfiles.id ?? null,
});
}
return {
...org,
profiles,
currentProfile,
};
}
async getLocalProfiles(options: LoadAssistantFilesOptions) {
/**
* Users can define as many local assistants as they want in a `.continue/assistants` folder
*/
const localProfiles: ProfileLifecycleManager[] = [];
if (options.includeGlobal) {
localProfiles.push(this.globalLocalProfileManager);
}
if (options.includeWorkspace) {
const assistantFiles = await getAllDotContinueYamlFiles(
this.ide,
{
...options,
includeGlobal: false, // Because the global comes from above
},
ASSISTANTS,
);
const profiles = assistantFiles.map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.llmLogger,
assistant,
);
});
const localAssistantProfiles = profiles.map(
(profile) => new ProfileLifecycleManager(profile, this.ide),
);
localProfiles.push(...localAssistantProfiles);
}
return localProfiles;
}
//////////////////
// External actions that can cause a cascading config refresh
// Should not be used internally
//////////////////
async refreshAll() {
await this.cascadeInit();
}
// Ide settings change: refresh session and cascade refresh from the top
async updateIdeSettings(ideSettings: IdeSettings) {
this.ideSettingsPromise = Promise.resolve(ideSettings);
void this.reloadConfig();
await this.cascadeInit();
}
// Session change: refresh session and cascade refresh from the top
async updateControlPlaneSessionInfo(
sessionInfo: ControlPlaneSessionInfo | undefined,
) {
@ -340,26 +325,97 @@ export class ConfigHandler {
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
);
this.fetchControlPlaneProfiles().catch((e) => {
console.error("Failed to fetch control plane profiles: ", e);
await this.cascadeInit();
}
// Org id: check id validity, save selection, switch and reload
async setSelectedOrgId(orgId: string, profileId?: string) {
if (orgId === this.currentOrg.id) {
return;
}
const org = this.organizations.find((org) => org.id === orgId);
if (!org) {
throw new Error(`Org ${orgId} not found`);
}
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: org.id,
});
}
private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = [];
onDidChangeAvailableProfiles(
listener: (profiles: ProfileDescription[]) => void,
) {
this.profilesListeners.push(listener);
}
this.currentOrg = org;
private notifyProfileListeners(profiles: ProfileDescription[]) {
for (const listener of this.profilesListeners) {
listener(profiles);
if (profileId) {
this.setSelectedProfileId(profileId);
} else {
this.currentProfile = org.currentProfile;
await this.reloadConfig();
}
}
// Profile id: check id validity, save selection, switch and reload
async setSelectedProfileId(profileId: string) {
if (
this.currentProfile &&
profileId === this.currentProfile.profileDescription.id
) {
return;
}
const profile = this.currentOrg.profiles.find(
(profile) => profile.profileDescription.id === profileId,
);
if (!profile) {
throw new Error(`Profile ${profileId} not found in current org`);
}
const profileKey = await this.getProfileKey(this.currentOrg.id);
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[profileKey]: profileId,
});
this.currentProfile = profile;
await this.reloadConfig();
}
// Bottom level of cascade: refresh the current profile
// IMPORTANT - must always refresh when switching profiles
// Because of e.g. MCP singleton and docs service using things from config
// Could improve this
async reloadConfig() {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
for (const org of this.organizations) {
for (const profile of org.profiles) {
if (
profile.profileDescription.id !==
this.currentProfile.profileDescription.id
) {
profile.clearConfig();
}
}
}
const { config, errors, configLoadInterrupted } =
await this.currentProfile.reloadConfig(this.additionalContextProviders);
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
return { config, errors, configLoadInterrupted };
}
// Listeners setup - can listen to current profile updates
private notifyConfigListeners(result: ConfigResult<ContinueConfig>) {
// Notify listeners that config changed
for (const listener of this.updateListeners) {
listener(result);
}
@ -371,27 +427,9 @@ 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() {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
configLoadInterrupted: true,
};
}
const { config, errors, configLoadInterrupted } =
await this.currentProfile.reloadConfig(this.additionalContextProviders);
if (config) {
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
}
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
return { config, errors, configLoadInterrupted };
}
// Methods for loading (without reloading) config
// Serialized for passing to GUI
// Load for just awaiting current config load promise for the profile
async getSerializedConfig(): Promise<
ConfigResult<BrowserSerializedContinueConfig>
> {
@ -407,10 +445,6 @@ export class ConfigHandler {
);
}
listProfiles(): ProfileDescription[] {
return this.profiles.map((p) => p.profileDescription);
}
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (!this.currentProfile) {
return {
@ -419,33 +453,46 @@ export class ConfigHandler {
configLoadInterrupted: true,
};
}
return await this.currentProfile.loadConfig(
const config = await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
}
async llmFromTitle(title?: string): Promise<ILLM> {
const { config } = await this.loadConfig();
const model = config?.models.find((m) => m.title === title);
if (!model) {
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,
});
return ollama;
} else if (config?.models?.length) {
return config?.models[0];
}
throw new Error("No model found");
if (config.errors?.length) {
logger.warn("Errors loading config: ", config.errors);
}
return model;
return config;
}
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
if (!openProfileId) {
return;
}
const profile = this.currentOrg.profiles.find(
(p) => p.profileDescription.id === openProfileId,
);
if (profile?.profileDescription.profileType === "local") {
await this.ide.openFile(profile.profileDescription.uri);
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
}
}
// Ancient method of adding custom providers through vs code
private additionalContextProviders: IContextProvider[] = [];
registerCustomContextProvider(contextProvider: IContextProvider) {
this.additionalContextProviders.push(contextProvider);
void this.reloadConfig();
}
/**
* 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);
}
}

View file

@ -21,6 +21,8 @@ export interface ProfileDescription {
id: string;
iconUrl: string;
errors: ConfigValidationError[] | undefined;
uri: string;
rawYaml?: string;
}
export interface OrganizationDescription {
@ -30,6 +32,16 @@ export interface OrganizationDescription {
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
}
export type OrgWithProfiles = OrganizationDescription & {
profiles: ProfileLifecycleManager[];
currentProfile: ProfileLifecycleManager | null;
};
export type SerializedOrgWithProfiles = OrganizationDescription & {
profiles: ProfileDescription[];
selectedProfileId: string | null;
};
export class ProfileLifecycleManager {
private savedConfigResult: ConfigResult<ContinueConfig> | undefined;
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;
@ -77,14 +89,21 @@ export class ProfileLifecycleManager {
// Set pending config promise
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
let result: ConfigResult<ContinueConfig>;
// This try catch is expected to catch high-level errors that aren't block-specific
// Like invalid json, invalid yaml, file read errors, etc.
// NOT block-specific loading errors
try {
result = await this.profileLoader.doLoadConfig();
} catch (e: any) {
} catch (e) {
const message =
e instanceof Error
? `${e.message}\n${e.stack ? e.stack : ""}`
: "Error loading config";
result = {
errors: [
{
fatal: true,
message: e.message,
message,
},
],
config: undefined,
@ -99,7 +118,6 @@ export class ProfileLifecycleManager {
).concat(additionalContextProviders);
}
this.savedConfigResult = result;
resolve(result);
});

View file

@ -1,91 +1,37 @@
import {
ContextProviderWithParams,
ModelDescription,
SerializedContinueConfig,
SlashCommandDescription,
} from "../";
import { ConfigYaml } from "@continuedev/config-yaml";
export const FREE_TRIAL_MODELS: ModelDescription[] = [
{
title: "Claude 3.5 Sonnet (Free Trial)",
provider: "free-trial",
model: "claude-3-5-sonnet-latest",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "GPT-4o (Free Trial)",
provider: "free-trial",
model: "gpt-4o",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "Llama3.1 70b (Free Trial)",
provider: "free-trial",
model: "llama3.1-70b",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "Codestral (Free Trial)",
provider: "free-trial",
model: "codestral-latest",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
export const defaultContextProvidersVsCode: NonNullable<
ConfigYaml["context"]
>[number][] = [
{ provider: "code" },
{ provider: "docs" },
{ provider: "diff" },
{ provider: "terminal" },
{ provider: "problems" },
{ provider: "folder" },
{ provider: "codebase" },
];
export const defaultContextProvidersVsCode: ContextProviderWithParams[] = [
{ name: "code", params: {} },
{ name: "docs", params: {} },
{ name: "diff", params: {} },
{ name: "terminal", params: {} },
{ name: "problems", params: {} },
{ name: "folder", params: {} },
{ name: "codebase", params: {} },
export const defaultContextProvidersJetBrains: NonNullable<
ConfigYaml["context"]
>[number][] = [
{ provider: "diff" },
{ provider: "folder" },
{ provider: "codebase" },
];
export const defaultContextProvidersJetBrains: ContextProviderWithParams[] = [
{ name: "diff", params: {} },
{ name: "folder", params: {} },
{ name: "codebase", params: {} },
];
export const defaultSlashCommandsVscode: SlashCommandDescription[] = [
{
name: "share",
description: "Export the current chat session to markdown",
},
{
name: "cmd",
description: "Generate a shell command",
},
{
name: "commit",
description: "Generate a git commit message",
},
];
export const defaultSlashCommandsJetBrains = [
{
name: "share",
description: "Export the current chat session to markdown",
},
{
name: "commit",
description: "Generate a git commit message",
},
];
export const defaultConfig: SerializedContinueConfig = {
export const defaultConfig: ConfigYaml = {
name: "Local Assistant",
version: "1.0.0",
schema: "v1",
models: [],
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
context: defaultContextProvidersVsCode,
};
export const defaultConfigJetBrains: SerializedContinueConfig = {
export const defaultConfigJetBrains: ConfigYaml = {
name: "Local Assistant",
version: "1.0.0",
schema: "v1",
models: [],
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
context: defaultContextProvidersJetBrains,
};

View file

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

View file

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

View file

@ -3,7 +3,11 @@ import * as fs from "fs";
import os from "os";
import path from "path";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import {
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import * as JSONC from "comment-json";
import * as tar from "tar";
@ -14,13 +18,14 @@ import {
ContinueConfig,
ContinueRcJson,
CustomContextProvider,
CustomLLM,
EmbeddingsProviderDescription,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
ILLM,
ILLMLogger,
LLMOptions,
ModelDescription,
RerankerDescription,
@ -30,17 +35,16 @@ import {
import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index.js";
import { AllRerankers } from "../context/allRerankers";
import { MCPManagerSingleton } from "../context/mcp";
} from "../commands/index";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
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 { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
import { useHub } from "../control-plane/env";
import { BaseLLM } from "../llm";
import { llmFromDescription } from "../llm/llms";
import { LLMClasses, llmFromDescription } from "../llm/llms";
import CustomLLMClass from "../llm/llms/CustomLLM";
import FreeTrial from "../llm/llms/FreeTrial";
import { LLMReranker } from "../llm/llms/llm";
@ -61,18 +65,14 @@ import {
getContinueDotEnv,
getEsbuildBinaryPath,
} from "../util/paths";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import { useHub } from "../control-plane/env";
import { localPathToUri } from "../util/pathToUri";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
defaultSlashCommandsJetBrains,
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { modifyContinueConfigWithSharedConfig } from "./sharedConfig";
getModelByRole,
isSupportedLanceDbCpuTargetForLinux,
serializePromptTemplates,
} from "./util";
import { validateConfig } from "./validation.js";
export function resolveSerializedConfig(
@ -116,7 +116,7 @@ function loadSerializedConfig(
let config: SerializedContinueConfig = overrideConfigJson!;
if (!config) {
try {
config = resolveSerializedConfig(getConfigJsonPath(ideType));
config = resolveSerializedConfig(getConfigJsonPath());
} catch (e) {
throw new Error(`Failed to parse config.json: ${e}`);
}
@ -156,20 +156,9 @@ function loadSerializedConfig(
);
}
// Set defaults if undefined (this lets us keep config.json uncluttered for new users)
config.contextProviders ??=
ideType === "vscode"
? [...defaultContextProvidersVsCode]
: [...defaultContextProvidersJetBrains];
config.slashCommands ??=
ideType === "vscode"
? [...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 };
}
@ -214,111 +203,113 @@ async function serializedToIntermediateConfig(
return config;
}
function isModelDescription(
llm: ModelDescription | CustomLLM,
): llm is ModelDescription {
return (llm as ModelDescription).title !== undefined;
}
export function isContextProviderWithParams(
contextProvider: CustomContextProvider | ContextProviderWithParams,
): contextProvider is ContextProviderWithParams {
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,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
loadPromptFiles: boolean = true,
allowFreeTrial: boolean = true,
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
async function intermediateToFinalConfig({
config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
loadPromptFiles = true,
allowFreeTrial = true,
}: {
config: Config;
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
loadPromptFiles?: boolean;
allowFreeTrial?: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
// Auto-detect models
let models: BaseLLM[] = [];
for (const desc of config.models) {
if (isModelDescription(desc)) {
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
config.completionOptions,
config.systemMessage,
);
if (!llm) {
continue;
}
if (llm.model === "AUTODETECT") {
try {
const modelNames = await llm.listModels();
const detectedModels = await Promise.all(
modelNames.map(async (modelName) => {
return await llmFromDescription(
{
...desc,
model: modelName,
title: `${llm.title} - ${modelName}`,
},
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
copyOf(config.completionOptions),
config.systemMessage,
);
}),
);
models.push(
...(detectedModels.filter(
(x) => typeof x !== "undefined",
) as BaseLLM[]),
);
} catch (e) {
console.warn("Error listing models: ", e);
await Promise.all(
config.models.map(async (desc) => {
if ("title" in desc) {
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
llmLogger,
config.completionOptions,
);
if (!llm) {
return;
}
} else {
models.push(llm);
}
} else {
const llm = new CustomLLMClass({
...desc,
options: { ...desc.options, writeLog } as any,
});
if (llm.model === "AUTODETECT") {
try {
const modelNames = await llm.listModels();
const models = modelNames.map(
(modelName) =>
new CustomLLMClass({
...desc,
options: { ...desc.options, model: modelName, writeLog },
if (llm.model === "AUTODETECT") {
try {
const modelNames = await llm.listModels();
const detectedModels = await Promise.all(
modelNames.map(async (modelName) => {
return await llmFromDescription(
{
...desc,
model: modelName,
title: modelName,
},
ide.readFile.bind(ide),
uniqueId,
ideSettings,
llmLogger,
copyOf(config.completionOptions),
);
}),
);
models.push(...models);
} catch (e) {
console.warn("Error listing models: ", e);
);
models.push(
...(detectedModels.filter(
(x) => typeof x !== "undefined",
) as BaseLLM[]),
);
} catch (e) {
console.warn("Error listing models: ", e);
}
} else {
models.push(llm);
}
} else {
models.push(llm);
const llm = new CustomLLMClass({
...desc,
options: { ...desc.options, logger: llmLogger } as any,
});
if (llm.model === "AUTODETECT") {
try {
const modelNames = await llm.listModels();
const models = modelNames.map(
(modelName) =>
new CustomLLMClass({
...desc,
options: {
...desc.options,
model: modelName,
logger: llmLogger,
},
}),
);
models.push(...models);
} catch (e) {
console.warn("Error listing models: ", e);
}
} else {
models.push(llm);
}
}
}
}
}),
);
// Prepare models
for (const model of models) {
@ -326,7 +317,7 @@ async function intermediateToFinalConfig(
...model.requestOptions,
...config.requestOptions,
};
model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified
model.roles = model.roles ?? ["chat", "apply", "edit", "summarize"]; // Default to chat role if not specified
}
if (allowFreeTrial) {
@ -354,15 +345,14 @@ async function intermediateToFinalConfig(
? config.tabAutocompleteModel
: [config.tabAutocompleteModel]
).map(async (desc) => {
if (isModelDescription(desc)) {
if ("title" in desc) {
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
llmLogger,
config.completionOptions,
config.systemMessage,
);
if (llm?.providerName === "free-trial") {
@ -398,10 +388,8 @@ 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({})] : []),
];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
@ -436,150 +424,235 @@ async function intermediateToFinalConfig(
}
// Embeddings Provider
const embeddingsProviderDescription = config.embeddingsProvider as
| EmbeddingsProviderDescription
| undefined;
if (embeddingsProviderDescription?.provider) {
const { provider, ...options } = embeddingsProviderDescription;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
config.embeddingsProvider = new embeddingsProviderClass();
function getEmbeddingsILLM(
embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
): ILLM | null {
if (embedConfig) {
// config.ts-injected ILLM
if ("providerName" in embedConfig) {
return embedConfig;
}
const { provider, ...options } = embedConfig;
if (provider === "transformers.js") {
return new TransformersJsEmbeddingsProvider();
} else {
const llmOptions: LLMOptions = {
model: options.model ?? "UNSPECIFIED",
...options,
};
config.embeddingsProvider = new embeddingsProviderClass(
llmOptions,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...config.requestOptions,
...options.requestOptions,
}),
);
const cls = LLMClasses.find((c) => c.providerName === provider);
if (cls) {
const llmOptions: LLMOptions = {
model: options.model ?? "UNSPECIFIED",
...options,
};
return new cls(llmOptions);
} else {
errors.push({
fatal: false,
message: `Embeddings provider ${provider} not found`,
});
}
}
}
if (ideInfo.ideType === "vscode") {
return new TransformersJsEmbeddingsProvider();
}
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;
}
// config.ts-injected ILLM
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);
} else {
const cls = LLMClasses.find((c) => c.providerName === name);
if (cls) {
const llmOptions: LLMOptions = {
model: params?.model ?? "UNSPECIFIED",
...params,
};
return new cls(llmOptions);
} else {
errors.push({
fatal: false,
message: `Unknown reranking provider ${name}`,
});
}
}
return null;
}
const newReranker = getRerankingILLM(config.reranker);
const continueConfig: ContinueConfig = {
...config,
contextProviders,
tools: [...allTools],
mcpServerStatuses: [],
slashCommands: config.slashCommands ?? [],
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
},
rules: [],
};
if (config.systemMessage) {
continueConfig.rules.unshift({
rule: config.systemMessage,
source: "json-systemMessage",
});
}
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
}),
),
false,
);
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
if (inlineEditModel) {
const match = continueConfig.modelsByRole.chat.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`,
});
}
}
let continueConfig: ContinueConfig = {
...config,
contextProviders,
models,
embeddingsProvider: config.embeddingsProvider as any,
tabAutocompleteModels,
reranker: config.reranker as any,
tools: allTools,
};
const applyBlockModel = getModelByRole(
continueConfig,
"applyCodeBlock",
)?.title;
if (applyBlockModel) {
const match = continueConfig.modelsByRole.chat.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`,
});
}
}
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
if (config.experimental?.modelContextProtocolServers) {
await Promise.all(
config.experimental.modelContextProtocolServers?.map(
async (server, index) => {
const mcpId = index.toString();
const mcpConnection = mcpManager.createConnection(mcpId, server);
if (!mcpConnection) {
return;
}
const abortController = new AbortController();
try {
const mcpError = await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
"MCP Server",
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;
}
}
},
) || [],
// 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 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,
baseChatSystemMessage: llm.baseChatSystemMessage,
requestOptions: llm.requestOptions,
promptTemplates: serializePromptTemplates(llm.promptTemplates),
capabilities: llm.capabilities,
roles: llm.roles,
configurationStatus: llm.getConfigurationStatus(),
};
}
async function finalToBrowserConfig(
final: ContinueConfig,
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,
roles: m.roles,
})),
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?
})),
slashCommands: final.slashCommands?.map(
({ run, ...slashCommandDescription }) => slashCommandDescription,
),
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,
rules: final.rules,
docs: final.docs,
tools: final.tools,
mcpServerStatuses: final.mcpServerStatuses,
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
};
}
@ -767,9 +840,9 @@ async function loadContinueConfigFromJson(
ide: IDE,
workspaceConfigs: ContinueRcJson[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
llmLogger: ILLMLogger,
workOsAccessToken: string | undefined,
overrideConfigJson: SerializedContinueConfig | undefined,
): Promise<ConfigResult<ContinueConfig>> {
@ -781,7 +854,7 @@ async function loadContinueConfigFromJson(
} = loadSerializedConfig(
workspaceConfigs,
ideSettings,
ideType,
ideInfo.ideType,
overrideConfigJson,
ide,
);
@ -790,24 +863,19 @@ async function loadContinueConfigFromJson(
return { errors, config: undefined, configLoadInterrupted: true };
}
const systemPromptDotFile = await getSystemPromptDotFile(ide);
if (systemPromptDotFile) {
serialized.systemMessage = systemPromptDotFile;
}
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyContinueConfigWithSharedConfig(
serialized,
sharedConfig,
);
const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
// Convert serialized to intermediate config
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
@ -863,14 +931,15 @@ async function loadContinueConfigFromJson(
// Convert to final config format
const { config: finalConfig, errors: finalErrors } =
await intermediateToFinalConfig(
intermediate,
await intermediateToFinalConfig({
config: intermediate,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
llmLogger,
workOsAccessToken,
);
});
return {
config: finalConfig,
errors: [...(errors ?? []), ...finalErrors],

View file

@ -0,0 +1,115 @@
import ignore from "ignore";
import { IDE } from "..";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
} from "../indexing/ignore";
import { walkDir } from "../indexing/walkDir";
import { getGlobalFolderWithName } from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { joinPathsToUri } from "../util/uri";
export const ASSISTANTS = "assistants";
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
export function isLocalAssistantFile(uri: string): boolean {
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
return false;
}
const normalizedUri = uri.replace(/\\/g, "/");
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
}
export async function listYamlFilesInDir(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
const overrideDefaultIgnores = ignore()
.add(DEFAULT_IGNORE_FILETYPES.filter((t) => t !== "config.yaml"))
.add(DEFAULT_IGNORE_DIRS);
const uris = await walkDir(dir, ide, {
overrideDefaultIgnores,
source: "get assistant files",
});
const assistantFilePaths = uris.filter(
(p) => p.endsWith(".yaml") || p.endsWith(".yml"),
);
const results = assistantFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch
return { path: uri, content };
});
return Promise.all(results);
} catch (e) {
console.error(e);
return [];
}
}
export interface LoadAssistantFilesOptions {
includeGlobal: boolean;
includeWorkspace: boolean;
}
export function getDotContinueSubDirs(
ide: IDE,
options: LoadAssistantFilesOptions,
workspaceDirs: string[],
subDirName: string,
): string[] {
let fullDirs: string[] = [];
// Workspace .continue/<subDirName>
if (options.includeWorkspace) {
fullDirs = workspaceDirs.map((dir) =>
joinPathsToUri(dir, ".continue", subDirName),
);
}
// ~/.continue/<subDirName>
if (options.includeGlobal) {
fullDirs.push(localPathToUri(getGlobalFolderWithName(subDirName)));
}
return fullDirs;
}
/**
* This method searches in both ~/.continue and workspace .continue
* for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
*/
export async function getAllDotContinueYamlFiles(
ide: IDE,
options: LoadAssistantFilesOptions,
subDirName: string,
): Promise<{ path: string; content: string }[]> {
const workspaceDirs = await ide.getWorkspaceDirs();
// Get all directories to check for assistant files
const fullDirs = getDotContinueSubDirs(
ide,
options,
workspaceDirs,
subDirName,
);
// Get all assistant files from the directories
const assistantFiles = (
await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
).flat();
return await Promise.all(
assistantFiles.map(async (file) => {
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),
);
}

View file

@ -1,7 +1,13 @@
/**
* I'm disabling this rule for the entire file under the assumption
* that this is a one-time migration script. I'm expecting this
* code to be removed in the future.
*/
/* eslint-disable max-statements */
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";
@ -196,11 +202,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
if (effected) {
new GlobalContext().updateSharedConfig(shareConfigUpdates);
editConfigJson(() => config);
// void ide.showToast(
// "warning",
// "Migrated deprecated Continue JSON settings. Edit in the Settings Page",
// );
}
} catch (e) {
throw new Error(`Migration: Failed to parse config.json: ${e}`);

View file

@ -1,6 +1,4 @@
import { SerializedContinueConfig } from "../";
import { FREE_TRIAL_MODELS } from "./default";
import { ConfigYaml } from "@continuedev/config-yaml";
export const TRIAL_FIM_MODEL = "codestral-latest";
export const LOCAL_ONBOARDING_PROVIDER_TITLE = "Ollama";
@ -9,64 +7,46 @@ 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";
export const LOCAL_ONBOARDING_EMBEDDINGS_TITLE = "Nomic Embed";
/**
* We set the "best" chat + autocopmlete models by default
* whenever a user doesn't have a config.json
*/
export function setupBestConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
export function setupBestConfig(config: ConfigYaml): ConfigYaml {
return {
...config,
models: config.models.filter((model) => model.provider !== "free-trial"),
models: config.models,
};
}
export function setupLocalConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
export function setupLocalConfig(config: ConfigYaml): ConfigYaml {
return {
...config,
models: [
{
title: LOCAL_ONBOARDING_CHAT_TITLE,
name: LOCAL_ONBOARDING_CHAT_TITLE,
provider: "ollama",
model: LOCAL_ONBOARDING_CHAT_MODEL,
roles: ["chat", "edit", "apply"],
},
...config.models.filter((model) => model.provider !== "free-trial"),
{
name: LOCAL_ONBOARDING_FIM_TITLE,
provider: "ollama",
model: LOCAL_ONBOARDING_FIM_MODEL,
roles: ["autocomplete"],
},
{
name: LOCAL_ONBOARDING_EMBEDDINGS_TITLE,
provider: "ollama",
model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL,
roles: ["embed"],
},
...(config.models ?? []),
],
tabAutocompleteModel: {
title: LOCAL_ONBOARDING_FIM_TITLE,
provider: "ollama",
model: LOCAL_ONBOARDING_FIM_MODEL,
},
embeddingsProvider: {
provider: "ollama",
model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL,
},
};
}
export function setupQuickstartConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: [
...FREE_TRIAL_MODELS,
...config.models.filter((model) => model.provider !== "free-trial"),
],
tabAutocompleteModel: {
title: "Tab Autocomplete",
provider: "free-trial",
model: TRIAL_FIM_MODEL,
},
embeddingsProvider: {
provider: "free-trial",
},
reranker: {
name: "free-trial",
},
};
export function setupQuickstartConfig(config: ConfigYaml): ConfigYaml {
return config;
}

View file

@ -1,80 +0,0 @@
import { ConfigJson } from "@continuedev/config-types";
import { ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import {
ContinueConfig,
IDE,
IdeSettings,
SerializedContinueConfig,
} from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
export default class ControlPlaneProfileLoader implements IProfileLoader {
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
description: ProfileDescription;
workspaceSettings: ConfigJson | undefined;
constructor(
private readonly workspaceId: string,
private workspaceTitle: string,
private readonly controlPlaneClient: ControlPlaneClient,
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private writeLog: (message: string) => Promise<void>,
private readonly onReload: () => void,
) {
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.description.id,
);
this.onReload();
}, ControlPlaneProfileLoader.RELOAD_INTERVAL);
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const settings =
this.workspaceSettings ??
((await this.controlPlaneClient.getSettingsForWorkspace(
this.description.id,
)) as any);
const serializedConfig: SerializedContinueConfig = settings;
const results = await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
serializedConfig,
undefined,
undefined,
this.workspaceId,
);
return {
...results,
errors: [], // Don't do config validation here, it happens in admin panel
};
}
setIsActive(isActive: boolean): void {}
}

View file

@ -1,44 +1,74 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getPrimaryConfigFilePath } from "../../util/paths.js";
import { localPathToUri } from "../../util/pathToUri.js";
import { getUriPathBasename } from "../../util/uri.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
export default class LocalProfileLoader implements IProfileLoader {
static ID = "local";
description: ProfileDescription = {
id: LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
iconUrl: "",
title: "Local Config",
errors: undefined,
};
constructor(
private ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private controlPlaneClient: ControlPlaneClient,
private writeLog: (message: string) => Promise<void>,
) {}
private llmLogger: ILLMLogger,
private overrideAssistantFile?:
| { path: string; content: string }
| undefined,
) {
const description: ProfileDescription = {
id: overrideAssistantFile?.path ?? LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
iconUrl: "",
title: overrideAssistantFile?.path
? getUriPathBasename(overrideAssistantFile.path)
: "Local Assistant",
errors: undefined,
uri:
overrideAssistantFile?.path ??
localPathToUri(getPrimaryConfigFilePath()),
rawYaml: undefined,
};
this.description = description;
if (overrideAssistantFile?.content) {
try {
const parsedAssistant = parseConfigYaml(
overrideAssistantFile?.content ?? "",
);
this.description.title = parsedAssistant.name;
} catch (e) {
console.error("Failed to parse assistant file: ", e);
}
}
}
description: ProfileDescription;
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const result = await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
undefined,
undefined,
undefined,
);
const result = await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
profileId: this.description.id,
overrideConfigYamlByPath: this.overrideAssistantFile?.path,
orgScopeId: null,
packageIdentifier: {
uriType: "file",
filePath:
this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
},
});
this.description.errors = result.errors;

View file

@ -1,7 +1,8 @@
import { ConfigResult, AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
@ -20,21 +21,84 @@ export interface PlatformConfigMetadata {
export default class PlatformProfileLoader implements IProfileLoader {
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
description: ProfileDescription;
private configResult: ConfigResult<AssistantUnrolled>;
private readonly ownerSlug: string;
private readonly packageSlug: string;
private readonly iconUrl: string;
private readonly versionSlug: string;
private readonly controlPlaneClient: ControlPlaneClient;
private readonly ide: IDE;
private ideSettingsPromise: Promise<IdeSettings>;
private llmLogger: ILLMLogger;
readonly description: ProfileDescription;
private readonly orgScopeId: string | null;
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 = {
private constructor({
configResult,
ownerSlug,
packageSlug,
iconUrl,
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
description,
orgScopeId,
}: {
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
packageSlug: string;
iconUrl: string;
versionSlug: string;
controlPlaneClient: ControlPlaneClient;
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
llmLogger: ILLMLogger;
description: ProfileDescription;
orgScopeId: string | null;
}) {
this.configResult = configResult;
this.ownerSlug = ownerSlug;
this.packageSlug = packageSlug;
this.iconUrl = iconUrl;
this.versionSlug = versionSlug;
this.controlPlaneClient = controlPlaneClient;
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.llmLogger = llmLogger;
this.description = description;
this.orgScopeId = orgScopeId;
}
static async create({
configResult,
ownerSlug,
packageSlug,
iconUrl,
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
rawYaml,
orgScopeId,
}: {
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
packageSlug: string;
iconUrl: string;
versionSlug: string;
controlPlaneClient: ControlPlaneClient;
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
llmLogger: ILLMLogger;
rawYaml: string;
orgScopeId: string | null;
}): Promise<PlatformProfileLoader> {
const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
const description: ProfileDescription = {
id: `${ownerSlug}/${packageSlug}`,
profileType: "platform",
fullSlug: {
@ -42,14 +106,30 @@ export default class PlatformProfileLoader implements IProfileLoader {
packageSlug,
versionSlug,
},
title: `${ownerSlug}/${packageSlug}@${versionSlug}`,
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
iconUrl: this.iconUrl,
iconUrl: iconUrl,
uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`,
rawYaml,
};
return new PlatformProfileLoader({
configResult,
ownerSlug,
packageSlug,
iconUrl,
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
description,
orgScopeId,
});
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (this.configResult.errors?.length) {
if (this.configResult.errors?.find((e) => e.fatal)) {
return {
config: undefined,
errors: this.configResult.errors,
@ -57,22 +137,28 @@ export default class PlatformProfileLoader implements IProfileLoader {
};
}
const results = await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
undefined,
this.configResult.config,
{
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
const results = await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigYaml: this.configResult.config,
profileId: this.description.id,
orgScopeId: this.orgScopeId,
packageIdentifier: {
uriType: "slug",
fullSlug: {
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
versionSlug: this.versionSlug,
},
},
);
});
return {
...results,
errors: [], // Don't do config validation here, it happens in admin panel
config: results.config,
errors: [...(this.configResult.errors ?? []), ...(results.errors ?? [])],
configLoadInterrupted: results.configLoadInterrupted,
};
}

View file

@ -4,37 +4,63 @@ import {
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
ModelRole,
PackageIdentifier,
} from "@continuedev/config-yaml";
import {
ContinueConfig,
ContinueRcJson,
IDE,
IdeSettings,
ILLMLogger,
SerializedContinueConfig,
Tool,
} from "../../";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { encodeMCPToolUri } from "../../tools/callTool";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
export default async function doLoadConfig(
ide: IDE,
ideSettingsPromise: Promise<IdeSettings>,
controlPlaneClient: ControlPlaneClient,
writeLog: (message: string) => Promise<void>,
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
workspaceId?: string,
): Promise<ConfigResult<ContinueConfig>> {
export default async function doLoadConfig(options: {
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
controlPlaneClient: ControlPlaneClient;
llmLogger: ILLMLogger;
overrideConfigJson?: SerializedContinueConfig;
overrideConfigYaml?: AssistantUnrolled;
profileId: string;
overrideConfigYamlByPath?: string;
orgScopeId: string | null;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<ContinueConfig>> {
const {
ide,
ideSettingsPromise,
controlPlaneClient,
llmLogger,
overrideConfigJson,
overrideConfigYaml,
profileId,
overrideConfigYamlByPath,
orgScopeId,
packageIdentifier,
} = options;
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
const uniqueId = await ide.getUniqueId();
@ -43,30 +69,32 @@ export default async function doLoadConfig(
// Migrations for old config files
// Removes
const configJsonPath = getConfigJsonPath(ideInfo.ideType);
const configJsonPath = getConfigJsonPath();
if (fs.existsSync(configJsonPath)) {
migrateJsonSharedConfig(configJsonPath, ide);
}
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
const configYamlPath = localPathOrUriToPath(
overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType),
);
let newConfig: ContinueConfig | undefined;
let errors: ConfigValidationError[] | undefined;
let configLoadInterrupted = false;
if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
const result = await loadContinueConfigFromYaml(
const result = await loadContinueConfigFromYaml({
ide,
workspaceConfigs.map((c) => JSON.stringify(c)),
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
llmLogger,
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
);
orgScopeId,
packageIdentifier,
workOsAccessToken,
});
newConfig = result.config;
errors = result.errors;
configLoadInterrupted = result.configLoadInterrupted;
@ -75,9 +103,9 @@ export default async function doLoadConfig(
ide,
workspaceConfigs,
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
llmLogger,
workOsAccessToken,
overrideConfigJson,
);
@ -90,6 +118,92 @@ export default async function doLoadConfig(
return { errors, config: newConfig, configLoadInterrupted: true };
}
// TODO using config result but result with non-fatal errors is an antipattern?
// Remove ability have undefined errors, just have an array
errors = [...(errors ?? [])];
// Add rules from .continuerules files
const { rules, errors: continueRulesErrors } =
await getWorkspaceContinueRuleDotFiles(ide);
newConfig.rules.unshift(...rules);
errors.push(...continueRulesErrors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
// Add things from MCP servers
const mcpManager = MCPManagerSingleton.getInstance();
const mcpServerStatuses = mcpManager.getStatuses();
// Slightly hacky just need connection's client to make slash command for now
const serializableStatuses = mcpServerStatuses.map((server) => {
const { client, ...rest } = server;
return rest;
});
newConfig.mcpServerStatuses = serializableStatuses;
for (const server of mcpServerStatuses) {
if (server.status === "connected") {
const serverTools: Tool[] = server.tools.map((tool) => ({
displayTitle: server.name + " " + tool.name,
function: {
description: tool.description,
name: tool.name,
parameters: tool.inputSchema,
},
faviconUrl: server.faviconUrl,
readonly: false,
type: "function" as const,
uri: encodeMCPToolUri(server.id, tool.name),
group: server.name,
}));
newConfig.tools.push(...serverTools);
const serverSlashCommands = server.prompts.map((prompt) =>
constructMcpSlashCommand(
server.client,
prompt.name,
prompt.description,
prompt.arguments?.map((a: any) => a.name),
),
);
newConfig.slashCommands.push(...serverSlashCommands);
const submenuItems = server.resources.map((resource) => ({
title: resource.name,
description: resource.description ?? resource.name,
id: resource.uri,
icon: server.faviconUrl,
}));
if (submenuItems.length > 0) {
const serverContextProvider = new MCPContextProvider({
submenuItems,
mcpId: server.id,
serverName: server.name,
});
newConfig.contextProviders.push(serverContextProvider);
}
}
}
// Detect duplicate tool names
const counts: Record<string, number> = {};
newConfig.tools.forEach((tool) => {
if (counts[tool.function.name]) {
counts[tool.function.name] = counts[tool.function.name] + 1;
} else {
counts[tool.function.name] = 1;
}
});
Object.entries(counts).forEach(([toolName, count]) => {
if (count > 1) {
errors!.push({
fatal: false,
message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`,
});
}
});
newConfig.allowAnonymousTelemetry =
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
@ -117,19 +231,19 @@ export default async function doLoadConfig(
controlPlaneProxyUrl += "/";
}
const controlPlaneProxyInfo = {
workspaceId,
profileId,
controlPlaneProxyUrl,
workOsAccessToken,
};
if (newConfig.analytics) {
await TeamAnalytics.setup(
newConfig.analytics,
uniqueId,
ideInfo.extensionVersion,
controlPlaneClient,
controlPlaneProxyInfo,
);
// await TeamAnalytics.setup(
// newConfig.analytics,
// uniqueId,
// ideInfo.extensionVersion,
// controlPlaneClient,
// controlPlaneProxyInfo,
// );
} else {
await TeamAnalytics.shutdown();
}
@ -147,21 +261,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.modelsByRole.chat.forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
return config;
}

View file

@ -0,0 +1,80 @@
import { ModelRole } from "@continuedev/config-yaml";
import { ContinueConfig, ILLM } from "..";
import { LLMConfigurationStatuses } from "../llm/constants";
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;
// summarize not implemented yet
const roles: ModelRole[] = [
"autocomplete",
"apply",
"edit",
"embed",
"rerank",
"chat",
];
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;
}
// Currently only check for configuration status for apply
if (
role === "apply" &&
newModel?.getConfigurationStatus() !== LLMConfigurationStatuses.VALID
) {
continue;
}
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;
}

View file

@ -1,13 +1,15 @@
import z from "zod";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
Config,
ContinueConfig,
SerializedContinueConfig,
} from "..";
export const sharedConfigSchema = z
.object({
// boolean fields in config.json
allowAnonymousTelemetry: z.boolean(),
disableIndexing: z.boolean(),
disableSessionTitles: z.boolean(),
@ -18,6 +20,7 @@ export const sharedConfigSchema = z
promptPath: z.string(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
codeBlockToolbarPosition: z.enum(["top", "bottom"]),
fontSize: z.number(),
codeWrap: z.boolean(),
@ -65,7 +68,19 @@ export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema {
return salvagedConfig;
}
export function modifyContinueConfigWithSharedConfig<
// 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
@ -92,6 +107,7 @@ export function modifyContinueConfigWithSharedConfig<
configCopy.ui = {
...configCopy.ui,
};
if (sharedConfig.codeBlockToolbarPosition !== undefined) {
configCopy.ui.codeBlockToolbarPosition =
sharedConfig.codeBlockToolbarPosition;
@ -119,6 +135,10 @@ export function modifyContinueConfigWithSharedConfig<
configCopy.disableSessionTitles = sharedConfig.disableSessionTitles;
}
if (sharedConfig.showSessionTabs !== undefined) {
configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs;
}
configCopy.experimental = {
...configCopy.experimental,
};
@ -135,28 +155,3 @@ export function modifyContinueConfigWithSharedConfig<
return configCopy;
}
// continueConfig.tabAutocompleteOptions = {
// ...continueConfig.tabAutocompleteOptions,
// useCache: sharedConfig.useAutocompleteCache,
// disableInFiles: sharedConfig.disableAutocompleteInFiles,
// multilineCompletions: sharedConfig.useAutocompleteMultilineCompletions,
// };
// continueConfig.ui = {
// ...continueConfig.ui,
// codeBlockToolbarPosition: sharedConfig.codeBlockToolbarPosition,
// fontSize: sharedConfig.fontSize,
// codeWrap: sharedConfig.codeWrap,
// displayRawMarkdown: sharedConfig.displayRawMarkdown,
// showChatScrollbar: sharedConfig.showChatScrollbar,
// };
// continueConfig.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
// continueConfig.disableIndexing = sharedConfig.disableIndexing;
// continueConfig.disableIndexing = sharedConfig.disableIndexing;
// continueConfig.disableSessionTitles = sharedConfig.disableSessionTitles;
// continueConfig.experimental = {
// ...continueConfig.experimental,
// useChromiumForDocsCrawling: sharedConfig.useChromiumForDocsCrawling,
// readResponseTTS: sharedConfig.readResponseTTS,
// promptPath: sharedConfig.promptPath,
// };

View file

@ -90,7 +90,7 @@ declare global {
requestOptions?: RequestOptions;
promptTemplates?: Record<string, PromptTemplate>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
llmLogger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
@ -403,6 +403,7 @@ declare global {
| "generated"
| "calling"
| "done"
| "errored"
| "canceled";
// Will exist only on "assistant" messages with tool calls
@ -433,6 +434,94 @@ declare global {
export type ToastType = "info" | "error" | "warning";
export interface LLMInteractionBase {
interactionId: string;
timestamp: number;
}
export interface LLMInteractionStartChat extends LLMInteractionBase {
kind: "startChat";
messages: ChatMessage[];
options: CompletionOptions;
}
export interface LLMInteractionStartComplete extends LLMInteractionBase {
kind: "startComplete";
prompt: string;
options: CompletionOptions;
}
export interface LLMInteractionStartFim extends LLMInteractionBase {
kind: "startFim";
prefix: string;
suffix: string;
options: CompletionOptions;
}
export interface LLMInteractionChunk extends LLMInteractionBase {
kind: "chunk";
chunk: string;
}
export interface LLMInteractionMessage extends LLMInteractionBase {
kind: "message";
message: ChatMessage;
}
export interface LLMInteractionEnd extends LLMInteractionBase {
promptTokens: number;
generatedTokens: number;
thinkingTokens: number;
}
export interface LLMInteractionSuccess extends LLMInteractionEnd {
kind: "success";
}
export interface LLMInteractionCancel extends LLMInteractionEnd {
kind: "cancel";
}
export interface LLMInteractionError extends LLMInteractionEnd {
kind: "error";
name: string;
message: string;
}
export type LLMInteractionItem =
| LLMInteractionStartChat
| LLMInteractionStartComplete
| LLMInteractionStartFim
| LLMInteractionChunk
| LLMInteractionMessage
| LLMInteractionSuccess
| LLMInteractionCancel
| LLMInteractionError;
// When we log a LLM interaction, we want to add the interactionId and timestamp
// in the logger code, so we need a type that omits these members from *each*
// member of the union. This can be done by using the distributive behavior of
// conditional types in Typescript.
//
// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
? Omit<T, K>
: never;
export type LLMInteractionItemDetails = DistributiveOmit<
LLMInteractionItem,
"interactionId" | "timestamp"
>;
export interface ILLMInteractionLog {
logItem(item: LLMInteractionItemDetails): void;
}
export interface ILLMLogger {
createInteractionLog(): ILLMInteractionLog;
}
export interface LLMOptions {
model: string;
@ -446,7 +535,7 @@ declare global {
template?: TemplateType;
promptTemplates?: Record<string, PromptTemplate>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
logger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
aiGatewaySlug?: string;
@ -570,7 +659,6 @@ declare global {
remoteConfigServerUrl: string | undefined;
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
pauseCodebaseIndexOnStart: boolean;
}
@ -870,7 +958,7 @@ declare global {
cacheBehavior?: CacheBehavior;
}
export interface EmbedOptions {
export interface JSONEmbedOptions {
apiBase?: string;
apiKey?: string;
model?: string;

45
core/config/util.test.ts Normal file
View file

@ -0,0 +1,45 @@
import { PromptTemplate } from "..";
import { serializePromptTemplates } from "./util";
describe("serializePromptTemplates", () => {
it("should return undefined for undefined input", () => {
expect(serializePromptTemplates(undefined)).toBeUndefined();
});
it("should convert function templates to empty strings", () => {
const functionTemplate: PromptTemplate = () => "Generated template";
const templates: Record<string, PromptTemplate> = {
template1: functionTemplate,
};
const result = serializePromptTemplates(templates);
expect(result).toEqual({ template1: "" });
});
it("should pass through string templates unchanged", () => {
const templates: Record<string, PromptTemplate> = {
template1: "This is a static template",
template2: "Another static template",
};
const result = serializePromptTemplates(templates);
expect(result).toEqual(templates);
});
it("should handle mixed template types", () => {
const functionTemplate: PromptTemplate = () => "Generated template";
const templates: Record<string, PromptTemplate> = {
function: functionTemplate,
string: "This is a static template",
};
const result = serializePromptTemplates(templates);
expect(result).toEqual({
function: "",
string: "This is a static template",
});
});
});

View file

@ -1,18 +1,18 @@
import { execSync } from "child_process";
import fs from "fs";
import os from "os";
import { ModelConfig } from "@continuedev/config-yaml";
import {
ContextProviderWithParams,
ContinueConfig,
ExperimentalModelRoles,
IDE,
ILLM,
ModelDescription,
ExperimentalModelRoles,
JSONModelDescription,
PromptTemplate,
} from "../";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigJson } from "../util/paths";
import { ConfigHandler } from "./ConfigHandler";
import { editConfigFile } from "../util/paths";
function stringify(obj: any, indentation?: number): string {
return JSON.stringify(
@ -24,78 +24,84 @@ function stringify(obj: any, indentation?: number): string {
);
}
export function addContextProvider(provider: ContextProviderWithParams, configHandler?: ConfigHandler) {
let isAdded = false;
editConfigJson((config) => {
if (!config.contextProviders) {
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,
model: JSONModelDescription,
role?: keyof ExperimentalModelRoles,
) {
editConfigJson((config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
return config;
}
if (config.models?.some((m: any) => m?.title === model.title)) {
model.title = `${model.title} (1)`;
}
config.models.push(model);
// Set the role for the model
if (role) {
if (!config.experimental) {
config.experimental = {};
editConfigFile(
(config) => {
if (config.models?.some((m) => stringify(m) === stringify(model))) {
return config;
}
if (!config.experimental.modelRoles) {
config.experimental.modelRoles = {};
const numMatches = config.models?.reduce(
(prev, curr) => (curr.title.startsWith(model.title) ? prev + 1 : prev),
0,
);
if (numMatches !== 0) {
model.title = `${model.title} (${numMatches})`;
}
config.experimental.modelRoles[role] = model.title;
}
return config;
});
}
config.models.push(model);
export function addOpenAIKey(key: string) {
editConfigJson((config) => {
config.models = config.models
.filter(
(model) =>
model.provider !== "free-trial" || model.model.startsWith("gpt"),
)
.map((m: ModelDescription) => {
if (m.provider === "free-trial") {
m.apiKey = key;
m.provider = "openai";
// Set the role for the model
if (role) {
if (!config.experimental) {
config.experimental = {};
}
return m;
});
return config;
});
if (!config.experimental.modelRoles) {
config.experimental.modelRoles = {};
}
config.experimental.modelRoles[role] = model.title;
}
return config;
},
(config) => {
const numMatches = config.models?.reduce(
(prev, curr) =>
"name" in curr && curr.name.startsWith(model.title) ? prev + 1 : prev,
0,
);
if (numMatches !== 0) {
model.title = `${model.title} (${numMatches})`;
}
if (!config.models) {
config.models = [];
}
const desc: ModelConfig = {
name: model.title,
provider: model.provider,
model: model.model,
apiKey: model.apiKey,
apiBase: model.apiBase,
defaultCompletionOptions: model.completionOptions,
};
if (model.systemMessage) {
desc.chatOptions = {
baseSystemMessage:
DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage,
};
}
config.models.push(desc);
return config;
},
);
}
export function deleteModel(title: string) {
editConfigJson((config) => {
config.models = config.models.filter((m: any) => m.title !== title);
return config;
});
editConfigFile(
(config) => {
config.models = config.models.filter((m: any) => m.title !== title);
return config;
},
(config) => {
config.models = config.models?.filter((m: any) => m.name !== title);
return config;
},
);
}
export function getModelByRole<T extends keyof ExperimentalModelRoles>(
@ -108,7 +114,7 @@ export function getModelByRole<T extends keyof ExperimentalModelRoles>(
return undefined;
}
const matchingModel = config.models.find(
const matchingModel = config.modelsByRole.chat.find(
(model) => model.title === roleTitle,
);
@ -121,11 +127,13 @@ export function getModelByRole<T extends keyof ExperimentalModelRoles>(
*
* 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) {
@ -133,51 +141,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;
@ -187,11 +179,32 @@ 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",
);
}
}
/**
* This is required because users are only able to define prompt templates as a
* string, while internally we also allow prompt templates to be functions
* @param templates
* @returns
*/
export function serializePromptTemplates(
templates: Record<string, PromptTemplate> | undefined,
): Record<string, string> | undefined {
if (!templates) return undefined;
return Object.fromEntries(
Object.entries(templates).map(([key, template]) => {
const serialized = typeof template === "function" ? "" : template;
return [key, serialized];
}),
);
}

View file

@ -1,4 +1,5 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import { ModelDescription, SerializedContinueConfig } from "../";
import { Telemetry } from "../util/posthog";

View file

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

View file

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

View file

@ -1,43 +0,0 @@
import {
clientRender,
PackageSlug,
PlatformClient,
SecretStore,
} from "@continuedev/config-yaml";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
export async function clientRenderHelper(
packageSlug: PackageSlug,
unrolledAssistant: string,
ide: IDE,
controlPlaneClient: ControlPlaneClient,
) {
const ideSecretStore: SecretStore = {
get: async function (secretName: string): Promise<string | undefined> {
const results = await ide.readSecrets([secretName]);
return results[secretName];
},
set: async function (
secretName: string,
secretValue: string,
): Promise<void> {
return await ide.writeSecrets({
[secretName]: secretValue,
});
},
};
const platformClient: PlatformClient = {
resolveFQSNs: controlPlaneClient.resolveFQSNs.bind(controlPlaneClient),
};
const userId = await controlPlaneClient.userId;
return await clientRender(
packageSlug,
unrolledAssistant,
ideSecretStore,
userId ? platformClient : undefined,
);
}

View file

@ -1,13 +1,17 @@
import { ModelConfig, AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { SerializedContinueConfig } from "../..";
/*
TODO this is not functional
*/
export function convertConfigJsonToConfigYaml(
configJson: SerializedContinueConfig,
): AssistantUnrolled {
return {
name: "Local Config",
name: "Local Assistant",
version: "1.0.0",
schema: "v1",
models: [
...configJson.models.map(
(model): ModelConfig => ({
@ -15,10 +19,11 @@ export function convertConfigJsonToConfigYaml(
name: model.title,
// defaultCompletionOptions: model.completionOptions,
provider: model.provider,
roles: ["chat"],
roles: ["chat", "edit", "apply", "summarize"],
}),
),
// ... tabAutocompleteModels
// TODO
// tabAutocompleteModels
// embeddingsModels
// rerankModels
],

View file

@ -4,13 +4,15 @@ import { AssistantUnrolled } from "@continuedev/config-yaml";
export const defaultConfigYaml: AssistantUnrolled = {
models: [],
context: [],
name: "Local Config",
name: "Local Assistant",
version: "1.0.0",
schema: "v1",
};
export const defaultConfigYamlJetBrains: AssistantUnrolled = {
models: [],
context: [],
name: "Local Config",
name: "Local Assistant",
version: "1.0.0",
schema: "v1",
};

View file

@ -1,62 +1,155 @@
import fs from "node:fs";
import {
AssistantUnrolled,
BLOCK_TYPES,
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
MCPServer,
ModelRole,
parseAssistantUnrolled,
PackageIdentifier,
RegistryClient,
Rule,
unrollAssistant,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { dirname } from "node:path";
import {
ContinueConfig,
ExperimentalMCPOptions,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
SlashCommand,
ILLMLogger,
RuleWithSource,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
import { AllRerankers } from "../../context/allRerankers";
import { MCPManagerSingleton } from "../../context/mcp";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
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 { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { allTools } from "../../tools";
import { GlobalContext } from "../../util/GlobalContext";
import { getConfigYamlPath } from "../../util/paths";
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
import { modifyContinueConfigWithSharedConfig } from "../sharedConfig";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { logger } from "../../util/logger";
import { getCleanUriPath } from "../../util/uri";
import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
async function loadConfigYaml(
workspaceConfigs: string[],
rawYaml: string,
overrideConfigYaml: AssistantUnrolled | undefined,
ide: IDE,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<AssistantUnrolled>> {
const ideSettings = await ide.getIdeSettings();
function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
if (typeof rule === "string") {
return {
rule: rule,
source: "rules-block",
};
} else {
return {
source: "rules-block",
rule: rule.rule,
globs: rule.globs,
name: rule.name,
};
}
}
function convertYamlMcpToContinueMcp(
server: MCPServer,
): ExperimentalMCPOptions {
return {
transport: {
type: "stdio",
command: server.command,
args: server.args ?? [],
env: server.env,
},
};
}
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
controlPlaneClient: ControlPlaneClient;
orgScopeId: string | null;
ideSettings: IdeSettings;
ide: IDE;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<AssistantUnrolled>> {
const {
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
ideSettings,
ide,
packageIdentifier,
} = options;
// Add local .continue blocks
const allLocalBlocks: PackageIdentifier[] = [];
for (const blockType of BLOCK_TYPES) {
const localBlocks = await getAllDotContinueYamlFiles(
ide,
{ includeGlobal: true, includeWorkspace: true },
blockType,
);
allLocalBlocks.push(
...localBlocks.map((b) => ({
uriType: "file" as const,
filePath: b.path,
})),
);
}
const rootPath =
packageIdentifier.uriType === "file"
? dirname(getCleanUriPath(packageIdentifier.filePath))
: undefined;
logger.info(
`Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
);
let config =
overrideConfigYaml ??
// (ideSettings.continueTestEnvironment === "production"
// ? await clientRenderHelper(rawYaml, ide, controlPlaneClient)
// :
parseAssistantUnrolled(rawYaml);
// );
const errors = validateConfigYaml(config);
// This is how we allow use of blocks locally
(await unrollAssistant(
packageIdentifier,
new RegistryClient({
accessToken: await controlPlaneClient.getAccessToken(),
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
.CONTROL_PLANE_URL,
rootPath,
}),
{
currentUserSlug: "",
onPremProxyUrl: null,
orgScopeId,
platformClient: new LocalPlatformClient(
orgScopeId,
controlPlaneClient,
ide,
),
renderSecrets: true,
injectBlocks: allLocalBlocks,
},
));
const errors = isAssistantUnrolledNonNullable(config)
? validateConfigYaml(config)
: [
{
fatal: true,
message: "Assistant includes blocks that don't exist",
},
];
if (errors?.some((error) => error.fatal)) {
return {
@ -69,142 +162,234 @@ async function loadConfigYaml(
// 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.fatal,
})),
errors,
configLoadInterrupted: false,
};
}
async function slashCommandsFromV1PromptFiles(
ide: IDE,
): Promise<SlashCommand[]> {
const slashCommands: SlashCommand[] = [];
async function configYamlToContinueConfig(options: {
config: AssistantUnrolled;
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
allowFreeTrial?: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let {
config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
allowFreeTrial,
} = options;
allowFreeTrial = allowFreeTrial ?? true;
const promptFiles = await getAllPromptFiles(ide, undefined, true);
const localErrors: ConfigValidationError[] = [];
for (const file of promptFiles) {
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
if (slashCommand) {
slashCommands.push(slashCommand);
const continueConfig: ContinueConfig = {
slashCommands: [],
tools: [...allTools],
mcpServerStatuses: [],
contextProviders: [],
modelsByRole: {
chat: [],
edit: [],
apply: [],
embed: [],
autocomplete: [],
rerank: [],
summarize: [],
},
selectedModelByRole: {
chat: null,
edit: null, // not currently used
apply: null,
embed: null,
autocomplete: null,
rerank: null,
summarize: null,
},
rules: [],
};
// Right now, if there are any missing packages in the config, then we will just throw an error
if (!isAssistantUnrolledNonNullable(config)) {
return {
config: continueConfig,
errors: [
{
message: "Found missing blocks in config.yaml",
fatal: true,
},
],
};
}
for (const rule of config.rules ?? []) {
continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
}
continueConfig.data = config.data;
continueConfig.docs = config.docs?.map((doc) => ({
title: doc.name,
startUrl: doc.startUrl,
rootUrl: doc.rootUrl,
faviconUrl: doc.faviconUrl,
}));
continueConfig.experimental = {
modelContextProtocolServers: config.mcpServers?.map(
convertYamlMcpToContinueMcp,
),
};
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
promptFiles.forEach((file) => {
try {
const slashCommand = slashCommandFromPromptFileV1(
file.path,
file.content,
);
if (slashCommand) {
continueConfig.slashCommands?.push(slashCommand);
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
});
}
});
} catch (e) {
localErrors.push({
fatal: false,
message: `Error loading local prompt files: ${e instanceof Error ? e.message : e}`,
});
}
config.prompts?.forEach((prompt) => {
try {
const slashCommand = slashFromCustomCommand(prompt);
continueConfig.slashCommands?.push(slashCommand);
} catch (e) {
localErrors.push({
message: `Error loading prompt ${prompt.name}: ${e instanceof Error ? e.message : e}`,
fatal: false,
});
}
});
// Models
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
try {
const llms = await llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config: continueConfig,
});
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 } = model;
if (provider === "transformers.js") {
if (ideInfo.ideType === "vscode") {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
} else {
localErrors.push({
fatal: false,
message: `Transformers.js embeddings provider not supported in this IDE.`,
});
}
} else {
continueConfig.modelsByRole.embed.push(...llms);
}
}
if (model.roles?.includes("rerank")) {
continueConfig.modelsByRole.rerank.push(...llms);
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to load model:\nName: ${model.name}\nModel: ${model.model}\nProvider: ${model.provider}\n${e instanceof Error ? e.message : e}`,
});
}
}
return slashCommands;
}
async function configYamlToContinueConfig(
config: AssistantUnrolled,
ide: IDE,
ideSettings: IdeSettings,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
allowFreeTrial: boolean = true,
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
const continueConfig: ContinueConfig = {
slashCommands: [
...(await slashCommandsFromV1PromptFiles(ide)),
...(config.prompts?.map(slashFromCustomCommand) ?? []),
],
models: [],
tabAutocompleteModels: [],
tools: allTools,
systemMessage: config.rules?.join("\n"),
embeddingsProvider: new TransformersJsEmbeddingsProvider(),
experimental: {
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: [],
};
// Models
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
// Main model array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.models.push(...llms);
}
if (model.roles?.includes("autocomplete")) {
// Autocomplete models array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.tabAutocompleteModels?.push(...llms);
}
if (
model.roles?.includes("apply") &&
!continueConfig.experimental?.modelRoles?.applyCodeBlock
) {
continueConfig.experimental ??= {};
continueConfig.experimental!.modelRoles ??= {};
continueConfig.experimental!.modelRoles!.applyCodeBlock = model.name;
}
if (
model.roles?.includes("edit") &&
!continueConfig.experimental?.modelRoles?.inlineEdit
) {
continueConfig.experimental ??= {};
continueConfig.experimental!.modelRoles ??= {};
continueConfig.experimental!.modelRoles!.inlineEdit = model.name;
}
// 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) {
// Obtain auth token (iff free trial being used)
const freeTrialModels = continueConfig.models.filter(
const freeTrialModels = continueConfig.modelsByRole.chat.filter(
(model) => model.providerName === "free-trial",
);
if (freeTrialModels.length > 0) {
const ghAuthToken = await ide.getGitHubAuthToken({});
for (const model of freeTrialModels) {
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
try {
const ghAuthToken = await ide.getGitHubAuthToken({});
for (const model of freeTrialModels) {
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`,
});
// Remove free trial models
continueConfig.modelsByRole.chat =
continueConfig.modelsByRole.chat.filter(
(model) => model.providerName !== "free-trial",
);
}
}
} else {
// Remove free trial models
continueConfig.models = continueConfig.models.filter(
continueConfig.modelsByRole.chat = continueConfig.modelsByRole.chat.filter(
(model) => model.providerName !== "free-trial",
);
}
// TODO: Split into model roles.
// Context providers
const codebaseContextParams: IContextProvider[] =
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
@ -212,7 +397,6 @@ async function configYamlToContinueConfig(
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
new PromptFilesContextProvider({}),
];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
@ -224,11 +408,17 @@ async function configYamlToContinueConfig(
const cls = contextProviderClassFromName(context.provider) as any;
if (!cls) {
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
console.warn(`Unknown context provider ${context.provider}`);
localErrors.push({
fatal: false,
message: `Unknown context provider ${context.provider}`,
});
}
return undefined;
}
const instance: IContextProvider = new cls(context.params ?? {});
const instance: IContextProvider = new cls({
name: context.name,
...context.params,
});
return instance;
})
.filter((p) => !!p) ?? []) as IContextProvider[];
@ -243,124 +433,57 @@ async function configYamlToContinueConfig(
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
// Embeddings Provider
// IMPORTANT this currently will grab the first model found with an embed role
const embedConfig = config.models?.find((model) =>
model.roles?.includes("embed"),
);
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
// IMPORTANT this currently will grab the first model found with a rerank role
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,
}),
);
}
}
// Apply MCP if specified
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
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;
}
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);
}) ?? [],
mcpManager.setConnections(
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
transport: {
type: "stdio",
args: [],
...server,
},
})),
false,
);
return { config: continueConfig, errors };
return { config: continueConfig, errors: localErrors };
}
export async function loadContinueConfigFromYaml(
ide: IDE,
workspaceConfigs: string[],
ideSettings: IdeSettings,
ideType: IdeType,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<ContinueConfig>> {
const rawYaml =
overrideConfigYaml === undefined
? fs.readFileSync(getConfigYamlPath(ideType), "utf-8")
: "";
const configYamlResult = await loadConfigYaml(
workspaceConfigs,
rawYaml,
overrideConfigYaml,
export async function loadContinueConfigFromYaml(options: {
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
overrideConfigYaml: AssistantUnrolled | undefined;
controlPlaneClient: ControlPlaneClient;
orgScopeId: string | null;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<ContinueConfig>> {
const {
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
overrideConfigYaml,
controlPlaneClient,
);
orgScopeId,
packageIdentifier,
} = options;
const configYamlResult = await loadConfigYaml({
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
ideSettings,
ide,
packageIdentifier,
});
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
return {
@ -370,36 +493,32 @@ export async function loadContinueConfigFromYaml(
};
}
const { config: continueConfig, errors } = await configYamlToContinueConfig(
configYamlResult.config,
ide,
ideSettings,
uniqueId,
writeLog,
workOsAccessToken,
platformConfigMetadata,
);
const systemPromptDotFile = await getSystemPromptDotFile(ide);
if (systemPromptDotFile) {
if (continueConfig.systemMessage) {
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
} else {
continueConfig.systemMessage = systemPromptDotFile;
}
}
const { config: continueConfig, errors: localErrors } =
await configYamlToContinueConfig({
config: configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
});
// Apply shared config
// TODO: override several of these values with user/org shared config
// Don't try catch this - has security implications and failure should be fatal
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyContinueConfigWithSharedConfig(
const withShared = modifyAnyConfigWithSharedConfig(
continueConfig,
sharedConfig,
);
if (withShared.allowAnonymousTelemetry === undefined) {
withShared.allowAnonymousTelemetry = true;
}
return {
config: withShared,
errors: [...(configYamlResult.errors ?? []), ...errors],
errors: [...(configYamlResult.errors ?? []), ...localErrors],
configLoadInterrupted: false,
};
}

View file

@ -1,9 +1,14 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { IDE, IdeSettings, LLMOptions } from "../..";
import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
LLMOptions,
} from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
const AUTODETECT = "AUTODETECT";
@ -13,30 +18,38 @@ function getModelClass(
return LLMClasses.find((llm) => llm.providerName === model.provider);
}
function getContinueProxyModelName(
ownerSlug: string,
packageSlug: string,
model: ModelConfig,
): string {
return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
}
// 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> {
async function modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM | undefined> {
const cls = getModelClass(model);
if (!cls) {
return undefined;
}
const { capabilities, ...rest } = model;
let options: LLMOptions = {
...model,
...rest,
contextLength: model.defaultCompletionOptions?.contextLength,
completionOptions: {
...(model.defaultCompletionOptions ?? {}),
model: model.model,
@ -44,27 +57,104 @@ async function modelConfigToBaseLLM(
model.defaultCompletionOptions?.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens,
},
writeLog,
logger: llmLogger,
uniqueId,
title: model.name,
systemMessage,
template: model.promptTemplates?.chatTemplate,
promptTemplates: model.promptTemplates,
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
capabilities: {
tools: model.capabilities?.includes("tool_use"),
uploadImage: model.capabilities?.includes("image_input"),
},
};
// Model capabilities - need to be undefined if not found
// To fallback to our autodetection
if (capabilities?.find((c) => c === "tool_use")) {
options.capabilities = {
...options.capabilities,
tools: true,
};
}
if (capabilities?.find((c) => c === "image_input")) {
options.capabilities = {
...options.capabilities,
uploadImage: true,
};
}
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;
}
async function autodetectModels(
llm: BaseLLM,
model: ModelConfig,
ide: IDE,
uniqueId: string,
ideSettings: IdeSettings,
writeLog: (log: string) => Promise<void>,
platformConfigMetadata: PlatformConfigMetadata | undefined,
systemMessage: string | undefined,
): Promise<BaseLLM[]> {
async function autodetectModels({
llm,
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
llm: BaseLLM;
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
try {
const modelNames = await llm.listModels();
const detectedModels = await Promise.all(
@ -74,18 +164,17 @@ async function autodetectModels(
return undefined;
}
return await modelConfigToBaseLLM(
{
return await modelConfigToBaseLLM({
model: {
...model,
model: modelName,
name: `${llm.title} - ${modelName}`,
name: modelName,
},
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
systemMessage,
);
llmLogger,
config,
});
}),
);
return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[];
@ -95,38 +184,42 @@ async function autodetectModels(
}
}
export async function llmsFromModelConfig(
model: ModelConfig,
ide: IDE,
uniqueId: string,
ideSettings: IdeSettings,
writeLog: (log: string) => Promise<void>,
platformConfigMetadata: PlatformConfigMetadata | undefined,
systemMessage: string | undefined,
): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM(
export async function llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
systemMessage,
);
llmLogger,
config,
});
if (!baseLlm) {
return [];
}
if (model.model === AUTODETECT) {
const models = await autodetectModels(
baseLlm,
const models = await autodetectModels({
llm: baseLlm,
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
systemMessage,
);
llmLogger,
config,
});
return models;
} else {
return [baseLlm];

View file

@ -1,17 +0,0 @@
import Bedrock from "../llm/llms/Bedrock";
import Cohere from "../llm/llms/Cohere";
import FreeTrial from "../llm/llms/FreeTrial";
import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI";
import { LLMReranker } from "../llm/llms/llm";
import ContinueProxy from "../llm/llms/stubs/ContinueProxy";
import Voyage from "../llm/llms/Voyage";
export const AllRerankers: { [key: string]: any } = {
cohere: Cohere,
bedrock: Bedrock,
llm: LLMReranker,
voyage: Voyage,
"free-trial": FreeTrial,
"huggingface-tei": HuggingFaceTEI,
"continue-proxy": ContinueProxy,
};

View file

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

View file

@ -0,0 +1,245 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import {
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
MCPResource,
MCPServerStatus,
MCPTool,
} from "../..";
export const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds
class MCPConnection {
public client: Client;
private transport: Transport;
private connectionPromise: Promise<unknown> | null = null;
public abortController: AbortController;
public status: MCPConnectionStatus = "not-connected";
public errors: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
constructor(public options: MCPOptions) {
this.transport = this.constructTransport(options);
this.client = new Client(
{
name: "continue-client",
version: "1.0.0",
},
{
capabilities: {},
},
);
this.abortController = new AbortController();
}
async disconnect() {
this.abortController.abort();
await this.client.close();
await this.transport.close();
}
private constructTransport(options: MCPOptions): Transport {
switch (options.transport.type) {
case "stdio":
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,
});
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
case "sse":
return new SSEClientTransport(new URL(options.transport.url));
default:
throw new Error(
`Unsupported transport type: ${(options.transport as any).type}`,
);
}
}
getStatus(): MCPServerStatus {
return {
...this.options,
errors: this.errors,
prompts: this.prompts,
resources: this.resources,
tools: this.tools,
status: this.status,
};
}
async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) {
if (!forceRefresh) {
// Already connected
if (this.status === "connected") {
return;
}
// Connection is already in progress; wait for it to complete
if (this.connectionPromise) {
await this.connectionPromise;
return;
}
}
this.status = "connecting";
this.tools = [];
this.prompts = [];
this.resources = [];
this.errors = [];
this.abortController.abort();
this.abortController = new AbortController();
this.connectionPromise = Promise.race([
// If aborted by a refresh or other, cancel and don't do anything
new Promise((resolve) => {
externalSignal.addEventListener("abort", () => {
resolve(undefined);
});
}),
new Promise((resolve) => {
this.abortController.signal.addEventListener("abort", () => {
resolve(undefined);
});
}),
(async () => {
const timeoutController = new AbortController();
const connectionTimeout = setTimeout(
() => timeoutController.abort(),
this.options.timeout ?? DEFAULT_MCP_TIMEOUT,
);
try {
await Promise.race([
new Promise((_, reject) => {
timeoutController.signal.addEventListener("abort", () => {
reject(new Error("Connection timed out"));
});
}),
(async () => {
this.transport = this.constructTransport(this.options);
try {
await this.client.connect(this.transport);
} catch (error) {
// Allow the case where for whatever reason is already connected
if (
error instanceof Error &&
error.message.startsWith(
"StdioClientTransport already started",
)
) {
await this.client.close();
await this.client.connect(this.transport);
} else {
throw error;
}
}
// TODO register server notification handlers
// this.client.transport?.onmessage(msg => console.log())
// this.client.setNotificationHandler(, notification => {
// console.log(notification)
// })
const capabilities = this.client.getServerCapabilities();
// Resources <—> Context Provider
if (capabilities?.resources) {
try {
const { resources } = await this.client.listResources(
{},
{ signal: timeoutController.signal },
);
this.resources = resources;
} catch (e) {
let errorMessage = `Error loading resources for MCP Server ${this.options.name}`;
if (e instanceof Error) {
errorMessage += `: ${e.message}`;
}
this.errors.push(errorMessage);
}
}
// Tools <—> Tools
if (capabilities?.tools) {
try {
const { tools } = await this.client.listTools(
{},
{ signal: timeoutController.signal },
);
this.tools = tools;
} catch (e) {
let errorMessage = `Error loading tools for MCP Server ${this.options.name}`;
if (e instanceof Error) {
errorMessage += `: ${e.message}`;
}
this.errors.push(errorMessage);
}
}
// Prompts <—> Slash commands
if (capabilities?.prompts) {
try {
const { prompts } = await this.client.listPrompts(
{},
{ signal: timeoutController.signal },
);
this.prompts = prompts;
} catch (e) {
let errorMessage = `Error loading prompts for MCP Server ${this.options.name}`;
if (e instanceof Error) {
errorMessage += `: ${e.message}`;
}
this.errors.push(errorMessage);
}
}
this.status = "connected";
})(),
]);
} catch (error) {
// Otherwise it's a connection error
let errorMessage = `Failed to connect to MCP server ${this.options.name}`;
if (error instanceof Error) {
const msg = error.message.toLowerCase();
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
errorMessage += `command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
} else {
errorMessage += ": " + error.message;
}
}
this.status = "error";
this.errors.push(errorMessage);
} finally {
this.connectionPromise = null;
clearTimeout(connectionTimeout);
}
})(),
]);
await this.connectionPromise;
}
}
export default MCPConnection;

View file

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

View file

@ -0,0 +1,164 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import {
MCPOptions,
MCPServerStatus,
StdioOptions,
TransportOptions,
} from "../..";
import MCPConnection from "./MCPConnection";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
public onConnectionsRefreshed?: () => void;
public connections: Map<string, MCPConnection> = new Map();
private abortController: AbortController = new AbortController();
private constructor() {}
public static getInstance(): MCPManagerSingleton {
if (!MCPManagerSingleton.instance) {
MCPManagerSingleton.instance = new MCPManagerSingleton();
}
return MCPManagerSingleton.instance;
}
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id)!;
}
}
getConnection(id: string) {
return this.connections.get(id);
}
async removeConnection(id: string) {
const connection = this.connections.get(id);
if (connection) {
await connection.client.close();
}
this.connections.delete(id);
}
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
let refresh = false;
// Remove any connections that are no longer in config
Array.from(this.connections.entries()).forEach(([id, connection]) => {
if (
!servers.find(
// Refresh the connection if TransportOptions changed
(s) =>
s.id === id &&
this.compareTransportOptions(
connection.options.transport,
s.transport,
),
)
) {
refresh = true;
connection.abortController.abort();
void connection.client.close();
this.connections.delete(id);
}
});
// Add any connections that are not yet in manager
servers.forEach((server) => {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
} else {
const conn = this.connections.get(server.id);
if (conn) {
// We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
conn.options = server;
}
}
});
// NOTE the id is made by stringifying the options
if (refresh) {
void this.refreshConnections(forceRefresh);
}
}
private compareTransportOptions(
a: TransportOptions,
b: TransportOptions,
): boolean {
if (a.type !== b.type) {
return false;
}
if (a.type === "stdio" && b.type === "stdio") {
return (
a.command === b.command &&
JSON.stringify(a.args) === JSON.stringify(b.args) &&
this.compareEnv(a, b)
);
} else if (a.type !== "stdio" && b.type !== "stdio") {
return a.url === b.url;
}
return false;
}
private compareEnv(a: StdioOptions, b: StdioOptions): boolean {
const aEnv = a.env ?? {};
const bEnv = b.env ?? {};
const aKeys = Object.keys(aEnv);
const bKeys = Object.keys(bEnv);
return (
aKeys.length === bKeys.length &&
aKeys.every((key) => aEnv[key] === bEnv[key])
);
}
async refreshConnection(serverId: string) {
const connection = this.connections.get(serverId);
if (!connection) {
throw new Error(`MCP Connection ${serverId} not found`);
}
await connection.connectClient(true, this.abortController.signal);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
}
}
async refreshConnections(force: boolean) {
this.abortController.abort();
this.abortController = new AbortController();
await Promise.race([
new Promise((resolve) => {
this.abortController.signal.addEventListener("abort", () => {
resolve(undefined);
});
}),
(async () => {
await Promise.all(
Array.from(this.connections.values()).map(async (connection) => {
await connection.connectClient(force, this.abortController.signal);
}),
);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
}
})(),
]);
}
getStatuses(): (MCPServerStatus & { client: Client })[] {
return Array.from(this.connections.values()).map((connection) => ({
...connection.getStatus(),
client: connection.client,
}));
}
}

View file

@ -1,212 +0,0 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { ConfigValidationError } from "@continuedev/config-yaml";
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { encodeMCPToolUri } from "../../tools/callTool";
import MCPContextProvider from "../providers/MCPContextProvider";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
private connections: Map<string, MCPConnection> = new Map();
private constructor() {}
public static getInstance(): MCPManagerSingleton {
if (!MCPManagerSingleton.instance) {
MCPManagerSingleton.instance = new MCPManagerSingleton();
}
return MCPManagerSingleton.instance;
}
createConnection(id: string, options: MCPOptions): MCPConnection | undefined {
if (!this.connections.has(id)) {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id);
}
}
getConnection(id: string) {
return this.connections.get(id);
}
async removeConnection(id: string) {
const connection = this.connections.get(id);
if (connection) {
await connection.client.close();
}
this.connections.delete(id);
}
}
class MCPConnection {
public client: Client;
private transport: Transport;
constructor(private readonly options: MCPOptions) {
this.transport = this.constructTransport(options);
this.client = new Client(
{
name: "continue-client",
version: "1.0.0",
},
{
capabilities: {},
},
);
}
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,
});
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
case "sse":
return new SSEClientTransport(new URL(options.transport.url));
default:
throw new Error(
`Unsupported transport type: ${(options.transport as any).type}`,
);
}
}
private isConnected: boolean = false;
private connectPromise: Promise<void> | null = null;
private async connectClient() {
if (this.isConnected) {
// Already connected
return;
}
if (this.connectPromise) {
// Connection is already in progress; wait for it to complete
await this.connectPromise;
return;
}
this.connectPromise = (async () => {
await this.client.connect(this.transport);
this.isConnected = true;
})();
try {
await this.connectPromise;
} finally {
// Reset the promise so future attempts can try again if necessary
this.connectPromise = null;
}
}
async modifyConfig(
config: ContinueConfig,
mcpId: string,
signal: AbortSignal,
name: string,
faviconUrl: string | undefined,
): Promise<ConfigValidationError | undefined> {
try {
await Promise.race([
this.connectClient(),
new Promise((_, reject) => {
signal.addEventListener("abort", () =>
reject(new Error("Connection aborted")),
);
}),
]);
} catch (error: any) {
if (signal.aborted) {
throw new Error("Operation aborted");
}
if (!error.message.startsWith("StdioClientTransport already started")) {
return {
fatal: false,
message: `Failed to connect to MCP: ${error.message}`,
};
}
}
const capabilities = this.client.getServerCapabilities();
// Resources <—> Context Provider
if (capabilities?.resources) {
const { resources } = await this.client.listResources({}, { signal });
const submenuItems = resources.map((resource: any) => ({
title: resource.name,
description: resource.description,
id: resource.uri,
icon: faviconUrl,
}));
if (!config.contextProviders) {
config.contextProviders = [];
}
config.contextProviders.push(
new MCPContextProvider({
submenuItems,
}),
);
}
// Tools <—> Tools
if (capabilities?.tools) {
const { tools } = await this.client.listTools({}, { signal });
const continueTools: Tool[] = tools.map((tool: any) => ({
displayTitle: name + " " + tool.name,
function: {
description: tool.description,
name: tool.name,
parameters: tool.inputSchema,
},
faviconUrl,
readonly: false,
type: "function",
wouldLikeTo: `use the ${name} ${tool.name} tool`,
uri: encodeMCPToolUri(mcpId, tool.name),
}));
config.tools = [...continueTools, ...config.tools];
}
// Prompts <—> Slash commands
if (capabilities?.prompts) {
const { prompts } = await this.client.listPrompts({}, { signal });
if (!config.slashCommands) {
config.slashCommands = [];
}
const slashCommands: SlashCommand[] = prompts.map((prompt: any) =>
constructMcpSlashCommand(
this.client,
prompt.name,
prompt.description,
prompt.arguments?.map((a: any) => a.name),
),
);
config.slashCommands.push(...slashCommands);
}
}
}
export default MCPConnection;

View file

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

View file

@ -5,10 +5,10 @@ import {
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
IDE,
LoadSubmenuItemsArgs,
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
@ -23,7 +23,7 @@ class DocsContextProvider extends BaseContextProvider {
// 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: "<docs-context-provider>",
renderInlineAs: "",
};
constructor(options: any) {
@ -36,6 +36,7 @@ class DocsContextProvider extends BaseContextProvider {
chunks: Chunk[],
reranker: NonNullable<ContextProviderExtras["reranker"]>,
fullInput: ContextProviderExtras["fullInput"],
ide: IDE,
) {
let chunksCopy = [...chunks];
@ -51,7 +52,7 @@ class DocsContextProvider extends BaseContextProvider {
this.options?.nFinal ?? DocsContextProvider.nFinal,
);
} catch (e) {
console.warn(`Failed to rerank docs results: ${e}`);
void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`);
chunksCopy = chunksCopy.splice(
0,
@ -62,23 +63,12 @@ class DocsContextProvider extends BaseContextProvider {
return chunksCopy;
}
private _sortByPreIndexedDocs(
private _sortAlphabetically(
submenuItems: ContextSubmenuItem[],
): ContextSubmenuItem[] {
// Sort submenuItems such that the objects with titles which don't occur in configs occur first, and alphabetized
// Sort submenu items alphabetically by title
return submenuItems.sort((a, b) => {
const aTitleInConfigs = a.metadata?.preIndexed ?? false;
const bTitleInConfigs = b.metadata?.preIndexed ?? false;
// Primary criterion: Items not in configs come first
if (!aTitleInConfigs && bTitleInConfigs) {
return -1;
} else if (aTitleInConfigs && !bTitleInConfigs) {
return 1;
} else {
// Secondary criterion: Alphabetical order when both items are in the same category
return a.title.toString().localeCompare(b.title.toString());
}
return a.title.toString().localeCompare(b.title.toString());
});
}
@ -116,6 +106,7 @@ class DocsContextProvider extends BaseContextProvider {
chunks,
extras.reranker,
extras.fullInput,
extras.ide,
);
}
@ -162,13 +153,13 @@ class DocsContextProvider extends BaseContextProvider {
}
await docsService.isInitialized;
// Create map of docs url -> submenu item
const submenuItemsMap = new Map<string, ContextSubmenuItem>();
// Create an array to hold submenu items
const submenuItems: ContextSubmenuItem[] = [];
// Add custom docs from config
// Get all indexed docs from the database
const docs = (await docsService.listMetadata()) ?? [];
for (const { startUrl, title, favicon } of docs) {
submenuItemsMap.set(startUrl, {
submenuItems.push({
title,
id: startUrl,
description: new URL(startUrl).hostname,
@ -176,32 +167,8 @@ class DocsContextProvider extends BaseContextProvider {
});
}
// Add pre-indexed docs if supported
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,
description: new URL(startUrl).hostname,
metadata: {
preIndexed: true,
},
});
}
}
// Create array and sort if pre-indexed is supported
const submenuItems = Array.from(submenuItemsMap.values());
if (canUsePreindexedDocs) {
return this._sortByPreIndexedDocs(submenuItems);
}
return submenuItems;
// Sort alphabetically
return this._sortAlphabetically(submenuItems);
}
}

View file

@ -8,9 +8,9 @@ import {
} from "../../";
import { walkDirs } from "../../indexing/walkDir";
import {
getUriPathBasename,
getShortestUniqueRelativeUriPaths,
getUriDescription,
getUriPathBasename,
} from "../../util/uri";
const MAX_SUBMENU_ITEMS = 10_000;
@ -53,7 +53,13 @@ class FileContextProvider extends BaseContextProvider {
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const workspaceDirs = await args.ide.getWorkspaceDirs();
const results = await walkDirs(args.ide, undefined, workspaceDirs);
const results = await walkDirs(
args.ide,
{
source: "load submenu items - file",
},
workspaceDirs,
);
const files = results.flat().slice(-MAX_SUBMENU_ITEMS);
const withUniquePaths = getShortestUniqueRelativeUriPaths(
files,

View file

@ -50,7 +50,9 @@ class FileTreeContextProvider extends BaseContextProvider {
directories: [],
};
const uris = await walkDir(workspaceDir, extras.ide);
const uris = await walkDir(workspaceDir, extras.ide, {
source: "get context items - file tree",
});
const relativePaths = uris.map(
(uri) => findUriInDirs(uri, [workspaceDir]).relativePathOrBasename,
);

View file

@ -35,7 +35,8 @@ class FolderContextProvider extends BaseContextProvider {
const folders = await walkDirs(
args.ide,
{
onlyDirs: true,
include: "dirs",
source: "load submenu items - folder",
},
workspaceDirs,
);

View file

@ -1,12 +1,40 @@
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import { fileURLToPath} from "node:url";
const runGitCommand = (args: string[], cwd: string): Promise<string> => {
return new Promise((resolve, reject) => {
// First argument is the command, rest are arguments
const gitProcess = spawn("git", args, {
cwd,
});
let stdout = "";
let stderr = "";
gitProcess.stdout.on("data", (data) => {
stdout += data.toString();
});
gitProcess.stderr.on("data", (data) => {
stderr += data.toString();
});
gitProcess.on("close", (code) => {
if (code !== 0) {
reject(new Error(`Git command failed: ${stderr}`));
return;
}
resolve(stdout);
});
});
};
class GitCommitContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -16,29 +44,55 @@ class GitCommitContextProvider extends BaseContextProvider {
type: "submenu",
};
async getContextItems(query: string, extras: ContextProviderExtras): Promise<ContextItem[]> {
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10;
if (typeof lastXCommitsDepth !== "number") {
throw new Error("LastXCommitsDepth must be a number");
}
const topLevelDir = fileURLToPath((await extras.ide.getWorkspaceDirs())[0]);
try{
if(query.includes("last ")){
try {
if (query.includes("last ")) {
const content = await runGitCommand(
[
"--no-pager",
"log",
'--pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b"',
"-p",
"-n",
lastXCommitsDepth.toString(),
],
topLevelDir,
);
return [
{
name: query,
description: query,
content: (await extras.ide.subprocess(`git --no-pager log --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" -p -n ${lastXCommitsDepth}`, topLevelDir))[0],
}
]
}
else{
name: query,
description: query,
content,
},
];
} else {
const content = await runGitCommand(
[
"--no-pager",
"show",
'--pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b"',
query,
],
topLevelDir,
);
return [
{
name: query,
description: `commit ${query}`,
content: (await extras.ide.subprocess(`git --no-pager show --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" ${query}`, topLevelDir))[0],
}
]
content,
},
];
}
}catch(err){
} catch (err) {
return [];
}
}
@ -48,24 +102,48 @@ class GitCommitContextProvider extends BaseContextProvider {
): Promise<ContextSubmenuItem[]> {
const depth = this.options?.Depth ?? 50;
const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10;
const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]);
try{
const [gitResult] = await args.ide.subprocess(`git --no-pager log --pretty=format:"%H%x00%s" -n ${depth}`, topLevelDir);
const recentCommits = [{ id: `last ${lastXCommitsDepth} commits`, title: `last ${lastXCommitsDepth} commits`, description: "recent commits" }];
const allCommits = gitResult
.trim()
.split('\n')
.map(line => {
const [hash, message] = line.split("\0");
return {
id: hash,
title: message,
description: hash
};
}
if (typeof depth !== "number") {
throw new Error("Depth must be a number");
}
if (typeof lastXCommitsDepth !== "number") {
throw new Error("LastXCommitsDepth must be a number");
}
const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]);
try {
const gitResult = await runGitCommand(
[
"--no-pager",
"log",
'--pretty=format:"%H%x00%s"',
`-n`,
depth.toString(),
],
topLevelDir,
);
const recentCommits = [
{
id: `last ${lastXCommitsDepth} commits`,
title: `last ${lastXCommitsDepth} commits`,
description: "recent commits",
},
];
const allCommits = gitResult
.trim()
.split("\n")
.map((line) => {
let [hash, message] = line.split("\0");
hash = hash.replace(/"/g, "");
message = message.replace(/"/g, "");
return {
id: hash,
title: message,
description: hash,
};
});
return recentCommits.concat(allCommits);
}catch(err: any){
} catch (err: any) {
//could be nice to toast the error eg. not a git repo or git is not installed
return [];
}

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

@ -1,7 +1,9 @@
import isLocalhost from "is-localhost-ip";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
IDE,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
@ -14,33 +16,51 @@ class HttpContextProvider extends BaseContextProvider {
renderInlineAs: "",
};
private async getWorkspacePath(ide: IDE, url: URL) {
try {
const currentFile = await ide.getCurrentFile();
// `isLocalhost` actually also returns true for other local addresses, not just localhost
return await isLocalhost(url.hostname) ?
(await ide.getWorkspaceDirs()).find(workspaceDirectory => {
return currentFile?.path.startsWith(workspaceDirectory)
}) : undefined
} catch (e) {
return undefined;
}
}
override get description(): ContextProviderDescription {
return {
title: this.options.title || "http",
displayTitle: this.options.displayTitle || "HTTP",
title: this.options.title || HttpContextProvider.description.title,
displayTitle:
this.options.displayTitle ||
this.options.name ||
HttpContextProvider.description.displayTitle,
description:
this.options.description ||
"Retrieve a context item from a custom server",
type: "normal",
this.options.description || HttpContextProvider.description.description,
type: HttpContextProvider.description.type,
renderInlineAs:
this.options.renderInlineAs ||
HttpContextProvider.description.renderInlineAs,
};
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const response = await extras.fetch(new URL(this.options.url), {
const parsedUrl = new URL(this.options.url)
const response = await extras.fetch(parsedUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(this.options.headers || {}),
},
body: JSON.stringify({
query: query || "",
fullInput: extras.fullInput,
options: this.options.options,
workspacePath: await this.getWorkspacePath(extras.ide, parsedUrl),
}),
});

View file

@ -9,6 +9,7 @@ interface JiraClientOptions {
password: string;
issueQuery?: string;
apiVersion?: string;
maxResults?: string;
requestOptions?: RequestOptions;
}
@ -73,6 +74,7 @@ export class JiraClient {
"assignee = currentUser() AND resolution = Unresolved order by updated DESC",
apiVersion: "3",
requestOptions: {},
maxResults: "50",
...options,
};
this.baseUrl = `https://${this.options.domain}/rest/api/${this.options.apiVersion}`;
@ -146,7 +148,7 @@ export class JiraClient {
`/search?fields=summary&jql=${
this.options.issueQuery ??
"assignee = currentUser() AND resolution = Unresolved order by updated DESC"
}`,
}&maxResults=${this.options.maxResults ?? "50"}`,
),
{
method: "GET",

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