Merge branch 'main' into apply-request-options-for-completion-models

This commit is contained in:
Nate 2025-04-23 16:17:11 -07:00
commit 1ad852cb1c
647 changed files with 31048 additions and 12199 deletions

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

@ -37,6 +37,52 @@ jobs:
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: |

View file

@ -4,12 +4,10 @@ on:
pull_request:
branches:
- main
- staging
push:
branches:
- main
- staging
jobs:
install-root:
@ -31,6 +29,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
@ -60,7 +114,7 @@ jobs:
npm ci
core-checks:
needs: install-core
needs: [install-core, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -81,6 +135,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
@ -90,7 +155,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
@ -115,6 +180,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: |
@ -147,13 +223,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
@ -178,6 +265,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: |
@ -190,7 +288,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
@ -215,6 +313,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: |
@ -249,14 +358,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
@ -270,6 +391,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: Run core tests
run: |
cd core
@ -285,7 +417,7 @@ jobs:
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:
@ -297,6 +429,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: Get test files
id: vscode-get-test-file-matrix
run: |
@ -320,7 +463,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
@ -340,6 +483,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
@ -353,7 +507,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
@ -373,6 +527,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: |
@ -394,6 +559,7 @@ jobs:
vscode-package-extension,
install-vscode,
install-core,
install-config-yaml,
]
runs-on: ubuntu-latest
# Tests requiring secrets need approval from maintainers
@ -434,6 +600,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
@ -476,7 +653,7 @@ jobs:
path: extensions/vscode/e2e/storage/screenshots
gui-tests:
needs: [install-gui, install-core]
needs: [install-gui, install-core, install-config-yaml]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -496,6 +673,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
@ -508,7 +696,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
@ -517,6 +705,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:
@ -627,11 +826,11 @@ jobs:
- 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:
@ -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
@ -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,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

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" />

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

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

@ -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,10 +248,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
"out/llamaTokenizerWorkerPool.mjs",
);
if (esbuildOnly) {
return;
}
console.log("[info] Building binaries with pkg...");
for (const target of targets) {
const targetDir = `bin/${target}`;

View file

@ -44,13 +44,13 @@
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
"@aws-sdk/credential-providers": "^3.758.0",
"@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.63",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.18",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.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",
@ -135,10 +136,11 @@
"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": {
@ -6404,10 +6406,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",

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

@ -12,11 +12,11 @@
"curly": "off",
"@typescript-eslint/semi": "off",
"eqeqeq": "error",
"complexity": ["error", { "max": 38 }],
"max-lines-per-function": ["error", { "max": 996 }],
"max-statements": ["error", { "max": 112 }],
"complexity": ["error", { "max": 36 }],
"max-lines-per-function": ["error", { "max": 472 }],
"max-statements": ["error", { "max": 108 }],
"max-depth": ["error", { "max": 6 }],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-params": ["error", { "max": 11 }]
"max-params": ["error", { "max": 8 }]
}
}

View file

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

View file

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

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

@ -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,68 +9,57 @@ 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 ?? "",
prompt: customCommand.prompt,
run: async function* ({ input, llm, history, ide, completionOptions }) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${customCommand.name}`)) {
userInput = userInput
.slice(customCommand.name.length + 1, userInput.length)
.trimStart();
}
run: async function* ({
input,
llm,
history,
ide,
completionOptions,
config,
selectedCode,
fetch,
}) {
// Render prompt template
let promptUserInput: string;
let renderedPrompt: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
promptUserInput = await renderTemplatedString(
renderedPrompt = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
{ input },
);
} else {
promptUserInput = customCommand.prompt + "\n\n" + userInput;
const renderedPromptFile = await renderPromptFileV2(
customCommand.prompt,
{
config,
llm,
ide,
selectedCode,
fetch,
fullInput: input,
embeddingsProvider: config.modelsByRole.embed[0],
reranker: config.modelsByRole.rerank[0],
},
);
renderedPrompt = renderedPromptFile[1];
}
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;
}
}
// 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,

View file

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

View file

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

View file

@ -34,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();
const profiles = testConfigHandler.currentOrg.profiles;
expect(profiles?.length).toBe(1);
expect(profiles?.[0].id).toBe("local");
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,384 +1,291 @@
import { ConfigResult, FullSlug } from "@continuedev/config-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 { getAllAssistantFiles } from "./loadLocalAssistants.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
LOCAL_ONBOARDING_PROVIDER_TITLE,
} from "./onboarding.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
import {
OrganizationDescription,
OrgWithProfiles,
ProfileDescription,
ProfileLifecycleManager,
SerializedOrgWithProfiles,
} from "./ProfileLifecycleManager.js";
export type { ProfileDescription };
type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
// Separately manages saving/reloading each profile
export class ConfigHandler {
private readonly globalContext = new GlobalContext();
private additionalContextProviders: IContextProvider[] = [];
private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded
private selectedProfileId: string | null = null;
private localProfileManager: ProfileLifecycleManager;
controlPlaneClient: ControlPlaneClient;
private readonly globalContext = new GlobalContext();
private globalLocalProfileManager: ProfileLifecycleManager;
initializedPromise: Promise<void>;
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 llmLogger: ILLMLogger,
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
private readonly didSelectOrganization?: (orgId: string | null) => void,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.writeLog = writeLog;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
);
// Set local profile as default
const localProfileLoader = new LocalProfileLoader(
ide,
ideSettingsPromise,
this.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,
);
// Profiles are loaded asynchronously
this.initializedPromise = new Promise((resolve, reject) => {
this.init()
.then(() => {
resolve();
})
.catch((e) => {
reject(e);
});
});
// 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();
}
/**
* Users can define as many local assistants as they want in a `.continue/assistants` folder
*/
private async getLocalAssistantProfiles() {
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();
return `${workspaceId}:::${orgId}`;
}
private async cascadeInit() {
this.workspaceDirs = null; // forces workspace dirs reload
const orgs = await this.getOrgs();
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
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();
}
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);
}),
);
}
private async getNonPersonalHubOrg(
org: OrganizationDescription,
): Promise<OrgWithProfiles> {
const profiles = await this.getHubProfiles(org.id);
return this.rectifyProfilesForOrg(org, profiles);
}
private PERSONAL_ORG_DESC: OrganizationDescription = {
iconUrl: "",
id: "personal",
name: "Personal",
slug: undefined,
};
private async getPersonalHubOrg() {
const allLocalProfiles = await this.getAllLocalProfiles();
const hubProfiles = await this.getHubProfiles(null);
const profiles = [...hubProfiles, ...allLocalProfiles];
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
}
private async getLocalOrg() {
const allLocalProfiles = await this.getAllLocalProfiles();
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles);
}
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 getAllLocalProfiles() {
/**
* Users can define as many local assistants as they want in a `.continue/assistants` folder
*/
const assistantFiles = await getAllAssistantFiles(this.ide);
const profiles = assistantFiles.map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
this.llmLogger,
assistant,
);
});
return profiles.map(
const localAssistantProfiles = profiles.map(
(profile) => new ProfileLifecycleManager(profile, this.ide),
);
return [this.globalLocalProfileManager, ...localAssistantProfiles];
}
/**
* 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);
//////////////////
// External actions that can cause a cascading config refresh
// Should not be used internally
//////////////////
async refreshAll() {
await this.cascadeInit();
}
private async init() {
try {
await this.fetchControlPlaneProfiles();
} catch (e) {
// If this fails, make sure at least local profile is loaded
console.error("Failed to fetch control plane profiles in init: ", e);
await this.loadLocalProfilesOnly();
}
try {
const configResult = await this.loadConfig();
this.notifyConfigListeners(configResult);
} catch (e) {
console.error("Failed to load config: ", e);
}
}
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
);
}
get inactiveProfiles() {
return (this.profiles ?? []).filter(
(p) => p.profileDescription.id !== this.selectedProfileId,
);
}
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
const profile = this.profiles?.find(
(p) => p.profileDescription.id === openProfileId,
);
if (profile?.profileDescription.profileType === "local") {
const ideInfo = await this.ide.getIdeInfo();
await this.ide.openFile(profile.profileDescription.uri);
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
}
}
async listOrganizations() {
return await this.controlPlaneClient.listOrganizations();
}
async loadAssistantsForSelectedOrg() {
// Get the profiles and create their lifecycle managers
const userId = await this.controlPlaneClient.userId;
const selectedOrgId = await this.getSelectedOrgId();
let profiles: ProfileLifecycleManager[] | null = null;
if (!userId) {
// Not logged in
const allLocalProfiles = await this.getAllLocalProfiles();
profiles = [...allLocalProfiles];
} else {
// Logged in
const assistants =
await this.controlPlaneClient.listAssistants(selectedOrgId);
const hubProfiles = await Promise.all(
assistants.map(async (assistant) => {
const profileLoader = await PlatformProfileLoader.create(
{
...assistant.configResult,
config: assistant.configResult.config,
},
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
assistant.rawYaml,
selectedOrgId,
);
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
);
if (selectedOrgId === null) {
// Personal
const allLocalProfiles = await this.getAllLocalProfiles();
profiles = [...hubProfiles, ...allLocalProfiles];
} else {
// Organization
profiles = hubProfiles;
}
}
await this.updateAvailableProfiles(profiles);
}
private async getAllLocalProfiles() {
const localAssistantProfiles = await this.getLocalAssistantProfiles();
return [this.localProfileManager, ...localAssistantProfiles];
}
private async loadLocalProfilesOnly() {
const allLocalProfiles = await this.getAllLocalProfiles();
await this.updateAvailableProfiles(allLocalProfiles);
}
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
this.profiles = profiles;
// If the last selected profile is in the list choose that
// Otherwise, choose the first profile
const previouslySelectedProfileId =
await this.getPersistedSelectedProfileId();
// Check if the previously selected profile exists in the current profiles
const profileExists = profiles.some(
(profile) =>
profile.profileDescription.id === previouslySelectedProfileId,
);
const selectedProfileId = profileExists
? previouslySelectedProfileId
: (profiles[0]?.profileDescription.id ?? null);
// Notify listeners
const profileDescriptions = profiles.map(
(profile) => profile.profileDescription,
);
this.notifyProfileListeners(profileDescriptions, selectedProfileId);
await this.setSelectedProfile(selectedProfileId);
}
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
// We use this to keep track of whether we should reload the assistants
private lastFullSlugsList: FullSlug[] = [];
private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean {
if (a.length !== b.length) {
return true;
}
for (let i = 0; i < a.length; i++) {
if (a[i].ownerSlug !== b[i].ownerSlug) {
return true;
}
if (a[i].packageSlug !== b[i].packageSlug) {
return true;
}
if (a[i].versionSlug !== b[i].versionSlug) {
return true;
}
}
return false;
}
private async reloadHubAssistants() {
const selectedOrgId = await this.getSelectedOrgId();
const newFullSlugsList =
await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId);
if (newFullSlugsList) {
const shouldReload = this.fullSlugsListsDiffer(
newFullSlugsList,
this.lastFullSlugsList,
);
if (shouldReload) {
await this.loadAssistantsForSelectedOrg();
}
this.lastFullSlugsList = newFullSlugsList;
}
}
private async fetchControlPlaneProfiles() {
if (await useHub(this.ideSettingsPromise)) {
clearInterval(this.platformProfilesRefreshInterval);
await this.loadAssistantsForSelectedOrg();
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
// If so, we do the full (more expensive) reload
this.platformProfilesRefreshInterval = setInterval(
this.reloadHubAssistants.bind(this),
PlatformProfileLoader.RELOAD_INTERVAL,
);
} else {
try {
const workspaces = await this.controlPlaneClient.listWorkspaces();
const profiles = await this.getAllLocalProfiles();
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
});
await this.updateAvailableProfiles(profiles);
} catch (e: any) {
console.error("Failed to load profiles: ", e);
await this.loadLocalProfilesOnly();
}
}
}
async getPersistedSelectedProfileId(): Promise<string | null> {
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
return lastSelectedIds[workspaceId] ?? null;
}
async getSelectedOrgId(): Promise<string | null> {
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const workspaceId = await this.getWorkspaceId();
return selectedOrgs[workspaceId] ?? null;
}
async setSelectedOrgId(orgId: string | null) {
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
selectedOrgs[await this.getWorkspaceId()] = orgId;
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
this.didSelectOrganization?.(orgId);
}
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,
);
}
// 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("&");
}
// Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed
updateIdeSettings(ideSettings: IdeSettings) {
// 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,
) {
@ -386,38 +293,97 @@ export class ConfigHandler {
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
);
await this.cascadeInit();
}
this.fetchControlPlaneProfiles().catch(async (e) => {
console.error("Failed to fetch control plane profiles: ", e);
await this.loadLocalProfilesOnly();
await this.reloadConfig();
// 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[],
selectedProfileId: string | null,
) => void)[] = [];
onDidChangeAvailableProfiles(
listener: (
profiles: ProfileDescription[],
selectedProfileId: string | null,
) => void,
) {
this.profilesListeners.push(listener);
}
this.currentOrg = org;
private notifyProfileListeners(
profiles: ProfileDescription[],
selectedProfileId: string | null,
) {
for (const listener of this.profilesListeners) {
listener(profiles, selectedProfileId);
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);
}
@ -429,27 +395,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>
> {
@ -465,10 +413,6 @@ export class ConfigHandler {
);
}
listProfiles(): ProfileDescription[] | null {
return this.profiles?.map((p) => p.profileDescription) ?? null;
}
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (!this.currentProfile) {
return {
@ -482,28 +426,36 @@ export class ConfigHandler {
);
}
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");
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}`);
}
return model;
}
// 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

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

View file

@ -1,93 +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,
data: [],
context: defaultContextProvidersVsCode,
};
export const defaultConfigJetBrains: SerializedContinueConfig = {
export const defaultConfigJetBrains: ConfigYaml = {
name: "Local Assistant",
version: "1.0.0",
schema: "v1",
models: [],
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
data: [],
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

@ -8,7 +8,6 @@ import {
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as JSONC from "comment-json";
import * as tar from "tar";
@ -19,7 +18,6 @@ import {
ContinueConfig,
ContinueRcJson,
CustomContextProvider,
CustomLLM,
EmbeddingsProviderDescription,
IContextProvider,
IDE,
@ -27,6 +25,7 @@ import {
IdeSettings,
IdeType,
ILLM,
ILLMLogger,
LLMOptions,
ModelDescription,
RerankerDescription,
@ -37,17 +36,15 @@ import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index";
import { AllRerankers } from "../context/allRerankers";
import { MCPManagerSingleton } from "../context/mcp";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import { useHub } from "../control-plane/env";
import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
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";
@ -70,15 +67,12 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
defaultSlashCommandsJetBrains,
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util";
import {
getModelByRole,
isSupportedLanceDbCpuTargetForLinux,
serializePromptTemplates,
} from "./util";
import { validateConfig } from "./validation.js";
export function resolveSerializedConfig(
@ -122,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}`);
}
@ -162,16 +156,6 @@ 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];
if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) {
config.disableIndexing = true;
}
@ -219,14 +203,12 @@ async function serializedToIntermediateConfig(
return config;
}
function isModelDescription(
llm: ModelDescription | CustomLLM,
): llm is ModelDescription {
return (llm as ModelDescription).title !== undefined;
}
// Merge request options set for entire config with model specific options
function applyRequestOptionsToModels(models: BaseLLM[], config : Config, roles : ModelRole[] | undefined = undefined) {
function applyRequestOptionsToModels(
models: BaseLLM[],
config: Config,
roles: ModelRole[] | undefined = undefined,
) {
// Prepare models
for (const model of models) {
model.requestOptions = {
@ -234,7 +216,7 @@ function applyRequestOptionsToModels(models: BaseLLM[], config : Config, roles :
...config.requestOptions,
};
if (roles !== undefined) {
model.roles = model.roles ?? roles;
model.roles = model.roles ?? roles;
}
}
}
@ -246,93 +228,113 @@ export function isContextProviderWithParams(
}
/** Only difference between intermediate and final configs is the `models` array */
async function intermediateToFinalConfig(
config: Config,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
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: 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);
}
}
}
}
applyRequestOptionsToModels(models, config, ["chat", "apply", "edit", "summarize"]) // Default to chat role if not specified
}),
);
applyRequestOptionsToModels(models, config, [
"chat",
"apply",
"edit",
"summarize",
]); // Default to chat role if not specified
if (allowFreeTrial) {
// Obtain auth token (iff free trial being used)
@ -359,15 +361,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") {
@ -386,6 +387,7 @@ async function intermediateToFinalConfig(
)
).filter((x) => x !== undefined) as BaseLLM[];
}
applyRequestOptionsToModels(tabAutocompleteModels, config);
// These context providers are always included, regardless of what, if anything,
@ -443,38 +445,32 @@ async function intermediateToFinalConfig(
function getEmbeddingsILLM(
embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
): ILLM | null {
if (!embedConfig) {
return null;
}
if ("providerName" in embedConfig) {
return embedConfig;
}
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
return new embeddingsProviderClass();
} else {
const llmOptions: LLMOptions = {
model: options.model ?? "UNSPECIFIED",
...options,
};
return new embeddingsProviderClass(
llmOptions,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...config.requestOptions,
...options.requestOptions,
}),
);
if (embedConfig) {
// config.ts-injected ILLM
if ("providerName" in embedConfig) {
return embedConfig;
}
} else {
errors.push({
fatal: false,
message: `Embeddings provider ${provider} not found. Using default`,
});
const { provider, ...options } = embedConfig;
if (provider === "transformers.js") {
return new TransformersJsEmbeddingsProvider();
} else {
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;
}
@ -487,11 +483,11 @@ async function intermediateToFinalConfig(
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);
@ -504,16 +500,20 @@ async function intermediateToFinalConfig(
} else {
return new LLMReranker(llm);
}
} else if (rerankerClass) {
const llmOptions: LLMOptions = {
model: "rerank-2",
...params,
};
return new rerankerClass(llmOptions, (url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...params?.requestOptions,
}),
);
} else {
const cls = LLMClasses.find((c) => c.providerName === name);
if (cls) {
const llmOptions: LLMOptions = {
model: params?.model,
...params,
};
return new cls(llmOptions);
} else {
errors.push({
fatal: false,
message: `Unknown reranking provider ${name}`,
});
}
}
return null;
}
@ -522,8 +522,7 @@ async function intermediateToFinalConfig(
const continueConfig: ContinueConfig = {
...config,
contextProviders,
models,
tools: allTools,
tools: [...allTools],
mcpServerStatuses: [],
slashCommands: config.slashCommands ?? [],
modelsByRole: {
@ -544,15 +543,23 @@ async function intermediateToFinalConfig(
rerank: newReranker ?? null,
summarize: null, // Not implemented
},
rules: [],
};
if (config.systemMessage) {
continueConfig.rules.unshift({
rule: config.systemMessage,
source: "json-systemMessage",
});
}
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server ${index + 1}`,
name: `MCP Server`,
...server,
}),
),
@ -562,7 +569,7 @@ async function intermediateToFinalConfig(
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
if (inlineEditModel) {
const match = continueConfig.models.find(
const match = continueConfig.modelsByRole.chat.find(
(m) => m.title === inlineEditModel,
);
if (match) {
@ -581,7 +588,7 @@ async function intermediateToFinalConfig(
"applyCodeBlock",
)?.title;
if (applyBlockModel) {
const match = continueConfig.models.find(
const match = continueConfig.modelsByRole.chat.find(
(m) => m.title === applyBlockModel,
);
if (match) {
@ -620,11 +627,12 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
contextLength: llm.contextLength,
template: llm.template,
completionOptions: llm.completionOptions,
systemMessage: llm.systemMessage,
baseChatSystemMessage: llm.baseChatSystemMessage,
requestOptions: llm.requestOptions,
promptTemplates: llm.promptTemplates as any,
promptTemplates: serializePromptTemplates(llm.promptTemplates),
capabilities: llm.capabilities,
roles: llm.roles,
configurationStatus: llm.getConfigurationStatus(),
};
}
@ -634,8 +642,6 @@ async function finalToBrowserConfig(
): Promise<BrowserSerializedContinueConfig> {
return {
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
models: final.models.map(llmToSerializedModelDescription),
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map(
({ run, ...slashCommandDescription }) => slashCommandDescription,
@ -854,7 +860,7 @@ async function loadContinueConfigFromJson(
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
llmLogger: ILLMLogger,
workOsAccessToken: string | undefined,
overrideConfigJson: SerializedContinueConfig | undefined,
): Promise<ConfigResult<ContinueConfig>> {
@ -875,11 +881,6 @@ async function loadContinueConfigFromJson(
return { errors, config: undefined, configLoadInterrupted: true };
}
const systemPromptDotFile = await getSystemPromptDotFile(ide);
if (systemPromptDotFile) {
serialized.systemMessage = systemPromptDotFile;
}
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
@ -948,15 +949,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

@ -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,79 +0,0 @@
import { ConfigJson } from "@continuedev/config-types";
import { ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { PRODUCTION_ENV } from "../../control-plane/env.js";
import {
ContinueConfig,
IDE,
IdeSettings,
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,
uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`,
};
setInterval(async () => {
this.workspaceSettings =
await this.controlPlaneClient.getSettingsForWorkspace(
this.description.id,
);
this.onReload();
}, ControlPlaneProfileLoader.RELOAD_INTERVAL);
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const settings =
this.workspaceSettings ??
((await this.controlPlaneClient.getSettingsForWorkspace(
this.description.id,
)) as any);
const serializedConfig: SerializedContinueConfig = settings;
return await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
serializedConfig,
undefined,
undefined,
this.workspaceId,
undefined,
null,
);
}
setIsActive(isActive: boolean): void {}
}

View file

@ -1,7 +1,7 @@
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";
@ -17,7 +17,7 @@ export default class LocalProfileLoader implements IProfileLoader {
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,
@ -55,18 +55,18 @@ export default class LocalProfileLoader implements IProfileLoader {
description: ProfileDescription;
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const result = await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
undefined,
undefined,
undefined,
this.description.id,
this.overrideAssistantFile?.path,
null,
);
const result = await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigJson: undefined,
overrideConfigYaml: undefined,
platformConfigMetadata: undefined,
profileId: this.description.id,
overrideConfigYamlByPath: this.overrideAssistantFile?.path,
orgScopeId: null,
});
this.description.errors = result.errors;

View file

@ -2,7 +2,7 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
@ -21,33 +21,81 @@ export interface PlatformConfigMetadata {
export default class PlatformProfileLoader implements IProfileLoader {
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
private constructor(
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 writeLog: (message: string) => Promise<void>,
readonly description: ProfileDescription,
private readonly orgScopeId: string | null,
) {}
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;
static async create(
configResult: ConfigResult<AssistantUnrolled>,
ownerSlug: string,
packageSlug: string,
iconUrl: string,
versionSlug: string,
controlPlaneClient: ControlPlaneClient,
ide: IDE,
ideSettingsPromise: Promise<IdeSettings>,
writeLog: (message: string) => Promise<void>,
rawYaml: string,
orgScopeId: string | null,
): Promise<PlatformProfileLoader> {
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 = {
@ -65,7 +113,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
rawYaml,
};
return new PlatformProfileLoader(
return new PlatformProfileLoader({
configResult,
ownerSlug,
packageSlug,
@ -74,10 +122,10 @@ export default class PlatformProfileLoader implements IProfileLoader {
controlPlaneClient,
ide,
ideSettingsPromise,
writeLog,
llmLogger,
description,
orgScopeId,
);
});
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
@ -89,21 +137,21 @@ export default class PlatformProfileLoader implements IProfileLoader {
};
}
const results = await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
undefined,
this.configResult.config,
{
const results = await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigJson: undefined,
overrideConfigYaml: this.configResult.config,
platformConfigMetadata: {
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
},
this.description.id,
undefined,
this.orgScopeId,
);
profileId: this.description.id,
overrideConfigYamlByPath: undefined,
orgScopeId: this.orgScopeId,
});
return {
config: results.config,

View file

@ -12,11 +12,12 @@ import {
ContinueRcJson,
IDE,
IdeSettings,
ILLMLogger,
SerializedContinueConfig,
Tool,
} from "../../";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { MCPManagerSingleton } from "../../context/mcp";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
@ -33,20 +34,32 @@ import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
export default async function doLoadConfig(
ide: IDE,
ideSettingsPromise: Promise<IdeSettings>,
controlPlaneClient: ControlPlaneClient,
writeLog: (message: string) => Promise<void>,
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
profileId: string,
overrideConfigYamlByPath: string | undefined,
orgScopeId: string | null,
): Promise<ConfigResult<ContinueConfig>> {
export default async function doLoadConfig({
ide,
ideSettingsPromise,
controlPlaneClient,
llmLogger,
overrideConfigJson,
overrideConfigYaml,
platformConfigMetadata,
profileId,
overrideConfigYamlByPath,
orgScopeId,
}: {
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
controlPlaneClient: ControlPlaneClient;
llmLogger: ILLMLogger;
overrideConfigJson: SerializedContinueConfig | undefined;
overrideConfigYaml: AssistantUnrolled | undefined;
platformConfigMetadata: PlatformConfigMetadata | undefined;
profileId: string;
overrideConfigYamlByPath: string | undefined;
orgScopeId: string | null;
}): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
const uniqueId = await ide.getUniqueId();
@ -55,7 +68,7 @@ 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);
}
@ -69,19 +82,18 @@ export default async function doLoadConfig(
let configLoadInterrupted = false;
if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
const result = await loadContinueConfigFromYaml(
const result = await loadContinueConfigFromYaml({
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
llmLogger,
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
configYamlPath,
orgScopeId,
);
});
newConfig = result.config;
errors = result.errors;
configLoadInterrupted = result.configLoadInterrupted;
@ -92,7 +104,7 @@ export default async function doLoadConfig(
ideSettings,
ideInfo,
uniqueId,
writeLog,
llmLogger,
workOsAccessToken,
overrideConfigJson,
);
@ -109,6 +121,12 @@ export default async function doLoadConfig(
// Remove ability have undefined errors, just have an array
errors = [...(errors ?? [])];
// Add rules from .continuerules files
const { rules, errors: continueRulesErrors } =
await getWorkspaceContinueRuleDotFiles(ide);
newConfig.rules.unshift(...rules);
errors.push(...continueRulesErrors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
@ -135,7 +153,6 @@ export default async function doLoadConfig(
faviconUrl: server.faviconUrl,
readonly: false,
type: "function" as const,
wouldLikeTo: "",
uri: encodeMCPToolUri(server.id, tool.name),
group: server.name,
}));
@ -161,6 +178,7 @@ export default async function doLoadConfig(
const serverContextProvider = new MCPContextProvider({
submenuItems,
mcpId: server.id,
serverName: server.name,
});
newConfig.contextProviders.push(serverContextProvider);
}
@ -257,7 +275,7 @@ async function injectControlPlaneProxyInfo(
}
});
config.models.forEach((model) => {
config.modelsByRole.chat.forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}

View file

@ -1,6 +1,7 @@
import { ModelRole } from "@continuedev/config-yaml";
import { ContinueConfig, ILLM } from "..";
import { LLMConfigurationStatuses } from "../llm/constants";
import {
GlobalContext,
GlobalContextModelSelections,
@ -19,19 +20,20 @@ export function rectifySelectedModelsFromGlobalContext(
let fellBack = false;
// chat and summarize not implemented yet
// default chat model is stored in GUI still
// 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,
@ -40,12 +42,23 @@ export function rectifySelectedModelsFromGlobalContext(
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;
}

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;
@ -433,6 +433,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 +534,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 +658,6 @@ declare global {
remoteConfigServerUrl: string | undefined;
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
pauseCodebaseIndexOnStart: boolean;
}
@ -870,7 +957,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 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,
);
@ -183,3 +189,22 @@ async function showUnsupportedCpuToast(ide: IDE) {
);
}
}
/**
* 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

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

@ -2,6 +2,9 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { SerializedContinueConfig } from "../..";
/*
TODO this is not functional
*/
export function convertConfigJsonToConfigYaml(
configJson: SerializedContinueConfig,
): AssistantUnrolled {

View file

@ -5,31 +5,34 @@ import {
ConfigResult,
ConfigValidationError,
FQSN,
isAssistantUnrolledNonNullable,
MCPServer,
ModelRole,
PlatformClient,
RegistryClient,
Rule,
SecretResult,
unrollAssistantFromContent,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import {
ContinueConfig,
ExperimentalMCPOptions,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
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 { 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";
@ -37,7 +40,6 @@ import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { allTools } from "../../tools";
import { GlobalContext } from "../../util/GlobalContext";
import { getConfigYamlPath } from "../../util/paths";
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
@ -60,6 +62,35 @@ export class LocalPlatformClient implements PlatformClient {
}
}
function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
if (typeof rule === "string") {
return {
rule: rule,
source: "rules-block",
};
} else {
return {
source: "rules-block",
rule: rule.rule,
if: rule.if,
name: rule.name,
};
}
}
function convertYamlMcpToContinueMcp(
server: MCPServer,
): ExperimentalMCPOptions {
return {
transport: {
type: "stdio",
command: server.command,
args: server.args ?? [],
env: server.env,
},
};
}
async function loadConfigYaml(
rawYaml: string,
overrideConfigYaml: AssistantUnrolled | undefined,
@ -81,7 +112,6 @@ async function loadConfigYaml(
await controlPlaneClient.getAccessToken(),
getControlPlaneEnvSync(
ideSettings.continueTestEnvironment,
ideSettings.enableControlServerBeta,
).CONTROL_PLANE_URL,
),
{
@ -92,7 +122,15 @@ async function loadConfigYaml(
renderSecrets: true,
},
));
const errors = validateConfigYaml(config);
const errors = isAssistantUnrolledNonNullable(config)
? validateConfigYaml(config)
: [
{
fatal: true,
message: "Assistant includes blocks that don't exist",
},
];
if (errors?.some((error) => error.fatal)) {
return {
@ -110,41 +148,31 @@ async function loadConfigYaml(
};
}
async function configYamlToContinueConfig(
config: AssistantUnrolled,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
allowFreeTrial: boolean = true,
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
async function configYamlToContinueConfig({
config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
platformConfigMetadata,
allowFreeTrial = true,
}: {
config: AssistantUnrolled;
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
allowFreeTrial: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const localErrors: ConfigValidationError[] = [];
const continueConfig: ContinueConfig = {
slashCommands: [],
models: [],
tools: [...allTools],
mcpServerStatuses: [],
systemMessage: config.rules?.join("\n"),
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,
})),
rules: config.rules,
contextProviders: [],
modelsByRole: {
chat: [],
@ -156,7 +184,7 @@ async function configYamlToContinueConfig(
summarize: [],
},
selectedModelByRole: {
chat: null, // not currently used - defaultModel on GUI is used
chat: null,
edit: null, // not currently used
apply: null,
embed: null,
@ -164,14 +192,44 @@ async function configYamlToContinueConfig(
rerank: null,
summarize: null,
},
data: config.data,
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);
for (const file of promptFiles) {
promptFiles.forEach((file) => {
try {
const slashCommand = slashCommandFromPromptFileV1(
file.path,
@ -186,7 +244,7 @@ async function configYamlToContinueConfig(
message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
});
}
}
});
} catch (e) {
localErrors.push({
fatal: false,
@ -207,23 +265,19 @@ async function configYamlToContinueConfig(
});
// Models
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
try {
const llms = await llmsFromModelConfig(
const llms = await llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
continueConfig.systemMessage,
);
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
continueConfig.models.push(...llms);
}
config: continueConfig,
});
if (model.roles?.includes("chat")) {
continueConfig.modelsByRole.chat.push(...llms);
@ -246,59 +300,25 @@ async function configYamlToContinueConfig(
}
if (model.roles?.includes("embed")) {
const { provider, ...options } = model;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
const { provider } = model;
if (provider === "transformers.js") {
if (ideInfo.ideType === "vscode") {
continueConfig.modelsByRole.embed.push(
new embeddingsProviderClass(),
new TransformersJsEmbeddingsProvider(),
);
} else {
continueConfig.modelsByRole.embed.push(
new embeddingsProviderClass(
{
...options,
title: options.name,
},
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
),
);
localErrors.push({
fatal: false,
message: `Transformers.js embeddings provider not supported in this IDE.`,
});
}
} else {
localErrors.push({
fatal: false,
message: `Unsupported embeddings model provider found: ${provider}`,
});
continueConfig.modelsByRole.embed.push(...llms);
}
}
if (model.roles?.includes("rerank")) {
const { provider, ...options } = model;
const rerankerClass = AllRerankers[provider];
if (rerankerClass) {
continueConfig.modelsByRole.rerank.push(
new rerankerClass(
{
...options,
title: options.name,
},
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
),
);
} else {
localErrors.push({
fatal: false,
message: `Unsupported reranking model provider found: ${provider}`,
});
}
continueConfig.modelsByRole.rerank.push(...llms);
}
} catch (e) {
localErrors.push({
@ -322,7 +342,7 @@ async function configYamlToContinueConfig(
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) {
@ -337,14 +357,15 @@ async function configYamlToContinueConfig(
message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`,
});
// Remove free trial models
continueConfig.models = continueConfig.models.filter(
(model) => model.providerName !== "free-trial",
);
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",
);
}
@ -374,7 +395,10 @@ async function configYamlToContinueConfig(
}
return undefined;
}
const instance: IContextProvider = new cls(context.params ?? {});
const instance: IContextProvider = new cls({
name: context.name,
...context.params,
});
return instance;
})
.filter((p) => !!p) ?? []) as IContextProvider[];
@ -407,19 +431,29 @@ async function configYamlToContinueConfig(
return { config: continueConfig, errors: localErrors };
}
export async function loadContinueConfigFromYaml(
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
controlPlaneClient: ControlPlaneClient,
configYamlPath: string | undefined,
orgScopeId: string | null,
): Promise<ConfigResult<ContinueConfig>> {
export async function loadContinueConfigFromYaml({
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
configYamlPath,
orgScopeId,
}: {
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
overrideConfigYaml: AssistantUnrolled | undefined;
platformConfigMetadata: PlatformConfigMetadata | undefined;
controlPlaneClient: ControlPlaneClient;
configYamlPath: string | undefined;
orgScopeId: string | null;
}): Promise<ConfigResult<ContinueConfig>> {
const rawYaml =
overrideConfigYaml === undefined
? fs.readFileSync(
@ -445,32 +479,16 @@ export async function loadContinueConfigFromYaml(
}
const { config: continueConfig, errors: localErrors } =
await configYamlToContinueConfig(
configYamlResult.config,
await configYamlToContinueConfig({
config: configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
llmLogger,
platformConfigMetadata,
);
try {
const systemPromptDotFile = await getSystemPromptDotFile(ide);
if (systemPromptDotFile) {
if (continueConfig.systemMessage) {
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
} else {
continueConfig.systemMessage = systemPromptDotFile;
}
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`,
allowFreeTrial: true,
});
}
// Apply shared config
// TODO: override several of these values with user/org shared config

View file

@ -1,6 +1,12 @@
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";
@ -13,22 +19,29 @@ 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,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM | undefined> {
const cls = getModelClass(model);
if (!cls) {
@ -39,7 +52,7 @@ async function modelConfigToBaseLLM(
let options: LLMOptions = {
...rest,
// contextLength: model.defaultCompletionOptions?.contextLength ?? undefined,
contextLength: model.defaultCompletionOptions?.contextLength,
completionOptions: {
...(model.defaultCompletionOptions ?? {}),
model: model.model,
@ -47,11 +60,11 @@ async function modelConfigToBaseLLM(
model.defaultCompletionOptions?.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens,
},
writeLog,
logger: llmLogger,
uniqueId,
title: model.name,
systemMessage,
promptTemplates: model.promptTemplates,
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
capabilities: {
tools: model.capabilities?.includes("tool_use"),
uploadImage: model.capabilities?.includes("image_input"),
@ -127,16 +140,25 @@ async function modelConfigToBaseLLM(
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,
platformConfigMetadata,
config,
}: {
llm: BaseLLM;
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
try {
const modelNames = await llm.listModels();
const detectedModels = await Promise.all(
@ -146,18 +168,18 @@ async function autodetectModels(
return undefined;
}
return await modelConfigToBaseLLM(
{
return await modelConfigToBaseLLM({
model: {
...model,
model: modelName,
name: modelName,
},
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
systemMessage,
);
config,
});
}),
);
return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[];
@ -167,38 +189,46 @@ 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,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
systemMessage,
);
config,
});
if (!baseLlm) {
return [];
}
if (model.model === AUTODETECT) {
const models = await autodetectModels(
baseLlm,
const models = await autodetectModels({
llm: baseLlm,
model,
ide,
uniqueId,
ideSettings,
writeLog,
llmLogger,
platformConfigMetadata,
systemMessage,
);
config,
});
return models;
} else {
return [baseLlm];

View file

@ -1,19 +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";
import WatsonX from "../llm/llms/WatsonX";
export const AllRerankers: { [key: string]: any } = {
cohere: Cohere,
bedrock: Bedrock,
llm: LLMReranker,
voyage: Voyage,
watsonx: WatsonX,
"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

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

View file

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

View file

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

View file

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

View file

@ -9,7 +9,6 @@ import {
LoadSubmenuItemsArgs,
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
@ -64,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());
});
}
@ -165,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,
@ -179,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

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

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

View file

@ -6,10 +6,11 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { MCPManagerSingleton } from "../mcp";
import { MCPManagerSingleton } from "../mcp/MCPManagerSingleton";
interface MCPContextProviderOptions {
mcpId: string;
serverName: string;
submenuItems: ContextSubmenuItem[];
}
@ -20,6 +21,16 @@ class MCPContextProvider extends BaseContextProvider {
description: "Model Context Protocol",
type: "submenu",
};
override get description(): ContextProviderDescription {
return {
title: `${MCPContextProvider.description.title}-${this.options["mcpId"]}`,
displayTitle: this.options["serverName"]
? `${this.options["serverName"]} resources`
: "MCP",
description: "Model Context Protocol",
type: "submenu",
};
}
static encodeMCPResourceId(mcpId: string, uri: string): string {
return JSON.stringify({ mcpId, uri });

View file

@ -54,7 +54,7 @@ class RepoMapContextProvider extends BaseContextProvider {
const folders = await walkDirs(
args.ide,
{
onlyDirs: true,
include: "dirs",
source: "load submenu items - repo map",
},
workspaceDirs,

View file

@ -3,6 +3,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { formatGrepSearchResults } from "../../util/grepSearch.js";
import { BaseContextProvider } from "../index.js";
class SearchContextProvider extends BaseContextProvider {
@ -19,10 +20,11 @@ class SearchContextProvider extends BaseContextProvider {
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const results = await extras.ide.getSearchResults(query);
const formatted = formatGrepSearchResults(results);
return [
{
description: "Search results",
content: `Results of searching codebase for "${query}":\n\n${results}`,
content: `Results of searching codebase for "${query}":\n\n${formatted}`,
name: "Search results",
},
];

View file

@ -7,6 +7,7 @@ import {
IContextProvider,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { LLMLogger } from "../../llm/logger";
import { TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
@ -26,13 +27,13 @@ async function getContextProviderExtras(
): Promise<ContextProviderExtras> {
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const llmLogger = new LLMLogger();
const configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
async (text) => {},
llmLogger,
Promise.resolve(undefined),
);
await configHandler.initializedPromise;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not found");
@ -44,7 +45,7 @@ async function getContextProviderExtras(
config,
embeddingsProvider: config.selectedModelByRole.embed,
fetch: fetch,
llm: config.models[0],
llm: config.modelsByRole.chat[0],
reranker: config.selectedModelByRole.rerank,
selectedCode: [],
};

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -16,7 +16,6 @@ export async function* streamLazyApply(
filename: string,
newCode: string,
llm: ILLM,
fastLlm: ILLM,
): AsyncGenerator<DiffLine> {
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
if (!promptFactory) {
@ -39,7 +38,7 @@ export async function* streamLazyApply(
oldCode,
linesBefore,
linesAfter,
fastLlm,
llm,
)) {
yield line;
}

View file

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

235
core/index.d.ts vendored
View file

@ -1,6 +1,8 @@
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
import { DataDestination, ModelRole, PromptTemplates } from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { LLMConfigurationStatuses } from "./llm/constants";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
interface Window {
ide?: "vscode";
@ -75,39 +77,19 @@ export type PromptTemplateFunction = (
export type PromptTemplate = string | PromptTemplateFunction;
export interface ILLM extends LLMOptions {
type RequiredLLMOptions =
| "uniqueId"
| "contextLength"
| "embeddingId"
| "maxEmbeddingChunkSize"
| "maxEmbeddingBatchSize"
| "completionOptions";
export interface ILLM
extends Omit<LLMOptions, RequiredLLMOptions>,
Required<Pick<LLMOptions, RequiredLLMOptions>> {
get providerName(): string;
uniqueId: string;
model: string;
title?: string;
systemMessage?: string;
contextLength: number;
maxStopWords?: number;
completionOptions: CompletionOptions;
requestOptions?: RequestOptions;
promptTemplates?: Record<string, PromptTemplate>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
deployment?: string;
apiVersion?: string;
apiType?: string;
region?: string;
projectId?: string;
// Embedding options
embeddingId: string;
maxEmbeddingChunkSize: number;
maxEmbeddingBatchSize: number;
complete(
prompt: string,
signal: AbortSignal,
@ -161,6 +143,8 @@ export interface ILLM extends LLMOptions {
otherData: Record<string, string>,
canPutWordsInModelsMouth?: boolean,
): string | ChatMessage[];
getConfigurationStatus(): LLMConfigurationStatuses;
}
export interface ModelInstaller {
@ -236,7 +220,6 @@ export interface SiteIndexingConfig {
maxDepth?: number;
faviconUrl?: string;
useLocalCrawling?: boolean;
rootUrl?: string; // Currently only used by preindexed docs
}
export interface DocsIndexingDetails {
@ -244,7 +227,6 @@ export interface DocsIndexingDetails {
config: SiteIndexingConfig;
indexingStatus: IndexingStatus | undefined;
chunks: Chunk[];
isPreIndexedDoc: boolean;
}
export interface IContextProvider {
@ -413,6 +395,7 @@ export interface ContextItem {
icon?: string;
uri?: ContextItemUri;
hidden?: boolean;
status?: string;
}
export interface ContextItemWithId extends ContextItem {
@ -484,20 +467,108 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions {
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;
title?: string;
uniqueId?: string;
systemMessage?: string;
baseChatSystemMessage?: string;
contextLength?: number;
maxStopWords?: number;
completionOptions?: CompletionOptions;
requestOptions?: RequestOptions;
template?: TemplateType;
promptTemplates?: Record<string, PromptTemplate>;
promptTemplates?: Partial<Record<keyof PromptTemplates, PromptTemplate>>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
logger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
@ -629,7 +700,6 @@ export interface IdeSettings {
remoteConfigServerUrl: string | undefined;
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
continueTestEnvironment: "none" | "production" | "staging" | "local";
pauseCodebaseIndexOnStart: boolean;
}
@ -711,6 +781,8 @@ export interface IDE {
getSearchResults(query: string): Promise<string>;
getFileResults(pattern: string): Promise<string[]>;
subprocess(command: string, cwd?: string): Promise<[string, string]>;
getProblems(fileUri?: string | undefined): Promise<Problem[]>;
@ -893,6 +965,11 @@ export interface ToolExtras {
llm: ILLM;
fetch: FetchFunction;
tool: Tool;
toolCallId?: string;
onPartialOutput?: (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => void;
}
export interface Tool {
@ -905,8 +982,11 @@ export interface Tool {
};
displayTitle: string;
wouldLikeTo: string;
wouldLikeTo?: string;
isCurrently?: string;
hasAlready?: string;
readonly: boolean;
isInstant?: boolean;
uri?: string;
faviconUrl?: string;
group: string;
@ -952,9 +1032,8 @@ export interface ModelDescription {
model: string;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
apiBase?: string;
apiKeyLocation?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
@ -963,15 +1042,16 @@ export interface ModelDescription {
maxStopWords?: number;
template?: TemplateType;
completionOptions?: BaseCompletionOptions;
systemMessage?: string;
baseChatSystemMessage?: string;
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
configurationStatus?: LLMConfigurationStatuses;
}
export interface EmbedOptions {
export interface JSONEmbedOptions {
apiBase?: string;
apiKey?: string;
model?: string;
@ -992,7 +1072,7 @@ export interface EmbedOptions {
projectId?: string;
}
export interface EmbeddingsProviderDescription extends EmbedOptions {
export interface EmbeddingsProviderDescription extends JSONEmbedOptions {
provider: string;
}
@ -1141,6 +1221,7 @@ export interface ApplyState {
numDiffs?: number;
filepath?: string;
fileContent?: string;
toolCallId?: string;
}
export interface RangeInFileWithContents {
@ -1215,11 +1296,39 @@ export interface AnalyticsConfig {
clientKey?: string;
}
export interface JSONModelDescription {
title: string;
provider: string;
model: string;
apiKey?: string;
apiBase?: string;
contextLength?: number;
maxStopWords?: number;
template?: TemplateType;
completionOptions?: BaseCompletionOptions;
systemMessage?: string;
requestOptions?: RequestOptions;
cacheBehavior?: CacheBehavior;
region?: string;
profile?: string;
modelArn?: string;
apiType?: "openai" | "azure";
apiVersion?: string;
deployment?: string;
projectId?: string;
accountId?: string;
aiGatewaySlug?: string;
useLegacyCompletionsEndpoint?: boolean;
deploymentId?: string;
}
// config.json
export interface SerializedContinueConfig {
env?: string[];
allowAnonymousTelemetry?: boolean;
models: ModelDescription[];
models: JSONModelDescription[];
systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
@ -1230,7 +1339,7 @@ export interface SerializedContinueConfig {
disableSessionTitles?: boolean;
userToken?: string;
embeddingsProvider?: EmbeddingsProviderDescription;
tabAutocompleteModel?: ModelDescription | ModelDescription[];
tabAutocompleteModel?: JSONModelDescription | JSONModelDescription[];
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
ui?: ContinueUIConfig;
reranker?: RerankerDescription;
@ -1250,11 +1359,11 @@ export type ContinueRcJson = Partial<SerializedContinueConfig> & {
export interface Config {
/** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://docs.continue.dev/telemetry */
allowAnonymousTelemetry?: boolean;
/** Each entry in this array will originally be a ModelDescription, the same object from your config.json, but you may add CustomLLMs.
/** Each entry in this array will originally be a JSONModelDescription, the same object from your config.json, but you may add CustomLLMs.
* A CustomLLM requires you only to define an AsyncGenerator that calls the LLM and yields string updates. You can choose to define either `streamCompletion` or `streamChat` (or both).
* Continue will do the rest of the work to construct prompt templates, handle context items, prune context, etc.
*/
models: (CustomLLM | ModelDescription)[];
models: (CustomLLM | JSONModelDescription)[];
/** A system message to be followed by all of your models */
systemMessage?: string;
/** The default completion options for all models */
@ -1278,8 +1387,8 @@ export interface Config {
/** The model that Continue will use for tab autocompletions. */
tabAutocompleteModel?:
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
| JSONModelDescription
| (CustomLLM | JSONModelDescription)[];
/** Options for tab autocomplete */
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
/** UI styles customization */
@ -1296,8 +1405,7 @@ export interface Config {
// in the actual Continue source code
export interface ContinueConfig {
allowAnonymousTelemetry?: boolean;
models: ILLM[];
systemMessage?: string;
// systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands: SlashCommand[];
@ -1312,7 +1420,7 @@ export interface ContinueConfig {
docs?: SiteIndexingConfig[];
tools: Tool[];
mcpServerStatuses: MCPServerStatus[];
rules?: string[];
rules: RuleWithSource[];
modelsByRole: Record<ModelRole, ILLM[]>;
selectedModelByRole: Record<ModelRole, ILLM | null>;
data?: DataDestination[];
@ -1320,8 +1428,7 @@ export interface ContinueConfig {
export interface BrowserSerializedContinueConfig {
allowAnonymousTelemetry?: boolean;
models: ModelDescription[];
systemMessage?: string;
// systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands: SlashCommandDescription[];
@ -1335,7 +1442,7 @@ export interface BrowserSerializedContinueConfig {
docs?: SiteIndexingConfig[];
tools: Tool[];
mcpServerStatuses: MCPServerStatus[];
rules?: string[];
rules: RuleWithSource[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
modelsByRole: Record<ModelRole, ModelDescription[]>;
@ -1382,4 +1489,20 @@ export type PackageDocsResult = {
export interface TerminalOptions {
reuseTerminal?: boolean;
terminalName?: string;
waitForCompletion?: boolean;
}
export interface RuleWithSource {
name?: string;
slug?: string;
source:
| "default"
| "model-chat-options"
| "rules-block"
| "json-systemMessage"
| ".continuerules";
if?: string;
rule: string;
description?: string;
ruleFile?: string;
}

View file

@ -1,53 +0,0 @@
import { ILLM } from "../index.js";
import Bedrock from "../llm/llms/Bedrock.js";
import Cohere from "../llm/llms/Cohere.js";
import DeepInfra from "../llm/llms/DeepInfra.js";
import FreeTrial from "../llm/llms/FreeTrial.js";
import FunctionNetwork from "../llm/llms/FunctionNetwork.js";
import Gemini from "../llm/llms/Gemini.js";
import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js";
import LMStudio from "../llm/llms/LMStudio.js";
import Mistral from "../llm/llms/Mistral.js";
import NCompass from "../llm/llms/NCompass.js";
import Nebius from "../llm/llms/Nebius.js";
import Nvidia from "../llm/llms/Nvidia.js";
import Ollama from "../llm/llms/Ollama.js";
import OpenAI from "../llm/llms/OpenAI.js";
import SageMaker from "../llm/llms/SageMaker.js";
import Scaleway from "../llm/llms/Scaleway.js";
import SiliconFlow from "../llm/llms/SiliconFlow.js";
import ContinueProxy from "../llm/llms/stubs/ContinueProxy.js";
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider.js";
import VertexAI from "../llm/llms/VertexAI.js";
import Voyage from "../llm/llms/Voyage.js";
import WatsonX from "../llm/llms/WatsonX.js";
type EmbeddingsProviderConstructor = new (...args: any[]) => ILLM;
export const allEmbeddingsProviders: Record<
string,
EmbeddingsProviderConstructor
> = {
sagemaker: SageMaker,
bedrock: Bedrock,
ollama: Ollama,
"transformers.js": TransformersJsEmbeddingsProvider,
openai: OpenAI,
cohere: Cohere,
"free-trial": FreeTrial,
"function-network": FunctionNetwork,
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
gemini: Gemini,
"continue-proxy": ContinueProxy,
deepinfra: DeepInfra,
ncompass: NCompass,
nvidia: Nvidia,
voyage: Voyage,
mistral: Mistral,
nebius: Nebius,
vertexai: VertexAI,
watsonx: WatsonX,
lmstudio: LMStudio,
siliconflow: SiliconFlow,
scaleway: Scaleway,
};

View file

@ -0,0 +1,25 @@
import OpenAI from "../../llm/llms/OpenAI";
import { DocsCache } from "./DocsCache"; // adjust import path as needed
describe("DocsCache", () => {
let openAIEmbeddings: OpenAI;
beforeAll(() => {
openAIEmbeddings = new OpenAI({
apiKey: "",
model: "text-embedding-ada-002",
});
});
test("normalizeEmbeddingId() produces a valid ID without constructor name", async () => {
// Get the embedding ID from OpenAI embeddings provider
const embeddingId = DocsCache.normalizeEmbeddingId(
openAIEmbeddings.embeddingId,
);
// The ID should not contain the constructor name (OpenAI)
expect(embeddingId).toEqual(
`${openAIEmbeddings.model}::${openAIEmbeddings.maxEmbeddingChunkSize}`,
);
});
});

View file

@ -0,0 +1,83 @@
import request from "request";
import { Chunk } from "../..";
export interface SiteIndexingResults {
chunks: (Chunk & { embedding: number[] })[];
url: string;
title: string;
}
export class DocsCache {
static readonly AWS_REGION: string = "us-west-1";
static readonly BUCKET_NAME: string = "continue-preindexed-docs";
/**
* Normalizes an embedding ID by stripping the constructor name part.
* This is done because we don't care about the provider, just the
* model and the max embedding chunk size.
*/
static normalizeEmbeddingId(embeddingId: string): string {
// Split by "::" and remove the first part (constructor name)
const parts = embeddingId.split("::");
if (parts.length <= 1) return embeddingId; // Return original if no "::" found
// Return everything except the first part, joining with "::"
return parts.slice(1).join("::");
}
/**
* Gets the filepath for a given embedding ID and URL
*/
static getFilepathForEmbeddingIdAndUrl(
embeddingId: string,
url: string,
): string {
const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_"));
return normalizedEmbeddingId + "/" + normalizedUrl;
}
/**
* Gets the fully qualified S3 URL for a given filepath
*/
private static getS3Url(filepath: string): string {
const pathname = filepath.split("/").map(encodeURIComponent).join("/");
return `https://${this.BUCKET_NAME}.s3.${this.AWS_REGION}.amazonaws.com/${pathname}`;
}
/**
* Downloads cached site indexing results from S3 for a given embedding ID and URL
* @param embeddingId The embedding ID
* @param url The URL of the document
* @returns The downloaded data as a string
*/
static async getDocsCacheForUrl(
embeddingId: string,
url: string,
): Promise<string> {
const filepath = DocsCache.getFilepathForEmbeddingIdAndUrl(
embeddingId,
url,
);
return new Promise<string>((resolve, reject) => {
let data = "";
const url = this.getS3Url(filepath);
const download = request({
url,
});
download.on("response", (response: any) => {
if (response.statusCode !== 200) {
reject(
new Error("There was an error retrieving the pre-indexed doc"),
);
}
});
download.on("error", (err: any) => reject(err));
download.on("data", (chunk: any) => (data += chunk));
download.on("end", () => resolve(data));
});
}
}

View file

@ -1,156 +1,156 @@
/**
* @jest-environment jsdom
*/
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { SiteIndexingConfig } from "../../index.js";
import FileSystemIde from "../../util/filesystem.js";
import { editConfigJson } from "../../util/paths.js";
// /**
// * @jest-environment jsdom
// */
// import { ConfigHandler } from "../../config/ConfigHandler.js";
// import { SiteIndexingConfig } from "../../index.js";
// import { LLMLogger } from "../../llm/logger.js";
// import FileSystemIde from "../../util/filesystem.js";
// import { editConfigJson } from "../../util/paths.js";
import DocsService from "./DocsService.js";
import preIndexedDocs from "./preIndexedDocs.js";
// import DocsService from "./DocsService.js";
// import preIndexedDocs from "./preIndexedDocs.js";
describe.skip("DocsService Integration Tests", () => {
let ide: FileSystemIde;
let configHandler: ConfigHandler;
let docsService: DocsService;
// describe.skip("DocsService Integration Tests", () => {
// let ide: FileSystemIde;
// let configHandler: ConfigHandler;
// let docsService: DocsService;
const mockSiteConfig: SiteIndexingConfig = {
startUrl: "https://amplified.dev/",
title: "Test repo",
faviconUrl: "https://github.com/favicon.ico",
};
// const mockSiteConfig: SiteIndexingConfig = {
// startUrl: "https://amplified.dev/",
// title: "Test repo",
// faviconUrl: "https://github.com/favicon.ico",
// };
/**
* We need to reload config explicitly to handle the scenario where the
* config file update listeners are not called before we attempt to
* use the new config
*/
async function getReloadedConfig() {
await configHandler.reloadConfig();
const latestConfig = await configHandler.loadConfig();
// /**
// * We need to reload config explicitly to handle the scenario where the
// * config file update listeners are not called before we attempt to
// * use the new config
// */
// async function getReloadedConfig() {
// await configHandler.reloadConfig();
// const latestConfig = await configHandler.loadConfig();
return latestConfig;
}
// return latestConfig;
// }
beforeEach(async () => {
ide = new FileSystemIde(process.cwd());
// beforeEach(async () => {
// ide = new FileSystemIde(process.cwd());
const ideSettingsPromise = Promise.resolve({
remoteConfigSyncPeriod: 60,
userToken: "",
enableControlServerBeta: false,
continueTestEnvironment: "none" as const,
pauseCodebaseIndexOnStart: false,
ideSettings: {} as any,
enableDebugLogs: false,
remoteConfigServerUrl: "",
});
configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
async () => {},
Promise.resolve(undefined),
);
// const ideSettingsPromise = Promise.resolve({
// remoteConfigSyncPeriod: 60,
// userToken: "",
// continueTestEnvironment: "none" as const,
// pauseCodebaseIndexOnStart: false,
// ideSettings: {} as any,
// enableDebugLogs: false,
// remoteConfigServerUrl: "",
// });
// configHandler = new ConfigHandler(
// ide,
// ideSettingsPromise,
// new LLMLogger(),
// Promise.resolve(undefined),
// );
docsService = DocsService.createSingleton(configHandler, ide);
// docsService = DocsService.createSingleton(configHandler, ide);
await docsService.isInitialized;
});
// await docsService.isInitialized;
// });
test("Indexing, retrieval, and deletion of a new documentation site", async () => {
await docsService.indexAndAdd(mockSiteConfig);
// test("Indexing, retrieval, and deletion of a new documentation site", async () => {
// await docsService.indexAndAdd(mockSiteConfig);
let latestConfig = await getReloadedConfig();
// let latestConfig = await getReloadedConfig();
// Sqlite check
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
// // Sqlite check
// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
// config.json check
expect(latestConfig.config!.docs).toContainEqual(mockSiteConfig);
// // config.json check
// expect(latestConfig.config!.docs).toContainEqual(mockSiteConfig);
// Lance DB check
let retrievedChunks = await docsService.retrieveChunksFromQuery(
"test",
mockSiteConfig.startUrl,
5,
);
// // Lance DB check
// let retrievedChunks = await docsService.retrieveChunksFromQuery(
// "test",
// mockSiteConfig.startUrl,
// 5,
// );
expect(retrievedChunks.length).toBeGreaterThan(0);
// expect(retrievedChunks.length).toBeGreaterThan(0);
await docsService.delete(mockSiteConfig.startUrl);
// await docsService.delete(mockSiteConfig.startUrl);
// Sqlite check
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
// // Sqlite check
// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
// config.json check
latestConfig = await getReloadedConfig();
expect(latestConfig.config!.docs).not.toContainEqual(
expect.objectContaining(mockSiteConfig),
);
// // config.json check
// latestConfig = await getReloadedConfig();
// expect(latestConfig.config!.docs).not.toContainEqual(
// expect.objectContaining(mockSiteConfig),
// );
// LanceDB check
retrievedChunks = await docsService.retrieveChunksFromQuery(
"test",
mockSiteConfig.startUrl,
5,
);
expect(retrievedChunks.length).toBe(0);
});
// // LanceDB check
// retrievedChunks = await docsService.retrieveChunksFromQuery(
// "test",
// mockSiteConfig.startUrl,
// 5,
// );
// expect(retrievedChunks.length).toBe(0);
// });
// test("Reindexes when changing embeddings provider", async () => {
// const originalEmbeddingsProvider =
// await docsService.getEmbeddingsProvider();
// // test("Reindexes when changing embeddings provider", async () => {
// // const originalEmbeddingsProvider =
// // await docsService.getEmbeddingsProvider();
// // Change embeddings provider
// editConfigJson((config) => ({
// ...config,
// embeddingsProvider: {
// provider: FreeTrial.providerName,
// },
// }));
// // // Change embeddings provider
// // editConfigJson((config) => ({
// // ...config,
// // embeddingsProvider: {
// // provider: FreeTrial.providerName,
// // },
// // }));
// await getReloadedConfig();
// // await getReloadedConfig();
// const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
// // const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
// // Verify reindexing
// const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
// const [newMockVector] = await provider.embed(["test"]);
// // // Verify reindexing
// // const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
// // const [newMockVector] = await provider.embed(["test"]);
// expect(originalVector).not.toEqual(newMockVector);
// });
// // expect(originalVector).not.toEqual(newMockVector);
// // });
test("Handles pulling down and adding pre-indexed docs", async () => {
const preIndexedDoc = Object.values(preIndexedDocs)[0];
await docsService.indexAndAdd(preIndexedDoc);
});
// test("Handles pulling down and adding pre-indexed docs", async () => {
// const preIndexedDoc = Object.values(preIndexedDocs)[0];
// await docsService.indexAndAdd(preIndexedDoc);
// });
test("Config synchronization with SQLite", async () => {
await docsService.indexAndAdd(mockSiteConfig);
// test("Config synchronization with SQLite", async () => {
// await docsService.indexAndAdd(mockSiteConfig);
await getReloadedConfig();
// await getReloadedConfig();
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
editConfigJson((config) => {
const { docs, ...restConfig } = config;
return restConfig;
});
// editConfigJson((config) => {
// const { docs, ...restConfig } = config;
// return restConfig;
// });
await getReloadedConfig();
// await getReloadedConfig();
const startTime = Date.now();
const maxWaitTimeMs = 10_000;
// const startTime = Date.now();
// const maxWaitTimeMs = 10_000;
while (docsService.isSyncing) {
if (Date.now() - startTime > maxWaitTimeMs) {
throw new Error(
`Timeout: docsService.isSyncing did not complete within within ${maxWaitTimeMs}ms`,
);
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
// while (docsService.isSyncing) {
// if (Date.now() - startTime > maxWaitTimeMs) {
// throw new Error(
// `Timeout: docsService.isSyncing did not complete within within ${maxWaitTimeMs}ms`,
// );
// }
// await new Promise((resolve) => setTimeout(resolve, 100));
// }
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
});
});
// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
// });
// });

View file

@ -13,18 +13,15 @@ import {
SiteIndexingConfig,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import {
addContextProvider,
isSupportedLanceDbCpuTargetForLinux,
} from "../../config/util";
import { isSupportedLanceDbCpuTargetForLinux } from "../../config/util";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { IMessenger } from "../../protocol/messenger";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import { fetchFavicon } from "../../util/fetchFavicon";
import { GlobalContext } from "../../util/GlobalContext";
import {
editConfigJson,
editConfigFile,
getDocsSqlitePath,
getLanceDbPath,
} from "../../util/paths";
@ -37,15 +34,9 @@ import {
} from "./article";
import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import {
downloadFromS3,
getS3Filename,
S3Buckets,
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import type * as LanceType from "vectordb";
import { DocsCache, SiteIndexingResults } from "./DocsCache";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -73,6 +64,48 @@ export type AddParams = {
favicon?: string;
};
const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
newFailedDocs.push(siteIndexingConfig);
globalContext.update("failedDocs", newFailedDocs);
};
const removeFromFailedGlobalContext = (
siteIndexingConfig: SiteIndexingConfig,
) => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
globalContext.update("failedDocs", newFailedDocs);
};
const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
return failedDocs.find((d) =>
siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
};
const siteIndexingConfigsAreEqual = (
config1: SiteIndexingConfig,
config2: SiteIndexingConfig,
) => {
return (
config1.startUrl === config2.startUrl &&
config1.faviconUrl === config2.faviconUrl &&
config1.title === config2.title &&
config1.maxDepth === config2.maxDepth &&
config1.useLocalCrawling === config2.useLocalCrawling
);
};
/*
General process:
- On config update:
@ -89,8 +122,7 @@ export default class DocsService {
static lanceTableName = "docs";
static sqlitebTableName = "docs";
static preIndexedDocsEmbeddingsProvider =
new TransformersJsEmbeddingsProvider();
static defaultEmbeddingsProvider = new TransformersJsEmbeddingsProvider();
public isInitialized: Promise<void>;
public isSyncing: boolean = false;
@ -250,12 +282,8 @@ export default class DocsService {
return false;
}
/*
* Currently, we generate and host embeddings for pre-indexed docs using transformers.
* However, we don't ship transformers with the JetBrains extension.
* So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs.
*/
async canUsePreindexedDocs() {
// Determine if transformers.js embeddings are supported in this environment
async canUseTransformersEmbeddings() {
const ideInfo = await this.ideInfoPromise;
if (ideInfo.ideType === "jetbrains") {
return false;
@ -263,28 +291,26 @@ export default class DocsService {
return true;
}
// Determines if using preIndexed and returns proper embeddings provider
async getEmbeddingsProvider(startUrl: string) {
// Conditions for using a pre-indexed doc
// Must be in pre indexed docs file
const preIndexedDoc = preIndexedDocs[startUrl];
if (preIndexedDoc) {
// Most not be overriden by config
if (!this.config?.docs?.find((doc) => doc.startUrl === startUrl)) {
// Must be supported
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
return {
provider: DocsService.preIndexedDocsEmbeddingsProvider,
isPreindexed: true,
};
}
}
// Get the appropriate embeddings provider
async getEmbeddingsProvider() {
// First check if there's a config selected embeddings provider
if (this.config.selectedModelByRole.embed) {
return {
provider: this.config.selectedModelByRole.embed,
};
}
// Fall back to transformers if supported
const canUseTransformers = await this.canUseTransformersEmbeddings();
if (canUseTransformers) {
return {
provider: DocsService.defaultEmbeddingsProvider,
};
}
// No provider available
return {
provider: this.config.selectedModelByRole.embed,
isPreindexed: false,
provider: undefined,
};
}
@ -312,29 +338,6 @@ export default class DocsService {
}
async syncDocsWithPrompt(reIndex: boolean = false) {
if (!this.hasDocsContextProvider()) {
const actionMsg = "Add 'docs' context provider";
const res = await this.ide.showToast(
"info",
"Starting docs indexing",
actionMsg,
);
if (res === actionMsg) {
addContextProvider({
name: DocsContextProvider.description.title,
params: {},
});
void this.ide.showToast(
"info",
"Successfuly added docs context provider",
);
} else {
return;
}
}
await this.syncDocs(undefined, this.config, reIndex);
void this.ide.showToast("info", "Docs indexing completed");
@ -379,6 +382,45 @@ export default class DocsService {
}
}
/**
* Attempt to load document embeddings from cache
* @returns true if cache was successfully loaded, false otherwise
*/
private async tryLoadFromCache(
startUrl: string,
embeddingId: string,
siteIndexingConfig: SiteIndexingConfig,
): Promise<boolean> {
try {
const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
if (cacheHit) {
console.log(`Successfully loaded cached embeddings for ${startUrl}`);
// Update status to complete
this.handleStatusUpdate({
type: "docs",
id: startUrl,
embeddingsProviderId: embeddingId,
isReindexing: false,
title: siteIndexingConfig.title,
debugInfo: "Loaded from cache",
icon: siteIndexingConfig.faviconUrl,
url: startUrl,
progress: 1,
description: "Complete",
status: "complete",
});
return true;
}
} catch (e) {
console.log(`Error trying to fetch from cache: ${e}`);
// Continue with regular indexing
}
return false;
}
async indexAndAdd(
siteIndexingConfig: SiteIndexingConfig,
forceReindex: boolean = false,
@ -392,21 +434,28 @@ export default class DocsService {
return;
}
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
if (isPreindexed) {
console.warn("Attempted to indexAndAdd pre-indexed doc");
return;
}
const { provider } = await this.getEmbeddingsProvider();
if (!provider) {
console.warn("@docs indexAndAdd: no embeddings provider found");
return;
}
// Try to fetch from cache first before crawling
if (!forceReindex) {
const cacheLoaded = await this.tryLoadFromCache(
startUrl,
provider.embeddingId,
siteIndexingConfig,
);
if (cacheLoaded) {
return;
}
}
const startedWithEmbedder = provider.embeddingId;
// Check if doc has been successfully indexed with the given embedder
// Note at this point we know it's not a pre-indexed doc
const indexExists = await this.hasMetadata(startUrl);
// Build status update - most of it is fixed values
@ -426,12 +475,7 @@ export default class DocsService {
// If not force-reindexing and has failed with same config, don't reattempt
if (!forceReindex) {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const hasFailed = failedDocs.find((d) =>
this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
if (hasFailed) {
if (hasIndexingFailed(siteIndexingConfig)) {
console.log(
`Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`,
);
@ -466,25 +510,6 @@ export default class DocsService {
return;
}
const markFailedInGlobalContext = () => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
newFailedDocs.push(siteIndexingConfig);
globalContext.update("failedDocs", newFailedDocs);
};
const removeFromFailedGlobalContext = () => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
);
globalContext.update("failedDocs", newFailedDocs);
};
try {
this.docsIndexingQueue.add(startUrl);
@ -622,8 +647,8 @@ export default class DocsService {
progress: 1,
});
void this.ide.showToast("info", `Failed to index ${startUrl}`);
markFailedInGlobalContext();
// void this.ide.showToast("info", `Failed to index ${startUrl}`);
markFailedInGlobalContext(siteIndexingConfig);
return;
}
@ -672,13 +697,18 @@ export default class DocsService {
progress: 1,
});
void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
// Only show notificaitons if the user manually re-indexed, otherwise
// they are too noisy, especially when switching embeddings providers
// and we automatically re-index all docs
if (forceReindex) {
void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
}
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
removeFromFailedGlobalContext();
removeFromFailedGlobalContext(siteIndexingConfig);
} catch (e) {
console.error(
`Error indexing docs at: ${siteIndexingConfig.startUrl}`,
@ -699,42 +729,48 @@ export default class DocsService {
status: "failed",
progress: 1,
});
markFailedInGlobalContext();
markFailedInGlobalContext(siteIndexingConfig);
} finally {
this.docsIndexingQueue.delete(startUrl);
}
}
// When user requests a pre-indexed doc for the first time
// And pre-indexed embeddings are supported
// Fetch pre-indexed embeddings from S3, add to Lance, and then search those
private async fetchAndAddPreIndexedDocEmbeddings(title: string) {
const data = await downloadFromS3(
S3Buckets.continueIndexedDocs,
getS3Filename(
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId,
title,
),
);
/**
* Try to fetch embeddings from the S3 cache for any document URL
* @param startUrl The URL of the documentation site
* @param embeddingsProviderId The ID of the embeddings provider
* @returns True if cache hit and successfully loaded, false otherwise
*/
private async tryFetchFromCache(
startUrl: string,
embeddingId: string,
): Promise<boolean> {
try {
const data = await DocsCache.getDocsCacheForUrl(embeddingId, startUrl);
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
const startUrl = new URL(siteEmbeddings.url).toString();
// Parse the cached data
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
const faviconUrl = preIndexedDocs[startUrl].faviconUrl;
const favicon =
typeof faviconUrl === "string"
? await getFaviconBase64(faviconUrl)
: undefined;
// Try to get a favicon for the site
const favicon = await fetchFavicon(new URL(startUrl));
await this.add({
favicon,
siteIndexingConfig: {
startUrl,
title: siteEmbeddings.title,
},
chunks: siteEmbeddings.chunks,
embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
});
// Add the cached embeddings to our database
await this.add({
favicon,
siteIndexingConfig: {
startUrl,
title: siteEmbeddings.title || new URL(startUrl).hostname,
},
chunks: siteEmbeddings.chunks,
embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
});
return true;
} catch (e) {
// Cache miss or error - silently fail
console.log(`Cache miss for ${startUrl} with provider ${embeddingId}`);
return false;
}
}
// Retrieve docs embeds based on user input
@ -743,8 +779,7 @@ export default class DocsService {
startUrl: string,
nRetrieve: number,
) {
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
const { provider } = await this.getEmbeddingsProvider();
if (!provider) {
void this.ide.showToast(
@ -755,15 +790,11 @@ export default class DocsService {
return [];
}
if (isPreindexed) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDocs[startUrl]!["title"],
});
}
// Try to get embeddings for the query
const [vector] = await provider.embed([query]);
return await this.retrieveChunks(startUrl, vector, nRetrieve, isPreindexed);
// Retrieve chunks using the query vector
return await this.retrieveChunks(startUrl, vector, nRetrieve);
}
private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk {
@ -783,8 +814,7 @@ export default class DocsService {
const db = await this.getOrCreateSqliteDb();
try {
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
const { provider } = await this.getEmbeddingsProvider();
if (!provider) {
throw new Error("No embeddings model set");
@ -819,22 +849,26 @@ export default class DocsService {
config: siteIndexingConfig,
indexingStatus: this.statuses.get(startUrl),
chunks: rows.map(this.lanceDBRowToChunk),
isPreIndexedDoc: isPreindexed,
};
} catch (e) {
console.warn("Error getting details", e);
throw e;
}
}
// This is split into its own function so that it can be recursive
// in the case of fetching preindexed docs from s3
// This function attempts to retrieve chunks by vector similarity
// It will also attempt to fetch from cache if no results are found
async retrieveChunks(
startUrl: string,
vector: number[],
nRetrieve: number,
isPreindexed: boolean,
isRetry: boolean = false,
): Promise<Chunk[]> {
// Get the appropriate embeddings provider
const { provider } = await this.getEmbeddingsProvider();
if (!provider) {
return [];
}
// Lance doesn't have an embeddingsprovider column, instead it includes it in the table name
const table = await this.getOrCreateLanceTable({
initializationVector: vector,
@ -852,15 +886,22 @@ export default class DocsService {
console.warn("Error retrieving chunks from LanceDB", e);
}
// No docs are found for preindexed? try fetching once
if (docs.length === 0 && isPreindexed) {
if (isRetry) {
return [];
// If no docs are found and this isn't a retry, try fetching from cache
if (docs.length === 0 && !isRetry) {
try {
// Try to fetch the document from the S3 cache
const cacheHit = await this.tryFetchFromCache(
startUrl,
provider.embeddingId,
);
if (cacheHit) {
// If cache hit, retry the search once
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
}
} catch (e) {
console.warn("Error trying to fetch from cache:", e);
}
await this.fetchAndAddPreIndexedDocEmbeddings(
preIndexedDocs[startUrl]!["title"],
);
return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true);
}
return docs.map(this.lanceDBRowToChunk);
@ -912,10 +953,9 @@ export default class DocsService {
return result.favicon;
}
/*
Sync with no embeddings provider change
Ignores pre-indexed docs
*/
/**
* Sync with no embeddings provider change
*/
private async syncDocs(
oldConfig: ContinueConfig | undefined,
newConfig: ContinueConfig,
@ -933,11 +973,9 @@ export default class DocsService {
const currentlyIndexedDocs = await this.listMetadata();
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
// Anything found in sqlite but not in new config should be deleted if not preindexed
// Anything found in sqlite but not in new config should be deleted
const deletedDocs = currentlyIndexedDocs.filter(
(doc) =>
!preIndexedDocs[doc.startUrl] &&
!newConfigStartUrls.includes(doc.startUrl),
(doc) => !newConfigStartUrls.includes(doc.startUrl),
);
// Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
@ -953,10 +991,7 @@ export default class DocsService {
(d) => d.startUrl === doc.startUrl,
);
if (
oldConfigDoc &&
!this.siteIndexingConfigsAreEqual(oldConfigDoc, doc)
) {
if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
changedDocs.push(doc);
} else {
if (forceReindex) {
@ -1063,7 +1098,7 @@ export default class DocsService {
const conn = await lance.connect(getLanceDbPath());
const tableNames = await conn.tableNames();
const { provider } = await this.getEmbeddingsProvider(startUrl);
const { provider } = await this.getEmbeddingsProvider();
if (!provider) {
throw new Error(
@ -1143,36 +1178,38 @@ export default class DocsService {
);
}
private siteIndexingConfigsAreEqual(
config1: SiteIndexingConfig,
config2: SiteIndexingConfig,
) {
return (
config1.startUrl === config2.startUrl &&
config1.faviconUrl === config2.faviconUrl &&
config1.title === config2.title &&
config1.maxDepth === config2.maxDepth &&
config1.useLocalCrawling === config2.useLocalCrawling
);
}
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
// Handles the case where a user has manually added the doc to config.json
// so it already exists in the file
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
);
if (!doesEquivalentDocExist) {
editConfigJson((config) => ({
...config,
docs: [
...(config.docs?.filter(
(doc) => doc.startUrl !== siteIndexingConfig.startUrl,
) ?? []),
siteIndexingConfig,
],
}));
editConfigFile(
(config) => ({
...config,
docs: [
...(config.docs?.filter(
(doc) => doc.startUrl !== siteIndexingConfig.startUrl,
) ?? []),
siteIndexingConfig,
],
}),
(config) => ({
...config,
docs: [
...(config.docs?.filter(
(doc) => (doc as any).startUrl !== siteIndexingConfig.startUrl,
) ?? []),
{
name: siteIndexingConfig.title,
faviconUrl: siteIndexingConfig.faviconUrl,
startUrl: siteIndexingConfig.startUrl,
},
],
}),
);
}
}
@ -1216,10 +1253,19 @@ export default class DocsService {
(doc) => doc.startUrl === startUrl,
);
if (doesDocExist) {
editConfigJson((config) => ({
...config,
docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [],
}));
editConfigFile(
(config) => ({
...config,
docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [],
}),
(config) => ({
...config,
docs:
config.docs?.filter(
(doc) => "startUrl" in doc && doc.startUrl !== startUrl,
) || [],
}),
);
}
}

View file

@ -9,7 +9,7 @@ import PCR from "puppeteer-chromium-resolver";
import { ContinueConfig, IDE } from "../../..";
import {
editConfigJson,
editConfigFile,
getChromiumPath,
getContinueUtilsPath,
} from "../../../util/paths";
@ -26,13 +26,16 @@ export class ChromiumCrawler {
) {}
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
editConfigJson((config) => ({
...config,
experimental: {
...config.experimental,
useChromiumForDocsCrawling,
},
}));
editConfigFile(
(config) => ({
...config,
experimental: {
...config.experimental,
useChromiumForDocsCrawling,
},
}),
(config) => config, // Not used in config.yaml
);
}
async *crawl(): AsyncGenerator<PageData> {

View file

@ -1,7 +1,7 @@
import { type Database } from "sqlite";
import { type Table } from "vectordb";
import { editConfigJson, migrate } from "../../util/paths.js";
import { editConfigFile, migrate } from "../../util/paths.js";
import DocsService, { SqliteDocsRow } from "./DocsService.js";
@ -58,10 +58,22 @@ export async function runSqliteMigrations(db: Database) {
const sqliteDocs = await db.all<
Array<Pick<SqliteDocsRow, "title" | "startUrl">>
>(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`);
editConfigJson((config) => ({
...config,
docs: [...(config.docs || []), ...sqliteDocs],
}));
editConfigFile(
(config) => ({
...config,
docs: [...(config.docs || []), ...sqliteDocs],
}),
(config) => ({
...config,
docs: [
...(config.docs || []),
...sqliteDocs.map((doc) => ({
name: doc.title,
startUrl: doc.startUrl,
})),
],
}),
);
}
} finally {
resolve(undefined);

View file

@ -1,52 +0,0 @@
import request from "request";
import { Chunk } from "../../";
export function getS3Filename(
embeddingsProviderId: string,
title: string,
): string {
return `_TransformersJsEmbeddingsProvider::all-MiniLM-L6-v2/${title}`;
}
export enum S3Buckets {
continueIndexedDocs = "continue-indexed-docs",
}
const AWS_REGION = "us-west-1";
export async function downloadFromS3(
bucket: string,
fileName: string,
): Promise<string> {
return new Promise<string>((resolve, reject) => {
let data = "";
const download = request({
url: `https://${bucket}.s3.${AWS_REGION}.amazonaws.com/${fileName}`,
});
download.on("response", (response: any) => {
if (response.statusCode !== 200) {
reject(new Error("There was an error retreiving the pre-indexed doc"));
}
});
download.on("error", (err: any) => {
reject(err);
});
download.on("data", (chunk: any) => {
data += chunk;
});
download.on("end", () => {
resolve(data);
});
});
}
export interface SiteIndexingResults {
chunks: (Chunk & { embedding: number[] })[];
url: string;
title: string;
}

View file

@ -1,368 +0,0 @@
import { SiteIndexingConfig } from "../../";
const preIndexedDocs: Record<
SiteIndexingConfig["startUrl"],
SiteIndexingConfig
> = {
"https://jinja.palletsprojects.com/en/3.1.x/": {
title: "Jinja",
startUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
rootUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
faviconUrl: "https://jinja.palletsprojects.com/favicon.ico",
},
"https://react.dev/reference/": {
title: "React",
startUrl: "https://react.dev/reference/",
rootUrl: "https://react.dev/reference/",
faviconUrl: "https://react.dev/favicon.ico",
},
"https://posthog.com/docs": {
title: "PostHog",
startUrl: "https://posthog.com/docs",
rootUrl: "https://posthog.com/docs",
faviconUrl: "https://posthog.com/favicon.ico",
},
"https://expressjs.com/en/5x/api.html": {
title: "Express",
startUrl: "https://expressjs.com/en/5x/api.html",
rootUrl: "https://expressjs.com/en/5x/",
faviconUrl: "https://expressjs.com/favicon.ico",
},
"https://platform.openai.com/docs/": {
title: "OpenAI",
startUrl: "https://platform.openai.com/docs/",
rootUrl: "https://platform.openai.com/docs/",
faviconUrl: "https://platform.openai.com/favicon.ico",
},
"https://www.prisma.io/docs": {
title: "Prisma",
startUrl: "https://www.prisma.io/docs",
rootUrl: "https://www.prisma.io/docs",
faviconUrl: "https://www.prisma.io/favicon.ico",
},
"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html": {
title: "Boto3",
startUrl:
"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html",
rootUrl: "https://boto3.amazonaws.com/v1/documentation/api/latest/",
faviconUrl: "https://boto3.amazonaws.com/favicon.ico",
},
"https://pytorch.org/docs/stable/": {
title: "Pytorch",
startUrl: "https://pytorch.org/docs/stable/",
rootUrl: "https://pytorch.org/docs/stable/",
faviconUrl: "https://pytorch.org/favicon.ico",
},
"https://redis.io/docs/": {
title: "Redis",
startUrl: "https://redis.io/docs/",
rootUrl: "https://redis.io/docs/",
faviconUrl: "https://redis.io/favicon.ico",
},
"https://axios-http.com/docs/intro": {
title: "Axios",
startUrl: "https://axios-http.com/docs/intro",
rootUrl: "https://axios-http.com/docs",
faviconUrl: "https://axios-http.com/favicon.ico",
},
"https://redwoodjs.com/docs/introduction": {
title: "Redwood JS",
startUrl: "https://redwoodjs.com/docs/introduction",
rootUrl: "https://redwoodjs.com/docs",
faviconUrl: "https://redwoodjs.com/favicon.ico",
},
"https://graphql.org/learn/": {
title: "GraphQL",
startUrl: "https://graphql.org/learn/",
rootUrl: "https://graphql.org/learn/",
faviconUrl: "https://graphql.org/favicon.ico",
},
"https://www.typescriptlang.org/docs/": {
title: "Typescript",
startUrl: "https://www.typescriptlang.org/docs/",
rootUrl: "https://www.typescriptlang.org/docs/",
faviconUrl: "https://www.typescriptlang.org/favicon.ico",
},
"https://jestjs.io/docs/getting-started": {
title: "Jest",
startUrl: "https://jestjs.io/docs/getting-started",
rootUrl: "https://jestjs.io/docs",
faviconUrl: "https://jestjs.io/favicon.ico",
},
"https://tailwindcss.com/docs/installation": {
title: "Tailwind CSS",
startUrl: "https://tailwindcss.com/docs/installation",
rootUrl: "https://tailwindcss.com/docs",
faviconUrl: "https://tailwindcss.com/favicon.ico",
},
"https://vuejs.org/guide/introduction.html": {
title: "Vue.js",
startUrl: "https://vuejs.org/guide/introduction.html",
rootUrl: "https://vuejs.org",
faviconUrl: "https://vuejs.org/favicon.ico",
},
"https://svelte.dev/docs/introduction": {
title: "Svelte",
startUrl: "https://svelte.dev/docs/introduction",
rootUrl: "https://svelte.dev/docs",
faviconUrl: "https://svelte.dev/favicon.ico",
},
"https://docs.github.com/en/actions": {
title: "GitHub Actions",
startUrl: "https://docs.github.com/en/actions",
rootUrl: "https://docs.github.com/en/actions",
faviconUrl: "https://docs.github.com/favicon.ico",
},
"https://nodejs.org/docs/latest/api/": {
title: "NodeJS",
startUrl: "https://nodejs.org/docs/latest/api/",
rootUrl: "https://nodejs.org/docs/latest/api/",
faviconUrl: "https://nodejs.org/favicon.ico",
},
"https://socket.io/docs/v4/": {
title: "Socket.io",
startUrl: "https://socket.io/docs/v4/",
rootUrl: "https://socket.io/docs/v4/",
faviconUrl: "https://socket.io/favicon.ico",
},
"https://docs.gradle.org/current/userguide/userguide.html": {
title: "Gradle",
startUrl: "https://docs.gradle.org/current/userguide/userguide.html",
rootUrl: "https://docs.gradle.org/current",
faviconUrl: "https://docs.gradle.org/favicon.ico",
},
"https://redux-toolkit.js.org/introduction/getting-started": {
title: "Redux Toolkit",
startUrl: "https://redux-toolkit.js.org/introduction/getting-started",
rootUrl: "https://redux-toolkit.js.org",
faviconUrl: "https://redux-toolkit.js.org/favicon.ico",
},
"https://docs.trychroma.com/": {
title: "Chroma",
startUrl: "https://docs.trychroma.com/",
rootUrl: "https://docs.trychroma.com/",
faviconUrl: "https://docs.trychroma.com/favicon.ico",
},
"https://www.sqlite.org/docs.html": {
title: "SQLite",
startUrl: "https://www.sqlite.org/docs.html",
rootUrl: "https://www.sqlite.org",
faviconUrl: "https://www.sqlite.org/favicon.ico",
},
"https://redux.js.org/introduction/getting-started": {
title: "Redux",
startUrl: "https://redux.js.org/introduction/getting-started",
rootUrl: "https://redux.js.org",
faviconUrl: "https://redux.js.org/favicon.ico",
},
"https://prettier.io/docs/en/": {
title: "Prettier",
startUrl: "https://prettier.io/docs/en/",
rootUrl: "https://prettier.io/docs/en/",
faviconUrl: "https://prettier.io/favicon.ico",
},
"https://code.visualstudio.com/api": {
title: "VS Code Extension API",
startUrl: "https://code.visualstudio.com/api",
rootUrl: "https://code.visualstudio.com/api",
faviconUrl: "https://code.visualstudio.com/favicon.ico",
},
"https://docs.continue.dev/intro": {
title: "Continue",
startUrl: "https://docs.continue.dev/intro",
rootUrl: "https://docs.continue.dev",
faviconUrl: "https://docs.continue.dev/favicon.ico",
},
"https://api.jquery.com/": {
title: "jQuery",
startUrl: "https://api.jquery.com/",
rootUrl: "https://api.jquery.com/",
faviconUrl: "https://api.jquery.com/favicon.ico",
},
"https://docs.python.org/3/": {
title: "Python",
startUrl: "https://docs.python.org/3/",
rootUrl: "https://docs.python.org/3/",
faviconUrl: "https://docs.python.org/favicon.ico",
},
"https://doc.rust-lang.org/book/": {
title: "Rust",
startUrl: "https://doc.rust-lang.org/book/",
rootUrl: "https://doc.rust-lang.org/book/",
faviconUrl: "https://doc.rust-lang.org/favicon.ico",
},
"https://plugins.jetbrains.com/docs/intellij/welcome.html": {
title: "IntelliJ Platform SDK",
startUrl: "https://plugins.jetbrains.com/docs/intellij/welcome.html",
rootUrl: "https://plugins.jetbrains.com/docs/intellij",
faviconUrl: "https://plugins.jetbrains.com/favicon.ico",
},
"https://docs.docker.com/": {
title: "Docker",
startUrl: "https://docs.docker.com/",
rootUrl: "https://docs.docker.com/",
faviconUrl: "https://docs.docker.com/favicon.ico",
},
"https://docs.npmjs.com/": {
title: "NPM",
startUrl: "https://docs.npmjs.com/",
rootUrl: "https://docs.npmjs.com/",
faviconUrl: "https://docs.npmjs.com/favicon.ico",
},
"https://tiptap.dev/docs/editor/introduction": {
title: "TipTap",
startUrl: "https://tiptap.dev/docs/editor/introduction",
rootUrl: "https://tiptap.dev/docs",
faviconUrl: "https://tiptap.dev/favicon.ico",
},
"https://esbuild.github.io/": {
title: "esbuild",
startUrl: "https://esbuild.github.io/",
rootUrl: "https://esbuild.github.io/",
faviconUrl: "https://esbuild.github.io/favicon.ico",
},
"https://tree-sitter.github.io/tree-sitter/": {
title: "Tree Sitter",
startUrl: "https://tree-sitter.github.io/tree-sitter/",
rootUrl: "https://tree-sitter.github.io/tree-sitter/",
faviconUrl: "https://tree-sitter.github.io/favicon.ico",
},
"https://docs.netlify.com/": {
title: "Netlify",
startUrl: "https://docs.netlify.com/",
rootUrl: "https://docs.netlify.com/",
faviconUrl: "https://docs.netlify.com/favicon.ico",
},
"https://replicate.com/docs": {
title: "Replicate",
startUrl: "https://replicate.com/docs",
rootUrl: "https://replicate.com/docs",
faviconUrl: "https://replicate.com/favicon.ico",
},
"https://www.w3schools.com/html/default.asp": {
title: "HTML",
startUrl: "https://www.w3schools.com/html/default.asp",
rootUrl: "https://www.w3schools.com/html",
faviconUrl: "https://www.w3schools.com/favicon.ico",
},
"https://www.w3schools.com/css/default.asp": {
title: "CSS",
startUrl: "https://www.w3schools.com/css/default.asp",
rootUrl: "https://www.w3schools.com/css",
faviconUrl: "https://www.w3schools.com/favicon.ico",
},
"https://python.langchain.com/docs/get_started/introduction": {
title: "Langchain",
startUrl: "https://python.langchain.com/docs/get_started/introduction",
rootUrl: "https://python.langchain.com/docs",
faviconUrl: "https://python.langchain.com/favicon.ico",
},
"https://developer.woocommerce.com/docs/": {
title: "WooCommerce",
startUrl: "https://developer.woocommerce.com/docs/",
rootUrl: "https://developer.woocommerce.com/docs/",
faviconUrl: "https://developer.woocommerce.com/favicon.ico",
},
"https://developer.wordpress.org/reference/": {
title: "WordPress",
startUrl: "https://developer.wordpress.org/reference/",
rootUrl: "https://developer.wordpress.org/reference/",
faviconUrl: "https://developer.wordpress.org/favicon.ico",
},
"https://doc.qt.io/qtforpython-6/quickstart.html": {
title: "PySide6",
startUrl: "https://doc.qt.io/qtforpython-6/quickstart.html",
rootUrl: "https://doc.qt.io/qtforpython-6/api.html",
faviconUrl: "https://doc.qt.io/favicon.ico",
},
"https://getbootstrap.com/docs/5.3/getting-started/introduction/": {
title: "Bootstrap",
startUrl: "https://getbootstrap.com/docs/5.3/getting-started/introduction/",
rootUrl: "https://getbootstrap.com/docs/5.3/",
faviconUrl: "https://getbootstrap.com/favicon.ico",
},
"https://alpinejs.dev/start-here": {
title: "Alpine.js",
startUrl: "https://alpinejs.dev/start-here",
rootUrl: "https://alpinejs.dev/",
faviconUrl: "https://alpinejs.dev/favicon.ico",
},
"https://learn.microsoft.com/en-us/dotnet/csharp/": {
title: "C# Language Reference",
startUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/",
rootUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/",
faviconUrl: "https://learn.microsoft.com/favicon.ico",
},
"https://docs.godotengine.org/en/latest/": {
title: "Godot",
startUrl: "https://docs.godotengine.org/en/latest/",
rootUrl: "https://docs.godotengine.org/en/latest/",
faviconUrl: "https://godotengine.org/favicon.ico",
},
"https://docs.amplify.aws/react/start/": {
title: "AWS Amplify (Gen 2)",
startUrl: "https://docs.amplify.aws/react/start/",
rootUrl: "https://docs.amplify.aws/react/",
faviconUrl: "https://docs.amplify.aws/favicon.ico",
},
"https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": {
title: "AWS SDK for JavaScript v3",
startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/",
rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/",
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
},
"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": {
title: "AWS CDK v2",
startUrl:
"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html",
rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/",
faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png",
},
"https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": {
title: "AWS CLI commands",
startUrl:
"https://awscli.amazonaws.com/v2/documentation/api/latest/index.html",
rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/",
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
},
"https://llama-stack.readthedocs.io/": {
title: "Llama Stack",
startUrl: "https://llama-stack.readthedocs.io/",
rootUrl: "https://llama-stack.readthedocs.io/",
},
"https://go.dev/doc": {
title: "Go",
startUrl: "https://go.dev/doc",
rootUrl: "https://go.dev",
faviconUrl: "https://go.dev/favicon.ico",
},
"https://api.flutter.dev": {
title: "Flutter",
startUrl: "https://api.flutter.dev",
rootUrl: "https://api.flutter.dev",
faviconUrl: "https://api.flutter.dev/flutter/static-assets/favicon.png",
},
"https://api.dart.dev": {
title: "Dart",
startUrl: "https://api.dart.dev",
rootUrl: "https://api.dart.dev",
faviconUrl: "https://api.dart.dev/static-assets/favicon.png",
},
"https://docs.asksage.ai/": {
title: "Ask Sage",
startUrl: "https://docs.asksage.ai/",
rootUrl: "https://docs.asksage.ai/",
},
"https://angular.dev/": {
title: "Angular",
startUrl: "https://angular.dev/",
rootUrl: "https://angular.dev/",
},
"https://docs.djangoproject.com/": {
title: "Django",
startUrl: "https://docs.djangoproject.com/",
rootUrl: "https://docs.djangoproject.com/",
}
};
export default preIndexedDocs;

View file

@ -158,18 +158,21 @@ async function getAddRemoveForTag(
const updateLastUpdated: PathAndCacheKey[] = [];
// First, group items by path and find latest timestamp for each
const pathGroups = new Map<string, {
latest: { lastUpdated: number, cacheKey: string },
allVersions: Array<{ cacheKey: string }>
}>();
const pathGroups = new Map<
string,
{
latest: { lastUpdated: number; cacheKey: string };
allVersions: Array<{ cacheKey: string }>;
}
>();
for (const item of saved) {
const { lastUpdated, path, cacheKey } = item;
if (!pathGroups.has(path)) {
pathGroups.set(path, {
latest: { lastUpdated, cacheKey },
allVersions: [{ cacheKey }]
allVersions: [{ cacheKey }],
});
} else {
const group = pathGroups.get(path)!;
@ -530,6 +533,6 @@ export function truncateToLastNBytes(input: string, maxBytes: number): string {
return input.substring(startIndex, input.length);
}
export function truncateSqliteLikePattern(input: string) {
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH);
export function truncateSqliteLikePattern(input: string, safety: number = 100) {
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety);
}

View file

@ -97,7 +97,7 @@ describe("walkDir functions", () => {
);
});
it("should handle onlyDirs option", async () => {
it("should handle include option", async () => {
addToTestDir([
"src/",
["src/file1.ts", "content1"],
@ -109,7 +109,7 @@ describe("walkDir functions", () => {
(await testIde.getWorkspaceDirs())[0],
testIde,
{
onlyDirs: true,
include: "dirs",
},
);

View file

@ -10,10 +10,11 @@ import {
} from "./ignore";
export interface WalkerOptions {
onlyDirs?: boolean;
include?: "dirs" | "files" | "both";
returnRelativeUrisPaths?: boolean;
source?: string;
overrideDefaultIgnores?: Ignore;
recursive?: boolean;
}
type Entry = [string, FileType];
@ -195,7 +196,7 @@ class DFSWalker {
if (this.entryIsDirectory(entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
if (this.options.include === "dirs") {
continue;
}
}
@ -221,19 +222,22 @@ class DFSWalker {
}
if (this.entryIsDirectory(entry)) {
stack.push({
walkableEntry,
ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.recursive) {
stack.push({
walkableEntry,
ignoreContexts,
});
}
if (this.options.include !== "files") {
// if yielding dirs or both, walker includes relative paths
const trailingSlash = this.options.include === "dirs" ? "" : "/";
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
yield walkableEntry.relativeUriPath + trailingSlash;
} else {
yield walkableEntry.uri;
yield walkableEntry.uri + trailingSlash;
}
}
} else {
} else if (this.options.include !== "dirs") {
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
@ -257,8 +261,9 @@ class DFSWalker {
}
const defaultOptions: WalkerOptions = {
onlyDirs: false,
include: "files",
returnRelativeUrisPaths: false,
recursive: true,
};
export async function* walkDirAsync(

View file

@ -1,5 +1,5 @@
const DEFAULT_MAX_TOKENS = 4096;
const DEFAULT_CONTEXT_LENGTH = 8096;
const DEFAULT_CONTEXT_LENGTH = 8192;
const DEFAULT_TEMPERATURE = 0.5;
const DEFAULT_ARGS = {
@ -32,6 +32,11 @@ const PROXY_URL = "http://localhost:65433";
const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
const DEFAULT_MAX_BATCH_SIZE = 64;
export enum LLMConfigurationStatuses {
VALID = "valid",
MISSING_API_KEY = "missing-api-key",
}
export {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,

View file

@ -1,24 +1,76 @@
import { ChatHistoryItem, ChatMessage, MessagePart } from "../";
import {
ChatHistoryItem,
ChatMessage,
RuleWithSource,
TextMessagePart,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import { messageIsEmpty } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
const DEFAULT_SYSTEM_MESSAGE = `<important_rules>
Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'.
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L8";
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
Always include the language and file name in the info string when you write code blocks.
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
When addressing code modification requests, present a concise code snippet that
emphasizes only the necessary changes and uses abbreviated placeholders for
unmodified sections. For example:
\`\`\`language /path/to/file
// ... rest of code here ...
{{ modified code here }}
// ... rest of code here ...
{{ another modification }}
// ... rest of code here ...
\`\`\`
In existing files, you should always restate the function or class that the snippet belongs to:
\`\`\`language /path/to/file
// ... rest of code here ...
function exampleFunction() {
// ... rest of code here ...
{{ modified code here }}
// ... rest of code here ...
}
// ... rest of code here ...
\`\`\`
Since users have access to their complete file, they prefer reading only the
relevant modifications. It's perfectly acceptable to omit unmodified portions
at the beginning, middle, or end of files using these "lazy" comments. Only
provide the complete file when explicitly requested. Include a concise explanation
of changes unless the user specifically asks for code only.
</important_rules>`;
const CANCELED_TOOL_CALL_MESSAGE =
"This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool.";
export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] {
export function constructMessages(
history: ChatHistoryItem[],
baseChatSystemMessage: string | undefined,
rules: RuleWithSource[],
modelName: string,
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
);
const msgs: ChatMessage[] = [];
msgs.push({
role: "system",
content: DEFAULT_SYSTEM_MESSAGE,
});
for (let i = 0; i < filteredHistory.length; i++) {
const historyItem = filteredHistory[i];
@ -26,9 +78,14 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] {
// Gather context items for user messages
let content = normalizeToMessageParts(historyItem.message);
const ctxItems = historyItem.contextItems.map((ctxItem) => {
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
});
const ctxItems = historyItem.contextItems
.map((ctxItem) => {
return {
type: "text",
text: `${ctxItem.content}\n`,
} as TextMessagePart;
})
.filter((part) => !!part.text.trim());
content = [...ctxItems, ...content];
msgs.push({
@ -46,6 +103,32 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] {
}
}
const userMessage = findLast(msgs, (msg) => msg.role === "user") as
| UserChatMessage
| undefined;
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
rules,
userMessage,
currentModel: modelName,
});
if (systemMessage.trim()) {
msgs.unshift({
role: "system",
content: systemMessage,
});
}
// We dispatch an empty assistant chat message to the history on submission. Don't send it
const lastMessage = msgs.at(-1);
if (
lastMessage &&
lastMessage.role === "assistant" &&
messageIsEmpty(lastMessage)
) {
msgs.pop();
}
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const { id, ...rest } = msg as any;

View file

@ -1,3 +1,4 @@
// @ts-nocheck
// Generated by continue
import { ChatMessage, MessagePart } from "../index.js";
import {

View file

@ -11,6 +11,12 @@ import {
import { autodetectTemplateType } from "./autodetect.js";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
import llamaTokenizer from "./llamaTokenizer.js";
import {
addSpaceToAnyEmptyMessages,
chatMessageIsEmpty,
flattenMessages,
messageHasToolCalls,
} from "./messages.js";
interface Encoding {
encode: Tiktoken["encode"];
decode: Tiktoken["decode"];
@ -27,9 +33,9 @@ class LlamaEncoding implements Encoding {
}
class NonWorkerAsyncEncoder implements AsyncEncoder {
constructor(private readonly encoding: Encoding) { }
constructor(private readonly encoding: Encoding) {}
async close(): Promise<void> { }
async close(): Promise<void> {}
async encode(text: string): Promise<number[]> {
return this.encoding.encode(text);
@ -118,31 +124,6 @@ function countTokens(
}
}
function messageHasToolCalls(msg: ChatMessage): boolean {
return msg.role === "assistant" && !!msg.toolCalls;
}
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
const flattened: ChatMessage[] = [];
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
if (
flattened.length > 0 &&
flattened[flattened.length - 1].role === msg.role &&
!messageHasToolCalls(msg) &&
!messageHasToolCalls(flattened[flattened.length - 1])
) {
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
} else {
flattened.push(msg);
}
}
return flattened;
}
function countChatMessageTokens(
modelName: string,
chatMessage: ChatMessage,
@ -240,10 +221,19 @@ function summarize(message: ChatMessage): string {
function pruneChatHistory(
modelName: string,
chatHistory: ChatMessage[],
msgs: ChatMessage[],
contextLength: number,
tokensForCompletion: number,
): ChatMessage[] {
// Move system message to 2nd to last to give it priority
const systemMessage = msgs.find((msg) => msg.role === "system");
const chatHistory: ChatMessage[] = msgs.filter(
(msg) => msg.role !== "system",
);
if (systemMessage) {
chatHistory.splice(-1, 0, systemMessage);
}
let totalTokens =
tokensForCompletion +
chatHistory.reduce((acc, message) => {
@ -251,16 +241,35 @@ function pruneChatHistory(
}, 0);
// 0. Prune any messages that take up more than 1/3 of the context length
const longestMessages = [...chatHistory];
longestMessages.sort((a, b) => b.content.length - a.content.length);
const zippedMessagesAndTokens: [ChatMessage, number][] = [];
const longerThanOneThird = longestMessages.filter(
(message: ChatMessage) =>
countTokens(message.content, modelName) > contextLength / 3,
// Zipped ChatMessage with its token counts
chatHistory.forEach((message) => {
const zippedItem: [ChatMessage, number] = [
message,
countTokens(message.content, modelName),
];
zippedMessagesAndTokens.push(zippedItem);
});
const zippedLongerThanOneThird = zippedMessagesAndTokens.filter(
([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3,
);
const distanceFromThird = longerThanOneThird.map(
(message: ChatMessage) =>
countTokens(message.content, modelName) - contextLength / 3,
zippedLongerThanOneThird.sort(
(
[_messageA, tokensA]: [ChatMessage, number],
[_messageB, tokensB]: [ChatMessage, number],
) => {
return tokensB - tokensA;
},
);
const longerThanOneThird = zippedLongerThanOneThird.map(
([message, _token]: [ChatMessage, number]) => message,
);
const distanceFromThird = zippedLongerThanOneThird.map(
([_message, token]: [ChatMessage, number]) => token - contextLength / 3,
);
for (let i = 0; i < longerThanOneThird.length; i++) {
@ -280,7 +289,7 @@ function pruneChatHistory(
// 1. Replace beyond last 5 messages with summary
let i = 0;
while (totalTokens > contextLength && i < chatHistory.length - 5) {
const message = chatHistory[0];
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(summarize(message), modelName);
message.content = summarize(message);
@ -288,11 +297,7 @@ function pruneChatHistory(
}
// 2. Remove entire messages until the last 5
while (
chatHistory.length > 5 &&
totalTokens > contextLength &&
chatHistory.length > 0
) {
while (chatHistory.length > 5 && totalTokens > contextLength) {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
@ -313,8 +318,21 @@ function pruneChatHistory(
// 4. Remove entire messages in the last 5, except last 1
while (totalTokens > contextLength && chatHistory.length > 1) {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
// If tool call/response detected prune both (can't have response with no call)
// TODO prune lines from tool response before pruning both messages
if (
chatHistory.length > 2 &&
messageHasToolCalls(chatHistory[0]) &&
chatHistory[1].role === "tool"
) {
const firstMessage = chatHistory.shift()!;
const secondMessage = chatHistory.shift()!;
totalTokens -= countTokens(firstMessage.content, modelName);
totalTokens -= countTokens(secondMessage.content, modelName);
} else {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
}
// 5. Truncate last message
@ -329,112 +347,37 @@ function pruneChatHistory(
totalTokens = contextLength;
}
// put system message back if applicable
if (
chatHistory.length > 1 &&
chatHistory[chatHistory.length - 2].role === "system"
) {
const movedSystemMessage = chatHistory.splice(-2, 1)[0];
chatHistory.unshift(movedSystemMessage);
}
return chatHistory;
}
function messageIsEmpty(message: ChatMessage): boolean {
if (typeof message.content === "string") {
return message.content.trim() === "";
}
if (Array.isArray(message.content)) {
return message.content.every(
(item) => item.type === "text" && item.text?.trim() === "",
);
}
return false;
}
function compileChatMessages({
modelName,
msgs,
contextLength,
maxTokens,
supportsImages,
}: {
modelName: string;
msgs: ChatMessage[];
contextLength: number;
maxTokens: number;
supportsImages: boolean;
}): ChatMessage[] {
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] {
return messages.map((message) => {
if (messageIsEmpty(message)) {
message.content = " ";
}
return message;
});
}
function chatMessageIsEmpty(message: ChatMessage): boolean {
switch (message.role) {
case "system":
case "user":
return (
typeof message.content === "string" && message.content.trim() === ""
);
case "assistant":
return (
typeof message.content === "string" &&
message.content.trim() === "" &&
!message.toolCalls
);
case "thinking":
case "tool":
return false;
}
}
function compileChatMessages(
modelName: string,
msgs: ChatMessage[] | undefined,
contextLength: number,
maxTokens: number,
supportsImages: boolean,
prompt: string | undefined = undefined,
functions: any[] | undefined = undefined,
systemMessage: string | undefined = undefined,
): ChatMessage[] {
let msgsCopy = msgs
? msgs
.map((msg) => ({ ...msg }))
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
: [];
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
if (prompt) {
const promptMsg: ChatMessage = {
role: "user",
content: prompt,
};
msgsCopy.push(promptMsg);
}
if (
(systemMessage && systemMessage.trim() !== "") ||
msgs?.[0]?.role === "system"
) {
let content = "";
if (msgs?.[0]?.role === "system") {
content = renderChatMessage(msgs?.[0]);
}
if (systemMessage && systemMessage.trim() !== "") {
const shouldAddNewLines = content !== "";
if (shouldAddNewLines) {
content += "\n\n";
}
content += systemMessage;
}
const systemChatMsg: ChatMessage = {
role: "system",
content,
};
// Insert as second to last
// Later moved to top, but want second-priority to last user message
msgsCopy.splice(-1, 0, systemChatMsg);
}
let functionTokens = 0;
if (functions) {
for (const func of functions) {
functionTokens += countTokens(JSON.stringify(func), modelName);
}
}
if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) {
throw new Error(
`maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`,
);
}
// If images not supported, convert MessagePart[] to string
if (!supportsImages) {
for (const msg of msgsCopy) {
@ -449,14 +392,9 @@ function compileChatMessages(
modelName,
msgsCopy,
contextLength,
functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY,
maxTokens + TOKEN_BUFFER_FOR_SAFETY,
);
if (history.length >= 2 && history[history.length - 2].role === "system") {
const movedSystemMessage = history.splice(-2, 1)[0];
history.unshift(movedSystemMessage);
}
const flattenedHistory = flattenMessages(history);
return flattenedHistory;
@ -466,10 +404,10 @@ export {
compileChatMessages,
countTokens,
countTokensAsync,
flattenMessages,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,
pruneStringFromBottom,
pruneStringFromTop
pruneStringFromTop,
};

View file

@ -1,6 +1,7 @@
import { ChatMessage, LLMOptions } from "..";
import { BaseLLM } from ".";
import { LLMLogger } from "./logger";
class DummyLLM extends BaseLLM {
static providerName = "openai";
@ -30,11 +31,10 @@ describe("BaseLLM", () => {
const templatMessagesFunction = (messages: ChatMessage[]) => {
return messages[0]?.content.toString() ?? "";
};
const writeLogFunction = async () => {};
const llmLogger = new LLMLogger();
const options: LLMOptions = {
model: "gpt-3.5-turbo",
uniqueId: "testId",
systemMessage: "Test System Message",
contextLength: 1024,
completionOptions: {
model: "some-model",
@ -43,7 +43,7 @@ describe("BaseLLM", () => {
requestOptions: {},
promptTemplates: {},
templateMessages: templatMessagesFunction,
writeLog: writeLogFunction,
logger: llmLogger,
llmRequestHook: () => {},
apiKey: "testApiKey",
aiGatewaySlug: "testSlug",
@ -61,13 +61,12 @@ describe("BaseLLM", () => {
expect(instance.title).toBeDefined();
expect(instance.uniqueId).toBe("testId");
expect(instance.model).toBe("gpt-3.5-turbo");
expect(instance.systemMessage).toBe("Test System Message");
expect(instance.contextLength).toBe(1024);
expect(instance.completionOptions.maxTokens).toBe(150);
expect(instance.requestOptions).toEqual({});
expect(instance.promptTemplates).toEqual({});
expect(instance.templateMessages).toEqual(templatMessagesFunction);
expect(instance.writeLog).toBe(writeLogFunction);
expect(instance.logger).toBe(llmLogger);
expect(instance.apiKey).toBe("testApiKey");
expect(instance.aiGatewaySlug).toBe("testSlug");
expect(instance.apiBase).toBe("https://api.example.com/");

View file

@ -16,6 +16,8 @@ import {
Chunk,
CompletionOptions,
ILLM,
ILLMInteractionLog,
ILLMLogger,
LLMFullCompletionOptions,
LLMOptions,
ModelCapability,
@ -44,6 +46,7 @@ import {
DEFAULT_MAX_BATCH_SIZE,
DEFAULT_MAX_CHUNK_SIZE,
DEFAULT_MAX_TOKENS,
LLMConfigurationStatuses,
} from "./constants.js";
import {
compileChatMessages,
@ -72,6 +75,8 @@ export function isModelInstaller(provider: any): provider is ModelInstaller {
return provider && typeof provider.installModel === "function";
}
type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
export abstract class BaseLLM implements ILLM {
static providerName: string;
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
@ -121,7 +126,7 @@ export abstract class BaseLLM implements ILLM {
model: string;
title?: string;
systemMessage?: string;
baseChatSystemMessage?: string;
contextLength: number;
maxStopWords?: number | undefined;
completionOptions: CompletionOptions;
@ -129,7 +134,7 @@ export abstract class BaseLLM implements ILLM {
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;
@ -177,14 +182,18 @@ export abstract class BaseLLM implements ILLM {
this.model = options.model;
// Use @continuedev/llm-info package to autodetect certain parameters
const llmInfo = findLlmInfo(this.model);
const modelSearchString =
this.providerName === "continue-proxy"
? this.model?.split("/").pop() || this.model
: this.model;
const llmInfo = findLlmInfo(modelSearchString);
const templateType =
options.template ?? autodetectTemplateType(options.model);
this.title = options.title;
this.uniqueId = options.uniqueId ?? "None";
this.systemMessage = options.systemMessage;
this.baseChatSystemMessage = options.baseChatSystemMessage;
this.contextLength =
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
this.maxStopWords = options.maxStopWords ?? this.maxStopWords;
@ -195,11 +204,11 @@ export abstract class BaseLLM implements ILLM {
options.completionOptions?.maxTokens ??
(llmInfo?.maxCompletionTokens
? Math.min(
llmInfo.maxCompletionTokens,
// Even if the model has a large maxTokens, we don't want to use that every time,
// because it takes away from the context length
this.contextLength / 4,
)
llmInfo.maxCompletionTokens,
// Even if the model has a large maxTokens, we don't want to use that every time,
// because it takes away from the context length
this.contextLength / 4,
)
: DEFAULT_MAX_TOKENS),
};
this.requestOptions = options.requestOptions;
@ -215,7 +224,7 @@ export abstract class BaseLLM implements ILLM {
options.template,
) ??
undefined;
this.writeLog = options.writeLog;
this.logger = options.logger;
this.llmRequestHook = options.llmRequestHook;
this.apiKey = options.apiKey;
@ -255,6 +264,10 @@ export abstract class BaseLLM implements ILLM {
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
}
getConfigurationStatus() {
return LLMConfigurationStatuses.VALID;
}
protected createOpenAiAdapter() {
return constructLlmApi({
provider: this.providerName as any,
@ -271,7 +284,6 @@ export abstract class BaseLLM implements ILLM {
private _compileChatMessages(
options: CompletionOptions,
messages: ChatMessage[],
functions?: any[],
) {
let contextLength = this.contextLength;
if (
@ -282,21 +294,13 @@ export abstract class BaseLLM implements ILLM {
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
}
return compileChatMessages(
options.model,
messages,
return compileChatMessages({
modelName: options.model,
msgs: messages,
contextLength,
options.maxTokens ?? DEFAULT_MAX_TOKENS,
this.supportsImages(),
undefined,
functions,
this.systemMessage,
);
}
private _getSystemMessage(): string | undefined {
// TODO: Merge with config system message
return this.systemMessage;
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
});
}
private _templatePromptLikeMessages(prompt: string): string {
@ -304,52 +308,24 @@ export abstract class BaseLLM implements ILLM {
return prompt;
}
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
// NOTE system message no longer supported here
const systemMessage = this._getSystemMessage();
if (systemMessage) {
msgs.unshift({ role: "system", content: systemMessage });
}
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
return this.templateMessages(msgs);
}
private _compilePromptForLog(
prompt: string,
completionOptions: CompletionOptions,
): string {
const completionOptionsLog = JSON.stringify(
{
contextLength: this.contextLength,
...completionOptions,
},
null,
2,
);
let requestOptionsLog = "";
if (this.requestOptions) {
requestOptionsLog = JSON.stringify(this.requestOptions, null, 2);
}
return (
"##### Completion options #####\n" +
completionOptionsLog +
(requestOptionsLog
? "\n\n##### Request options #####\n" + requestOptionsLog
: "") +
"\n\n##### Prompt #####\n" +
prompt
);
}
private _logTokensGenerated(
private _logEnd(
model: string,
prompt: string,
completion: string,
) {
thinking: string | undefined,
interaction: ILLMInteractionLog | undefined,
error?: any,
): InteractionStatus {
let promptTokens = this.countTokens(prompt);
let generatedTokens = this.countTokens(completion);
let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
void Telemetry.capture(
"tokens_generated",
@ -378,6 +354,37 @@ export abstract class BaseLLM implements ILLM {
generatedTokens: generatedTokens,
},
});
if (error !== undefined) {
if (error === "cancel" || error.name === "AbortError") {
interaction?.logItem({
kind: "cancel",
promptTokens,
generatedTokens,
thinkingTokens,
});
return "cancelled";
} else {
console.log(error);
interaction?.logItem({
kind: "error",
name: error.name,
message: error.message,
promptTokens,
generatedTokens,
thinkingTokens,
});
return "error";
}
} else {
interaction?.logItem({
kind: "success",
promptTokens,
generatedTokens,
thinkingTokens,
});
return "success";
}
}
fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
@ -458,11 +465,7 @@ export abstract class BaseLLM implements ILLM {
throw new Error(message);
}
}
//if e instance of LLMError, rethrow
if (e instanceof LLMError) {
throw e;
}
throw new Error(e.message);
throw e;
}
};
return withExponentialBackoff<Response>(
@ -537,52 +540,89 @@ export abstract class BaseLLM implements ILLM {
): AsyncGenerator<string> {
const { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
let status: InteractionStatus = "in_progress";
const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(
this._compilePromptForLog(fimLog, completionOptions),
);
}
interaction?.logItem({
kind: "startFim",
prefix,
suffix,
options: completionOptions,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, fimLog);
}
}
let completion = "";
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
const stream = this.openaiAdapter.fimStream(
toFimBody(prefix, suffix, completionOptions),
signal,
);
for await (const chunk of stream) {
const result = fromChatCompletionChunk(chunk);
if (result) {
const content = renderChatMessage(result);
completion += content;
yield content;
try {
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
const stream = this.openaiAdapter.fimStream(
toFimBody(prefix, suffix, completionOptions),
signal,
);
for await (const chunk of stream) {
const result = fromChatCompletionChunk(chunk);
if (result) {
const content = renderChatMessage(result);
interaction?.logItem({
kind: "chunk",
chunk: content,
});
completion += content;
yield content;
}
}
} else {
for await (const chunk of this._streamFim(
prefix,
suffix,
signal,
completionOptions,
)) {
interaction?.logItem({
kind: "chunk",
chunk,
});
completion += chunk;
yield chunk;
}
}
} else {
for await (const chunk of this._streamFim(
prefix,
suffix,
signal,
completionOptions,
)) {
completion += chunk;
yield chunk;
status = this._logEnd(
completionOptions.model,
fimLog,
completion,
undefined,
interaction,
);
} catch (e) {
status = this._logEnd(
completionOptions.model,
fimLog,
completion,
undefined,
interaction,
e,
);
throw e;
} finally {
if (status === "in_progress") {
this._logEnd(
completionOptions.model,
fimLog,
completion,
undefined,
interaction,
"cancel",
);
}
}
this._logTokensGenerated(completionOptions.model, fimLog, completion);
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
return {
prompt: fimLog,
completion,
@ -597,6 +637,10 @@ export abstract class BaseLLM implements ILLM {
) {
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
let status: InteractionStatus = "in_progress";
let prompt = pruneRawPromptFromTop(
completionOptions.model,
@ -610,11 +654,11 @@ export abstract class BaseLLM implements ILLM {
}
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
interaction?.logItem({
kind: "startComplete",
prompt,
options: completionOptions,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
@ -642,6 +686,10 @@ export abstract class BaseLLM implements ILLM {
)) {
const content = chunk.choices[0]?.text ?? "";
completion += content;
interaction?.logItem({
kind: "chunk",
chunk: content,
});
yield content;
}
}
@ -652,14 +700,40 @@ export abstract class BaseLLM implements ILLM {
completionOptions,
)) {
completion += chunk;
interaction?.logItem({
kind: "chunk",
chunk,
});
yield chunk;
}
}
status = this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
);
} catch (e) {
status = this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
e,
);
throw e;
} finally {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
if (status === "in_progress") {
this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
"cancel",
);
}
}
@ -678,6 +752,10 @@ export abstract class BaseLLM implements ILLM {
) {
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
let status: InteractionStatus = "in_progress";
let prompt = pruneRawPromptFromTop(
completionOptions.model,
@ -691,34 +769,65 @@ export abstract class BaseLLM implements ILLM {
}
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
interaction?.logItem({
kind: "startComplete",
prompt: prompt,
options: completionOptions,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
let completion: string;
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
const result = await this.openaiAdapter.completionNonStream(
{
...toCompleteBody(prompt, completionOptions),
stream: false,
},
signal,
let completion: string = "";
try {
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
const result = await this.openaiAdapter.completionNonStream(
{
...toCompleteBody(prompt, completionOptions),
stream: false,
},
signal,
);
completion = result.choices[0].text;
} else {
completion = await this._complete(prompt, signal, completionOptions);
}
interaction?.logItem({
kind: "chunk",
chunk: completion,
});
status = this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
);
completion = result.choices[0].text;
} else {
completion = await this._complete(prompt, signal, completionOptions);
}
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
} catch (e) {
status = this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
e,
);
throw e;
} finally {
if (status === "in_progress") {
this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
"cancel",
);
}
}
return completion;
@ -763,6 +872,10 @@ export abstract class BaseLLM implements ILLM {
): AsyncGenerator<ChatMessage, PromptLog> {
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const interaction = logEnabled
? this.logger?.createInteractionLog()
: undefined;
let status: InteractionStatus = "in_progress";
completionOptions = this._modifyCompletionOptions(completionOptions);
@ -772,11 +885,11 @@ export abstract class BaseLLM implements ILLM {
? this.templateMessages(messages)
: this._formatChatMessages(messages);
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
interaction?.logItem({
kind: "startChat",
messages,
options: completionOptions,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
@ -784,7 +897,6 @@ export abstract class BaseLLM implements ILLM {
let thinking = "";
let completion = "";
let citations: null | string[] = null;
try {
if (this.templateMessages) {
@ -794,6 +906,10 @@ export abstract class BaseLLM implements ILLM {
completionOptions,
)) {
completion += chunk;
interaction?.logItem({
kind: "chunk",
chunk: chunk,
});
yield { role: "assistant", content: chunk };
}
} else {
@ -823,15 +939,12 @@ export abstract class BaseLLM implements ILLM {
const result = fromChatCompletionChunk(chunk);
if (result) {
completion += result.content;
interaction?.logItem({
kind: "message",
message: result,
});
yield result;
}
if (
!citations &&
(chunk as any).citations &&
Array.isArray((chunk as any).citations)
) {
citations = (chunk as any).citations;
}
}
}
} else {
@ -840,47 +953,58 @@ export abstract class BaseLLM implements ILLM {
signal,
completionOptions,
)) {
if (chunk.role === "assistant") {
completion += chunk.content;
yield chunk;
} else if (chunk.role === "thinking") {
thinking += chunk.content;
}
if (chunk.role === "thinking") {
thinking += chunk.content;
yield chunk;
}
interaction?.logItem({
kind: "message",
message: chunk,
});
yield chunk;
}
}
}
} catch (error) {
console.log(error);
throw error;
}
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (logEnabled && this.writeLog) {
if (thinking) {
await this.writeLog(`Thinking:\n${thinking}\n\n`);
}
/*
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
and you must include the complete unmodified block back to the API. This is critical
for maintaining the model's reasoning flow and conversation integrity.
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
requests when not using tools, so it's the simplest option to always add to history.
*/
await this.writeLog(`Completion:\n${completion}\n\n`);
if (citations) {
await this.writeLog(
`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`,
status = this._logEnd(
completionOptions.model,
prompt,
completion,
thinking,
interaction,
);
} catch (e) {
status = this._logEnd(
completionOptions.model,
prompt,
completion,
thinking,
interaction,
e,
);
throw e;
} finally {
if (status === "in_progress") {
this._logEnd(
completionOptions.model,
prompt,
completion,
undefined,
interaction,
"cancel",
);
}
}
/*
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
and you must include the complete unmodified block back to the API. This is critical
for maintaining the model's reasoning flow and conversation integrity.
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
requests when not using tools, so it's the simplest option to always add to history.
*/
return {
modelTitle: this.title ?? completionOptions.model,
@ -948,7 +1072,7 @@ export abstract class BaseLLM implements ILLM {
);
}
protected async * _streamComplete(
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
@ -956,7 +1080,7 @@ export abstract class BaseLLM implements ILLM {
throw new Error("Not implemented");
}
protected async * _streamChat(
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,

View file

@ -140,7 +140,9 @@ function testLLM(
},
},
type: "function",
wouldLikeTo: "Say hello",
wouldLikeTo: "say hello",
isCurrently: "saying hello",
hasAlready: "said hello",
readonly: true,
group: "Hello",
},

View file

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

View file

@ -2,8 +2,9 @@ import {
BedrockRuntimeClient,
ContentBlock,
ConverseStreamCommand,
ConverseStreamCommandOutput,
InvokeModelCommand,
Message
Message,
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
@ -11,11 +12,12 @@ import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions
LLMOptions,
} from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
import { getSecureID } from "../utils/getSecureID.js";
interface ModelConfig {
formatPayload: (text: string) => any;
@ -31,6 +33,14 @@ interface ToolUseState {
input: string;
}
/**
* Interface for prompt caching metrics
*/
interface PromptCachingMetrics {
cacheReadInputTokens: number;
cacheWriteInputTokens: number;
}
class Bedrock extends BaseLLM {
static providerName = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
@ -41,8 +51,16 @@ class Bedrock extends BaseLLM {
};
private _currentToolResponse: Partial<ToolUseState> | null = null;
private _promptCachingMetrics: PromptCachingMetrics = {
cacheReadInputTokens: 0,
cacheWriteInputTokens: 0,
};
public requestOptions: { region?: string; credentials?: any; headers?: Record<string, string> };
public requestOptions: {
region?: string;
credentials?: any;
headers?: Record<string, string>;
};
constructor(options: LLMOptions) {
super(options);
@ -108,12 +126,17 @@ class Bedrock extends BaseLLM {
},
);
const input = this._generateConverseInput(messages, { ...options, stream: true });
const input = this._generateConverseInput(messages, {
...options,
stream: true,
});
const command = new ConverseStreamCommand(input);
let response;
let response: ConverseStreamCommandOutput;
try {
response = await client.send(command, { abortSignal: signal });
response = (await client.send(command, {
abortSignal: signal,
})) as ConverseStreamCommandOutput;
} catch (error: unknown) {
console.error(error);
const message = error instanceof Error ? error.message : "Unknown error";
@ -124,51 +147,82 @@ class Bedrock extends BaseLLM {
throw new Error("No stream received from Bedrock API");
}
// Reset cache metrics for new request
this._promptCachingMetrics = {
cacheReadInputTokens: 0,
cacheWriteInputTokens: 0,
};
try {
for await (const chunk of response.stream) {
if (chunk.metadata?.usage) {
console.log(`${JSON.stringify(chunk.metadata.usage)}`);
}
if (chunk.contentBlockDelta?.delta) {
const delta: any = chunk.contentBlockDelta.delta
const delta: any = chunk.contentBlockDelta.delta;
// Handle text content
if (chunk.contentBlockDelta.delta.text) {
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
yield {
role: "assistant",
content: chunk.contentBlockDelta.delta.text,
};
continue;
}
// Handle text content
if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) {
yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent.text };
yield {
role: "thinking",
content: (chunk.contentBlockDelta.delta as any).reasoningContent
.text,
};
continue;
}
// Handle signature for thinking
if (delta.reasoningContent?.signature) {
yield { role: "thinking", content: "", signature: delta.reasoningContent.signature };
yield {
role: "thinking",
content: "",
signature: delta.reasoningContent.signature,
};
continue;
}
// Handle redacted thinking
if (delta.redactedReasoning?.data) {
yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data };
yield {
role: "thinking",
content: "",
redactedThinking: delta.redactedReasoning.data,
};
continue;
}
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
if (
chunk.contentBlockDelta.delta.toolUse?.input &&
this._currentToolResponse
) {
// Append the new input to the existing string
if (this._currentToolResponse.input === undefined) {
this._currentToolResponse.input = "";
}
this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input;
this._currentToolResponse.input +=
chunk.contentBlockDelta.delta.toolUse.input;
continue;
}
}
if (chunk.contentBlockStart?.start) {
const start: any = chunk.contentBlockStart.start
const start: any = chunk.contentBlockStart.start;
if (start.redactedReasoning) {
yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data };
yield {
role: "thinking",
content: "",
redactedThinking: start.redactedReasoning.data,
};
continue;
}
@ -177,7 +231,7 @@ class Bedrock extends BaseLLM {
this._currentToolResponse = {
toolUseId: toolUse.toolUseId,
name: toolUse.name,
input: ""
input: "",
};
}
continue;
@ -188,14 +242,16 @@ class Bedrock extends BaseLLM {
yield {
role: "assistant",
content: "",
toolCalls: [{
id: this._currentToolResponse.toolUseId,
type: "function",
function: {
name: this._currentToolResponse.name,
arguments: this._currentToolResponse.input
}
}],
toolCalls: [
{
id: this._currentToolResponse.toolUseId,
type: "function",
function: {
name: this._currentToolResponse.name,
arguments: this._currentToolResponse.input,
},
},
],
};
this._currentToolResponse = null;
}
@ -207,13 +263,16 @@ class Bedrock extends BaseLLM {
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`);
throw new Error(
`AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
);
}
throw new Error(`Error processing Bedrock stream: ${error.message}`);
}
throw new Error("Error processing Bedrock stream: Unknown error occurred");
throw new Error(
"Error processing Bedrock stream: Unknown error occurred",
);
}
}
/**
@ -226,24 +285,48 @@ class Bedrock extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): any {
const systemMessage = stripImages(
messages.find((m) => m.role === "system")?.content ?? "",
);
const convertedMessages = this._convertMessages(messages);
const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
const shouldCacheSystemMessage =
!!systemMessage && this.cacheBehavior?.cacheSystemMessage;
const enablePromptCaching =
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
// Add header for prompt caching
if (enablePromptCaching) {
this.requestOptions.headers = {
...this.requestOptions.headers,
"x-amzn-bedrock-enablepromptcaching": "true",
};
}
const supportsTools =
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
return {
modelId: options.model,
messages: convertedMessages,
system: this.systemMessage ? [{ text: this.systemMessage }] : undefined,
toolConfig: supportsTools && options.tools ? {
tools: options.tools.map(tool => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters
system: systemMessage
? shouldCacheSystemMessage
? [{ text: systemMessage }, { cachePoint: { type: "default" } }]
: [{ text: systemMessage }]
: undefined,
toolConfig:
supportsTools && options.tools
? {
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
}
}
}))
} : undefined,
: undefined,
inferenceConfig: {
maxTokens: options.maxTokens,
temperature: options.temperature,
@ -261,20 +344,29 @@ class Bedrock extends BaseLLM {
.slice(0, 4),
},
additionalModelRequestFields: {
"thinking": options.reasoning ? {
"type": "enabled",
"budget_tokens": options.reasoningBudgetTokens
} : undefined,
}
thinking: options.reasoning
? {
type: "enabled",
budget_tokens: options.reasoningBudgetTokens,
}
: undefined,
},
};
}
private _convertMessage(message: ChatMessage): Message | null {
private _convertMessage(
message: ChatMessage,
addCaching: boolean = false,
): Message | null {
// Handle system messages explicitly
if (message.role === "system") {
return null;
}
const cachePoint = addCaching
? { cachePoint: { type: "default" } }
: undefined;
// Tool response handling
if (message.role === "tool") {
return {
@ -285,12 +377,12 @@ class Bedrock extends BaseLLM {
toolUseId: message.toolCallId,
content: [
{
text: message.content || ""
}
]
}
}
]
text: message.content || "",
},
],
},
},
],
};
}
@ -303,8 +395,8 @@ class Bedrock extends BaseLLM {
toolUseId: toolCall.id,
name: toolCall.function?.name,
input: JSON.parse(toolCall.function?.arguments || "{}"),
}
}))
},
})),
};
}
@ -312,84 +404,117 @@ class Bedrock extends BaseLLM {
if (message.redactedThinking) {
const content: ContentBlock.ReasoningContentMember = {
reasoningContent: {
redactedContent: new Uint8Array(Buffer.from(message.redactedThinking))
}
redactedContent: new Uint8Array(
Buffer.from(message.redactedThinking),
),
},
};
return {
role: "assistant",
content: [content]
content: [content],
};
} else {
const content: ContentBlock.ReasoningContentMember = {
reasoningContent: {
reasoningText: {
text: (message.content as string) || "",
signature: message.signature
}
}
signature: message.signature,
},
},
};
return {
role: "assistant",
content: [content]
content: [content],
};
}
}
// Standard text message
if (typeof message.content === "string") {
if (addCaching) {
message.content += getSecureID();
}
const content: any[] = [{ text: message.content }];
if (addCaching) {
content.push({ cachePoint: { type: "default" } });
}
return {
role: message.role,
content: [{ text: message.content }]
content,
};
}
// Improved multimodal content handling
if (Array.isArray(message.content)) {
const content: any[] = [];
// Process all parts first
message.content.forEach((part) => {
if (part.type === "text") {
if (addCaching) {
part.text += getSecureID();
}
content.push({ text: part.text });
} else if (part.type === "imageUrl" && part.imageUrl) {
try {
const [mimeType, base64Data] = part.imageUrl.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
content.push({
image: {
format,
source: {
bytes: Buffer.from(base64Data, "base64"),
},
},
});
} catch (error) {
console.warn(`Failed to process image: ${error}`);
}
}
});
// Add cache point as a separate block at the end if needed
if (addCaching && content.length > 0) {
content.push({ cachePoint: { type: "default" } });
}
return {
role: message.role,
content: message.content.map(part => {
if (part.type === "text") {
return { text: part.text };
}
if (part.type === "imageUrl" && part.imageUrl) {
try {
const [mimeType, base64Data] = part.imageUrl.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
return {
image: {
format,
source: {
bytes: Buffer.from(base64Data, "base64")
}
}
};
} catch (error) {
console.warn(`Failed to process image: ${error}`);
return null;
}
}
return null;
}).filter(Boolean)
content,
} as Message;
}
return null;
}
private _convertMessages(messages: ChatMessage[]): any[] {
const filteredmessages = messages.filter(
(m) => m.role !== "system" && !!m.content,
);
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1)
.slice(-2);
const converted = filteredmessages
.map((message, filteredMsgIdx) => {
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
const addCaching =
this.cacheBehavior?.cacheConversation &&
lastTwoUserMsgIndices.includes(filteredMsgIdx);
const converted = messages
.map((message) => {
try {
return this._convertMessage(message);
return this._convertMessage(message, addCaching);
} catch (error) {
console.error(`Failed to convert message: ${error}`);
return null;
}
})
.filter(Boolean);
return converted;
return converted;
}
private async _getCredentials() {
@ -453,7 +578,6 @@ class Bedrock extends BaseLLM {
return modelConfig.extractEmbeddings(responseBody);
}
private _getModelConfig() {
const modelConfigs: { [key: string]: ModelConfig } = {
cohere: {
@ -491,7 +615,11 @@ class Bedrock extends BaseLLM {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
// Base payload for both models
@ -530,11 +658,15 @@ class Bedrock extends BaseLLM {
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`);
throw new Error(
`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
);
}
throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
}
throw new Error("Error in BedrockReranker.rerank: Unknown error occurred");
throw new Error(
"Error in BedrockReranker.rerank: Unknown error occurred",
);
}
}
}

View file

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

197
core/llm/llms/Docker.ts Normal file
View file

@ -0,0 +1,197 @@
import { spawn } from "child_process";
import { LLMOptions, ModelInstaller } from "../../index.js";
import OpenAI from "./OpenAI.js";
/**
* Docker Model Runner provider
*
* Integrates with Docker Desktop's Model Runner feature (currently in beta)
* that allows running local AI models through Docker.
*
* Docker Model Runner provides an OpenAI-compatible API endpoint, making it
* easy to integrate with existing OpenAI-compatible code.
*
* More information at: https://docs.docker.com/desktop/features/model-runner/
*/
class Docker extends OpenAI implements ModelInstaller {
static providerName = "docker";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:12434/engines/v1",
model: "gemma3-4B-F4", // Default model
};
private modelMap: Record<string, string> = {
// Map of "continue model name" to Docker model name
// Models can be pulled using: docker model pull <model_name>
"llama3.3-70b": "ai/llama3.3:70B-Q4_K_M",
"smollm2-360M-F4": "ai/smollm2:360M-Q4_K_M",
"smollm2-360M-F16": "ai/ai/smollm2:360M-F16",
"qwen2.5-7B-F16": "ai/qwen2.5:7B-F16",
"qwen2.5-7B-F4": "ai/qwen2.5:7B-Q4_K_M",
"phi4-14B-F16": "ai/phi4:14B-F16",
"phi4-14B-F4": "ai/phi4:14B-Q4_K_M",
"mistral-7B-F16": "ai/mistral:7B-F16",
"mistral-7B-F4": "ai/mistral:7B-Q4_K_M",
"mistral-nemo-12B": "ai/mistral-nemo:12B-Q4_K_M",
"gemma3-4B-F16": "ai/gemma3:4B-F16",
"gemma3-4B-F4": "ai/gemma3:4B-Q4_K_M",
"llama3.2-3B-F16": "ai/llama3.2:3B-F16",
"llama3.2-3B-F4": "ai/llama3.2:3B-Q4_K_M",
"llama3.2-1B-F16": "ai/llama3.2:1B-F16",
"llama3.2-1B-F8": "ai/llama3.2:1B-Q8_0",
"qwq-32B-F16": "ai/qwq:32B-F16",
"qwq-32B-F4": "ai/qwq:32B-Q4_K_M",
"deepseek-r1-distill-llama-70B-F4":
"ai/deepseek-r1-distill-llama:70B-Q4_K_M",
"deepseek-r1-distill-llama-8B-F16": "ai/deepseek-r1-distill-llama:8B-F16",
"deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M",
};
constructor(options: LLMOptions) {
super(options);
// Handle model name mapping
if (this.model && this.modelMap[this.model]) {
this.model = this.modelMap[this.model];
}
// Check if Docker Model Runner is active and enable it if needed
this.ensureModelRunnerEnabled();
}
/**
* Checks if Docker Model Runner is running at the expected port
* and enables it if not running
*/
private async ensureModelRunnerEnabled(): Promise<void> {
try {
// Check if the Model Runner service is running on the expected port
const isRunning = await this.isPortBound(12434);
if (!isRunning) {
console.log(
"Docker Model Runner not detected. Attempting to enable it...",
);
await this.executeDockerCommand([
"desktop",
"enable",
"model-runner",
"--tcp",
"12434",
]);
console.log("Docker Model Runner has been enabled on port 12434");
}
} catch (error) {
console.warn("Failed to enable Docker Model Runner:", error);
}
}
/**
* Checks if a port is currently bound/in use
*/
private async isPortBound(port: number): Promise<boolean> {
try {
await this.fetch(`http://localhost:${port}`, {
method: "HEAD",
signal: AbortSignal.timeout(1000),
});
return true;
} catch (e) {
return false;
}
}
private async executeDockerCommand(
args: string[],
signal?: AbortSignal,
): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
const proc = spawn("docker", args, { shell: true });
let stdout = "";
let stderr = "";
proc.stdout.on("data", (data) => {
stdout += data.toString();
});
proc.stderr.on("data", (data) => {
stderr += data.toString();
});
proc.on("close", (code) => {
if (code === 0) {
resolve({ stdout, stderr });
} else {
reject(
new Error(`Docker command failed with code ${code}: ${stderr}`),
);
}
});
if (signal) {
signal.addEventListener("abort", () => {
proc.kill();
reject(new Error("Docker command was aborted"));
});
}
});
}
async listModels(): Promise<string[]> {
try {
// Execute docker model ls and parse the output
const { stdout } = await this.executeDockerCommand([
"model",
"ls",
"--format",
"{{.Repository}}/{{.Tag}}",
]);
return stdout
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
} catch (error) {
console.error("Failed to list Docker models:", error);
return Object.values(this.modelMap);
}
}
async installModel(
modelName: string,
signal: AbortSignal,
progressReporter?: (task: string, increment: number, total: number) => void,
): Promise<any> {
const targetModel = this.modelMap[modelName] || modelName;
try {
// Report starting the installation
progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100);
// Pull the model
const { stdout, stderr } = await this.executeDockerCommand(
["model", "pull", targetModel],
signal,
);
// Report completion
progressReporter?.(
`Docker model ${targetModel} installed successfully`,
100,
100,
);
return { success: true, stdout, stderr };
} catch (error) {
console.error(`Failed to install Docker model ${targetModel}:`, error);
// Fix: Type check the error before accessing message property
const errorMessage =
error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to install Docker model ${targetModel}: ${errorMessage}`,
);
}
}
}
export default Docker;

View file

@ -1,22 +1,25 @@
import { v4 as uuidv4 } from "uuid";
import {
AssistantChatMessage,
ChatMessage,
CompletionOptions,
LLMOptions,
MessagePart,
TextMessagePart,
ToolCallDelta,
} from "../../index.js";
import { findLast } from "../../util/findLast.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
import {
GeminiChatContent,
GeminiChatContentPart,
GeminiChatRequestBody,
GeminiChatResponse,
GeminiGenerationConfig,
GeminiToolFunctionDeclaration,
} from "./gemini-types.js";
convertContinueToolToGeminiFunction,
} from "./gemini-types";
class Gemini extends BaseLLM {
static providerName = "gemini";
@ -69,20 +72,84 @@ class Gemini extends BaseLLM {
}
}
/**
* Removes the system message and merges it with the next user message if present.
* @param messages Array of chat messages
* @returns Modified array with system message merged into user message if applicable
*/
public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] {
// should be public for use within VertexAI
const msgs = [...messages];
// If no messages or first message isn't system, return copy of original messages
if (messages.length === 0 || messages[0]?.role !== "system") {
return [...messages];
}
if (msgs[0]?.role === "system") {
const sysMsg = msgs.shift()?.content;
// @ts-ignore
if (msgs[0]?.role === "user") {
// @ts-ignore
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
// Extract system message
const systemMessage: ChatMessage = messages[0];
// Extract system content based on its type
let systemContent = "";
if (typeof systemMessage.content === "string") {
systemContent = systemMessage.content;
} else if (Array.isArray(systemMessage.content)) {
const contentArray: Array<MessagePart> =
systemMessage.content as Array<MessagePart>;
const concatenatedText = contentArray
.filter((part): part is TextMessagePart => part.type === "text")
.map((part) => part.text)
.join(" ");
systemContent = concatenatedText ? concatenatedText : "";
} else if (
systemMessage.content &&
typeof systemMessage.content === "object"
) {
const typedContent = systemMessage.content as TextMessagePart;
systemContent = typedContent?.text || "";
}
// Create new array without the system message
const remainingMessages: ChatMessage[] = messages.slice(1);
// Check if there's a user message to merge with
if (remainingMessages.length > 0 && remainingMessages[0].role === "user") {
const userMessage: ChatMessage = remainingMessages[0];
const prefix = `System message - follow these instructions in every response: ${systemContent}\n\n---\n\n`;
// Merge based on user content type
if (typeof userMessage.content === "string") {
userMessage.content = prefix + userMessage.content;
} else if (Array.isArray(userMessage.content)) {
const contentArray: Array<MessagePart> =
userMessage.content as Array<MessagePart>;
const textPart = contentArray.find((part) => part.type === "text") as
| TextMessagePart
| undefined;
if (textPart) {
textPart.text = prefix + textPart.text;
} else {
userMessage.content.push({
type: "text",
text: prefix,
} as TextMessagePart);
}
} else if (
userMessage.content &&
typeof userMessage.content === "object"
) {
const typedContent = userMessage.content as TextMessagePart;
userMessage.content = [
{
type: "text",
text: prefix + (typedContent.text || ""),
} as TextMessagePart,
];
}
}
return msgs;
return remainingMessages;
}
protected async *_streamChat(
@ -90,14 +157,8 @@ class Gemini extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
// Ensure this.apiBase is used if available, otherwise use default
const apiBase =
this.apiBase ||
Gemini.defaultOptions?.apiBase ||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
const isV1API = apiBase.includes("/v1/");
const isV1API = this.apiBase?.includes("/v1/");
// Conditionally apply removeSystemMessage
const convertedMsgs = isV1API
? this.removeSystemMessage(messages)
: messages;
@ -139,20 +200,27 @@ class Gemini extends BaseLLM {
options: CompletionOptions,
isV1API: boolean,
): GeminiChatRequestBody {
const toolCallIdToNameMap = new Map<string, string>();
messages.forEach((msg) => {
if (msg.role === "assistant" && msg.toolCalls) {
msg.toolCalls.forEach((call) => {
if (call.id && call.function?.name) {
toolCallIdToNameMap.set(call.id, call.function.name);
}
});
}
});
const systemMessage = messages.find(
(msg) => msg.role === "system",
)?.content;
const body: GeminiChatRequestBody = {
contents: messages
.filter((msg) => !(msg.role === "system" && isV1API))
.map((msg) => {
if (msg.role === "tool") {
let fn_name = "";
const lastToolCallMessage = findLast(
messages,
(msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name,
) as AssistantChatMessage;
if (lastToolCallMessage) {
fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!;
}
if (!fn_name) {
let functionName = toolCallIdToNameMap.get(msg.toolCallId);
if (!functionName) {
console.warn(
"Sending tool call response for unidentified tool call",
);
@ -162,7 +230,8 @@ class Gemini extends BaseLLM {
parts: [
{
functionResponse: {
name: fn_name || "unknown",
id: msg.toolCallId,
name: functionName || "unknown",
response: {
output: msg.content, // "output" key is opinionated - not all functions will output objects
},
@ -171,28 +240,35 @@ class Gemini extends BaseLLM {
],
};
}
const assistantMsg = {
role:
msg.role === "assistant" ? ("model" as const) : ("user" as const),
if (msg.role === "assistant") {
const assistantMsg: GeminiChatContent = {
role: "model",
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this.continuePartToGeminiPart),
};
if (msg.toolCalls) {
msg.toolCalls.forEach((toolCall) => {
if (toolCall.function?.name && toolCall.function?.arguments) {
assistantMsg.parts.push({
functionCall: {
name: toolCall.function.name,
args: JSON.parse(toolCall.function.arguments),
},
});
}
});
}
return assistantMsg;
}
return {
role: "user",
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this.continuePartToGeminiPart),
};
if (msg.role === "assistant" && msg.toolCalls) {
msg.toolCalls.forEach((toolCall) => {
if (toolCall.function?.name && toolCall.function?.arguments) {
assistantMsg.parts.push({
functionCall: {
name: toolCall.function.name,
args: JSON.parse(toolCall.function.arguments),
},
});
}
});
}
return assistantMsg;
}),
};
if (options) {
@ -201,8 +277,10 @@ class Gemini extends BaseLLM {
// https://ai.google.dev/gemini-api/docs/api-versions
if (!isV1API) {
if (this.systemMessage) {
body.systemInstruction = { parts: [{ text: this.systemMessage }] };
if (systemMessage) {
body.systemInstruction = {
parts: [{ text: stripImages(systemMessage) }],
};
}
// Convert and add tools if present
if (options.tools?.length) {
@ -211,77 +289,12 @@ class Gemini extends BaseLLM {
// Same difference
const functions: GeminiToolFunctionDeclaration[] = [];
options.tools.forEach((tool) => {
if (tool.function.description && tool.function.name) {
const fn: GeminiToolFunctionDeclaration = {
description: tool.function.description,
name: tool.function.name,
};
if (
tool.function.parameters &&
"type" in tool.function.parameters
// && typeof tool.function.parameters.type === "string"
) {
// const paramType = "TYPE_UNSPECIFIED"
// | "STRING"
// | "NUMBER"
// | "INTEGER"
// | "BOOLEAN"
// | "ARRAY"
// | "OBJECT"
if (tool.function.parameters.type === "object") {
// Gemini can't take an empty object
// So if empty object param is present just don't add parameters
if (
JSON.stringify(tool.function.parameters.properties) === "{}"
) {
functions.push(fn);
return;
}
}
// Helper function to recursively clean JSON Schema objects
const cleanJsonSchema = (schema: any): any => {
if (!schema || typeof schema !== "object") return schema;
if (Array.isArray(schema)) {
return schema.map(cleanJsonSchema);
}
const {
$schema,
additionalProperties,
default: defaultValue,
...rest
} = schema;
// Recursively clean nested properties
if (rest.properties) {
rest.properties = Object.entries(rest.properties).reduce(
(acc, [key, value]) => ({
...acc,
[key]: cleanJsonSchema(value),
}),
{},
);
}
// Clean items in arrays
if (rest.items) {
rest.items = cleanJsonSchema(rest.items);
}
return rest;
};
// Clean the parameters and convert type to uppercase
const cleanedParams = cleanJsonSchema(tool.function.parameters);
fn.parameters = {
...cleanedParams,
type: tool.function.parameters.type.toUpperCase(),
};
}
functions.push(fn);
try {
functions.push(convertContinueToolToGeminiFunction(tool));
} catch (e) {
console.warn(
`Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`,
);
}
});
if (functions.length) {
@ -332,75 +345,39 @@ class Gemini extends BaseLLM {
// Check for existence of each level before accessing the final 'text' property
const content = data?.candidates?.[0]?.content;
if (content) {
const supportedParts: MessagePart[] = [];
const textParts: MessagePart[] = [];
const toolCalls: ToolCallDelta[] = [];
// Process all parts first to maintain order
const processedParts: Array<{
type: "content" | "tool" | "toolCall";
data: any;
}> = [];
for (const part of content.parts) {
if ("text" in part) {
supportedParts.push({ type: "text", text: part.text });
} else if ("inlineData" in part) {
supportedParts.push({
type: "imageUrl",
imageUrl: {
url: `data:image/jpeg;base64,${part.inlineData.data}`,
},
});
textParts.push({ type: "text", text: part.text });
} else if ("functionCall" in part) {
// Queue function call
processedParts.push({
type: "toolCall",
data: {
type: "function",
id: "", // Not supported by gemini
function: {
name: part.functionCall.name,
arguments:
typeof part.functionCall.args === "string"
? part.functionCall.args
: JSON.stringify(part.functionCall.args),
},
},
});
} else if ("functionResponse" in part) {
// Queue function response
processedParts.push({
type: "tool",
data: {
role: "tool",
content: part.functionResponse.response.output as string,
toolCallId: part.functionResponse.name,
toolCalls.push({
type: "function",
id: part.functionCall.id ?? uuidv4(),
function: {
name: part.functionCall.name,
arguments:
typeof part.functionCall.args === "string"
? part.functionCall.args
: JSON.stringify(part.functionCall.args),
},
});
} else {
// Note: function responses shouldn't be streamed, images not supported
console.warn("Unsupported gemini part type received", part);
}
}
// If we have supported content parts, yield them first
if (supportedParts.length) {
yield {
role: "assistant",
content: supportedParts,
};
const assistantMessage: AssistantChatMessage = {
role: "assistant",
content: textParts.length ? textParts : "",
};
if (toolCalls.length > 0) {
assistantMessage.toolCalls = toolCalls;
}
// Then process tool calls and responses in order
for (const part of processedParts) {
if (part.type === "toolCall") {
yield {
role: "assistant",
content: "",
toolCalls: [part.data],
};
} else if (part.type === "tool") {
yield part.data;
}
if (textParts.length || toolCalls.length) {
yield assistantMessage;
}
} else {
// Handle the case where the expected data structure is not found
@ -424,10 +401,8 @@ class Gemini extends BaseLLM {
`models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
this.apiBase,
);
// This feels hacky to repeat code from above function but was the quickest
// way to ensure system message re-formatting isn't done if user has specified v1
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
const isV1API = apiBase.includes("/v1/");
const isV1API = !!this.apiBase?.includes("/v1/");
// Convert chat messages to contents
const body = this.prepareBody(messages, options, isV1API);

View file

@ -0,0 +1,70 @@
import { CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import OpenAI from "./OpenAI.js";
/**
* Inception Labs provider
*
* Integrates with Inception Labs' OpenAI-compatible API endpoints.
* Provides access to Mercury models for autocomplete and other tasks.
*
* Different models use different API endpoints:
* - mercury-editor-mini-experimental: zaragoza.api.inceptionlabs.ai
* - mercury-editor-small-experimental: copenhagen.api.inceptionlabs.ai
*
* More information at: https://docs.inceptionlabs.ai/
*/
class Inception extends OpenAI {
static providerName = "inception";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://copenhagen.api.inceptionlabs.ai/v1/",
model: "mercury-editor-small-experimental",
completionOptions: {
temperature: 0.0,
maxTokens: 150,
presencePenalty: 1.5,
stop: ["\n\n", "\n \n", "<|endoftext|>"],
model: "mercury-editor-small-experimental", // Added model to fix TypeScript error
},
};
supportsFim(): boolean {
return true;
}
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("completions", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
prompt: prefix,
suffix,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal,
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].text;
}
}
}
export default Inception;

View file

@ -35,7 +35,7 @@ class LlamaCpp extends BaseLLM {
...this.requestOptions?.headers,
};
const resp = await this.fetch(new URL("completion", this.apiBase), {
const resp = await this.fetch(new URL("completions", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify({

View file

@ -102,7 +102,12 @@ class OpenAI extends BaseLLM {
}
protected supportsPrediction(model: string): boolean {
const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"];
const SUPPORTED_MODELS = [
"gpt-4o-mini",
"gpt-4o",
"mistral-large",
"Fast-Apply",
];
return SUPPORTED_MODELS.some((m) => model.includes(m));
}
@ -288,7 +293,10 @@ class OpenAI extends BaseLLM {
// To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs
// In practice, setting this to true and asking for multiple tool calls
// leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}'
body.parallel_tool_calls = false;
// o3 does not support this
if (!body.model.startsWith("o3")) {
body.parallel_tool_calls = false;
}
}
return body;

View file

@ -1,4 +1,5 @@
import { LLMOptions } from "../..";
import { LLMConfigurationStatuses } from "../constants";
import { LlmApiRequestType } from "../openaiTypeConverters";
import OpenAI from "./OpenAI";
@ -9,4 +10,16 @@ export class Relace extends OpenAI {
apiBase: "https://instantapply.endpoint.relace.run/v1/",
};
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"];
protected supportsPrediction(model: string): boolean {
return true;
}
getConfigurationStatus() {
if (!this.apiKey) {
return LLMConfigurationStatuses.MISSING_API_KEY;
}
return LLMConfigurationStatuses.VALID;
}
}

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