Merge pull request #2113 from continuedev/v0.9.199-vscode-hotfix

V0.9.199 vscode hotfix
This commit is contained in:
Nate Sesti 2024-08-27 12:31:18 -07:00 • committed by GitHub
commit 110ee4cc72
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
208 changed files with 6190 additions and 3139 deletions

View file

@ -9,8 +9,8 @@
## Screenshots
[ "For visual changes, include screenshots." ]
[ For visual changes, include screenshots. ]
## Testing
[ For new or modified features, provide testing instructions. ]
[ For new or modified features, provide step-by-step testing instructions to validate the intended behavior of the change. ]

View file

@ -7,7 +7,7 @@ When merging to `preview`:
- the VS Code extension along with Rust extension is built and uploaded as an artifact
- all of the artifacts are downloaded and pushed to the store/registry all at once, as full releases.
- the version is bumped and this change is commited to preview
- in the future, the Intellij extension will be built and uploaded to the marketplace here
- in the future, the JetBrains extension will be built and uploaded to the marketplace here
## main
@ -16,4 +16,4 @@ When merging to `main`:
- the VS Code extension along with Rust extension is built and uploaded as an artifact
- all of the artifacts are downloaded and pushed to the store/registry all at once, as full releases.
- the version is bumped and this change is commited to main
- in the future, the Intellij extension will be built and uploaded to the marketplace here
- in the future, the JetBrains extension will be built and uploaded to the marketplace here

92
.github/workflows/dev_pr.yaml vendored Normal file
View file

@ -0,0 +1,92 @@
name: Dev PR checks
on:
pull_request:
branches:
- dev
jobs:
tsc-check:
runs-on: ubuntu-latest
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Cache extension node_modules
uses: actions/cache@v3
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Cache core node_modules
uses: actions/cache@v3
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache gui node_modules
uses: actions/cache@v3
with:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Cache binary node_modules
uses: actions/cache@v3
with:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: extensions/vscode install
run: |
cd extensions/vscode
npm ci
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: core install
run: |
cd core
npm ci
- name: gui install
run: |
cd gui
npm ci
- name: binary install
run: |
cd binary
npm ci
- name: extensions/vscode checks
run: |
cd extensions/vscode
npx tsc --noEmit
- name: core checks
run: |
cd core
npm ci
npx tsc --noEmit
npm run lint
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
- name: gui checks
run: |
cd gui
npx tsc --noEmit
- name: binary checks
run: |
cd binary
npx tsc --noEmit

View file

@ -1,476 +0,0 @@
# GitHub Actions Workflow is created for testing and preparing the plugin release in the following steps:
# - Validate Gradle Wrapper.
# - Run 'test' and 'verifyPlugin' tasks.
# - Run Qodana inspections.
# - Run the 'buildPlugin' task and prepare artifact for further tests.
# - Run the 'runPluginVerifier' task.
# - Create a draft release.
#
# The workflow is triggered on push and pull_request events.
#
# GitHub Actions reference: https://help.github.com/en/actions
#
## JBIJPPTPL
name: Build
# on:
# # Trigger the workflow on pushes to only the 'main' branch (this avoids duplicate checks being run e.g., for dependabot pull requests)
# push:
# branches: [main, preview]
# Trigger the workflow on any pull request
# pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
defaults:
run:
working-directory: ./extensions/intellij
jobs:
# Prepare environment and build the plugin
build:
name: Build
runs-on: macos-latest
outputs:
version: ${{ steps.properties.outputs.version }}
changelog: ${{ steps.properties.outputs.changelog }}
pluginVerifierHomeDir: ${{ steps.properties.outputs.pluginVerifierHomeDir }}
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
# Validate wrapper
- name: Gradle Wrapper Validation
uses: gradle/actions/wrapper-validation@v3
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
# Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
with:
gradle-home-cache-cleanup: true
# Set environment variables
- name: Export Properties
id: properties
shell: bash
run: |
PROPERTIES="$(./gradlew properties --console=plain -q)"
VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')"
# CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)"
CHANGELOG=""
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT
echo "changelog<<EOF" >> $GITHUB_OUTPUT
echo "$CHANGELOG" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier
# Setup Node.js
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
# Cache node_modules
- name: Cache core node_modules
uses: actions/cache@v3
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache binary node_modules
uses: actions/cache@v3
with:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: Cache gui node_modules
uses: actions/cache@v3
with:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
# npm install core
- name: Install core node_modules
run: |
cd ../../core
npm ci
# npm install binary
- name: Install core node_modules
run: |
cd ../../binary
npm ci
# npm install gui
- name: Install gui node_modules
run: |
cd ../../gui
npm ci
# build gui
- name: Build gui
run: |
cd ../../gui
npm run build
# Run prepackage.js script
- name: Run prepackage script
run: |
cd ../../extensions/vscode
npm ci
npm run prepackage
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
# Build binaries
- name: Build the binaries
run: |
cd ../../binary
npm run build
# Build plugin
- name: Build plugin
run: ./gradlew buildPlugin
# Prepare plugin archive content for creating artifact
- name: Prepare Plugin Artifact
id: artifact
shell: bash
run: |
cd ../../extensions/intellij/build/distributions
FILENAME=`ls *.zip`
unzip "$FILENAME" -d content
echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT
# Store already-built plugin as an artifact for downloading
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: ${{ steps.artifact.outputs.filename }}
path: ./extensions/intellij/build/distributions/content/*/*
# Upload binaries as artifacts
- name: Upload artifact (darwin-arm64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-darwin-arm64
path: ./binary/bin/darwin-arm64/
- name: Upload artifact (darwin-x64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-darwin-x64
path: ./binary/bin/darwin-x64/
- name: Upload artifact (win32-x64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-win32-x64
path: ./binary/bin/win32-x64/
- name: Upload artifact (linux-arm64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-linux-arm64
path: ./binary/bin/linux-arm64/
- name: Upload artifact (linux-x64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-linux-x64
path: ./binary/bin/linux-x64/
test-binaries:
needs: build
strategy:
matrix:
include:
- os: windows-latest
platform: win32
arch: x64
npm_config_arch: x64
- os: ubuntu-latest
platform: linux
arch: x64
npm_config_arch: x64
# arm64 not actually supported by GitHub
# - os: ubuntu-latest
# platform: linux
# arch: arm64
# npm_config_arch: arm64
- os: macos-12
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-latest
platform: darwin
arch: arm64
npm_config_arch: arm64
runs-on: ${{ matrix.os }}
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Cache core node_modules
uses: actions/cache@v3
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache binary node_modules
uses: actions/cache@v3
with:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: Install Core Dependencies
run: |
cd ../../core
npm ci
- name: Install Binary Dependencies
run: |
cd ../../binary
npm ci
# Download the binary artifact
- name: Download binary artifact
uses: actions/download-artifact@v4
with:
name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }}
path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/
# Set execute permissions for the binary (non-Windows)
- name: Set execute permissions
run: |
cd ../../binary/bin/${{ matrix.platform }}-${{ matrix.arch }}
chmod +x continue-binary
chmod +x node_sqlite3.node
chmod +x index.node
chmod +x esbuild
if: ${{ matrix.platform }} != 'win32'
- name: Copy node_sqlite3.node to necessary location
run: |
cd ../../binary
mkdir build
cp ./bin/${{ matrix.platform }}-${{ matrix.arch }}/node_sqlite3.node ./build/node_sqlite3.node
# Run tests for binary
- name: Run binary tests
run: |
cd ../../binary
npm run test
- name: Upload logs
if: ${{ always() }}
uses: actions/upload-artifact@v2
with:
name: core-logs-${{ matrix.platform }}-${{ matrix.arch }}
path: binary/.continue/logs/core.log
# Run tests and upload a code coverage report
test:
name: Test
needs: [build]
runs-on: ubuntu-latest
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
# Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
with:
gradle-home-cache-cleanup: true
# Run tests
- name: Run Tests
run: ./gradlew check
# Collect Tests Result of failed tests
- name: Collect Tests Result
if: ${{ failure() }}
uses: actions/upload-artifact@v4
with:
name: tests-result
path: ${{ github.workspace }}/extensions/intellij/build/reports/tests
# Upload the Kover report to CodeCov
# - name: Upload Code Coverage Report
# uses: codecov/codecov-action@v4
# with:
# files: ${{ github.workspace }}/build/reports/kover/report.xml
# Run Qodana inspections and provide report
inspectCode:
if: false
name: Inspect code
needs: [build]
runs-on: ubuntu-latest
permissions:
contents: write
checks: write
pull-requests: write
steps:
# Free GitHub Actions Environment Disk Space
- name: Maximize Build Space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: false
large-packages: false
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2024.1.5
with:
cache-default-branch-only: true
# Run plugin structure verification along with IntelliJ Plugin Verifier
verify:
name: Verify plugin
needs: [build]
runs-on: ubuntu-latest
steps:
# Free GitHub Actions Environment Disk Space
- name: Maximize Build Space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: false
large-packages: false
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
# Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
with:
gradle-home-cache-cleanup: true
# Cache Plugin Verifier IDEs
- name: Setup Plugin Verifier IDEs Cache
uses: actions/cache@v4
with:
path: ${{ needs.build.outputs.pluginVerifierHomeDir }}/ides
key: plugin-verifier-${{ hashFiles('build/listProductsReleases.txt') }}
# Run Verify Plugin task and IntelliJ Plugin Verifier tool
- name: Run Plugin Verification tasks
run: ./gradlew runPluginVerifier -Dplugin.verifier.home.dir=${{ needs.build.outputs.pluginVerifierHomeDir }}
# Collect Plugin Verifier Result
- name: Collect Plugin Verifier Result
if: ${{ always() }}
uses: actions/upload-artifact@v4
with:
name: pluginVerifier-result
path: ${{ github.workspace }}/build/reports/pluginVerifier
# Prepare a draft release for GitHub Releases page for the manual verification
# If accepted and published, release workflow would be triggered
releaseDraft:
name: Release draft
if: github.event_name != 'pull_request'
needs: [build, test, test-binaries, verify]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
# Check out current repository
- name: Fetch Sources
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: Tag the repository
id: tag
run: |
# See https://docs.github.com/en/get-started/using-git/dealing-with-special-characters-in-branch-and-tag-names
TAG=v${{ needs.build.outputs.version }}-jetbrains
echo "$TAG"
echo "tag=$TAG" >> $GITHUB_OUTPUT
git tag -a $TAG -m "Published version $TAG" ${GITHUB_SHA}
git push origin $TAG
# Remove old release drafts by using the curl request for the available releases with a draft flag
- name: Remove Old Release Drafts
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh api repos/{owner}/{repo}/releases \
--jq '.[] | select(.draft == true) | .id' \
| xargs -I '{}' gh api -X DELETE repos/{owner}/{repo}/releases/{}
# Create a new release draft which is not publicly visible and requires manual acceptance
- name: Create Release Draft
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create "${{ steps.tag.outputs.tag }}" \
--draft \
--title "v${{ needs.build.outputs.version }}-jetbrains" \
--notes "$(cat << 'EOM'
${{ needs.build.outputs.changelog }}
EOM
)"
# Download the Gradle build artifact
- name: Download Gradle build artifact
uses: actions/download-artifact@v4
with:
name: ${{ needs.build.outputs.filename }}
path: ./artifacts

View file

@ -2,14 +2,19 @@
# Running the publishPlugin task requires all following secrets to be provided: PUBLISH_TOKEN, PRIVATE_KEY, PRIVATE_KEY_PASSWORD, CERTIFICATE_CHAIN.
# See https://plugins.jetbrains.com/docs/intellij/plugin-signing.html for more information.
name: Release
# on:
# release:
# types: [prereleased, released]
name: JetBrains Release
on:
release:
types: [prereleased]
defaults:
run:
working-directory: ./extensions/intellij
working-directory: extensions/intellij
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
check_release_name:
@ -18,19 +23,20 @@ jobs:
should_run: ${{ steps.check.outputs.should_run }}
steps:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.name }}" == *-jetbrains ]]; then
if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
fi
# Prepare and publish the plugin to JetBrains Marketplace repository
release:
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
name: Publish Plugin
runs-on: ubuntu-latest
name: Build Plugin
runs-on: macos-latest
permissions:
contents: write
pull-requests: write
@ -41,14 +47,26 @@ jobs:
with:
ref: ${{ github.event.release.tag_name }}
# Set up Java environment for the next steps
- name: Import Apple certificate
uses: apple-actions/import-codesign-certs@v3
with:
keychain: ${{ github.run_id }}
keychain-password: ${{ github.run_id }}
p12-file-base64: ${{ secrets.APPLE_CERT_DATA }}
p12-password: ${{ secrets.APPLE_CERT_PASSWORD }}
# Validate wrapper
- name: Gradle Wrapper Validation
uses: gradle/actions/wrapper-validation@v3
# # Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
# Setup Gradle
# # Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
with:
@ -59,16 +77,21 @@ jobs:
id: properties
shell: bash
run: |
CHANGELOG="$(cat << 'EOM' | sed -e 's/^[[:space:]]*$//g' -e '/./,$!d'
${{ github.event.release.body }}
EOM
)"
PROPERTIES="$(./gradlew properties --console=plain -q)"
VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')"
# CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)"
CHANGELOG=""
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT
echo "changelog<<EOF" >> $GITHUB_OUTPUT
echo "$CHANGELOG" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Setup Node.js
./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier
# # Setup Node.js
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
@ -99,22 +122,11 @@ jobs:
cd ../../core
npm ci
# npm install binary
- name: Install core node_modules
run: |
cd ../../binary
npm ci
# npm install gui
- name: Install gui node_modules
- name: Install gui node_modules and build
run: |
cd ../../gui
npm ci
# build gui
- name: Build gui
run: |
cd ../../gui
npm run build
# Run prepackage.js script
@ -123,26 +135,360 @@ jobs:
cd ../../extensions/vscode
npm ci
npm run prepackage
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
# npm install binary
- name: Install binary node_modules
run: |
cd ../../binary
npm ci
# Build binaries
- name: Install core node_modules
- name: Build the binaries
run: |
cd ../../binary
npm run build
# Update Unreleased section with the current release note
- name: Patch Changelog
if: ${{ steps.properties.outputs.changelog != '' }}
# - name: Code sign darwin binaries
# run: |
# echo "Signing executable with keychain: ${{ github.run_id }}"
# codesign --sign - ../../binary/bin/darwin-x64/continue-binary
# codesign --sign - ../../binary/bin/darwin-arm64/continue-binary
# - name: Sign darwin-arm64 binary
# uses: lando/code-sign-action@v2
# with:
# file: ./binary/bin/darwin-arm64/continue-binary
# certificate-data: ${{ secrets.APPLE_CERT_DATA }}
# certificate-password: ${{ secrets.APPLE_CERT_PASSWORD }}
# apple-notary-user: ${{ secrets.APPLE_NOTARY_USER }}
# apple-notary-password: ${{ secrets.APPLE_NOTARY_PASSWORD }}
# apple-notary-tool: altool
# apple-team-id: 43XFLY66ZD
# apple-product-id: dev.continue.continue-binary
# options: --options runtime --entitlements entitlements.xml
# Build plugin
- name: Build plugin
run: ./gradlew buildPlugin
# Publish the plugin to JetBrains Marketplace
- name: Publish EAP Plugin
env:
CHANGELOG: ${{ steps.properties.outputs.changelog }}
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: eap
run: ./gradlew publishPlugin
- name: Publish Stable Plugin
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: default
run: ./gradlew publishPlugin
# Prepare plugin archive content for creating artifact
- name: Prepare Plugin Artifact
id: artifact
shell: bash
run: |
./gradlew patchChangelog --release-note="$CHANGELOG"
cd ../../extensions/intellij/build/distributions
echo "Contents of distributions folder:"
ls
echo "---"
FILENAME=`ls continue-intellij-extension-*.zip`
unzip "$FILENAME" -d content
echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT
# Store already-built plugin as an artifact for downloading
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: ${{ steps.artifact.outputs.filename }}
path: ./extensions/intellij/build/distributions/content/*/*
# Upload binaries as artifacts
- name: Upload artifact (darwin-arm64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-darwin-arm64
path: ./binary/bin/darwin-arm64/
- name: Upload artifact (darwin-x64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-darwin-x64
path: ./binary/bin/darwin-x64/
- name: Upload artifact (win32-x64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-win32-x64
path: ./binary/bin/win32-x64/
- name: Upload artifact (linux-arm64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-linux-arm64
path: ./binary/bin/linux-arm64/
- name: Upload artifact (linux-x64)
uses: actions/upload-artifact@v4
with:
name: continue-binary-linux-x64
path: ./binary/bin/linux-x64/
test-binaries:
needs: build
strategy:
matrix:
include:
- os: windows-latest
platform: win32
arch: x64
npm_config_arch: x64
- os: ubuntu-latest
platform: linux
arch: x64
npm_config_arch: x64
# arm64 not actually supported by GitHub
# - os: ubuntu-latest
# platform: linux
# arch: arm64
# npm_config_arch: arm64
- os: macos-12
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-latest
platform: darwin
arch: arm64
npm_config_arch: arm64
runs-on: ${{ matrix.os }}
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Cache core node_modules
uses: actions/cache@v3
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache binary node_modules
uses: actions/cache@v3
with:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: Install Core Dependencies
run: |
cd ../../core
npm ci
- name: Install Binary Dependencies
run: |
cd ../../binary
npm ci
# Download the binary artifact
- name: Download binary artifact
uses: actions/download-artifact@v4
with:
name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }}
path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/
# Set execute permissions for the binary (non-Windows)
- name: Set execute permissions
run: |
cd ../../binary/bin/${{ matrix.platform }}-${{ matrix.arch }}
chmod +x continue-binary
chmod +x build/Release/node_sqlite3.node
chmod +x index.node
chmod +x esbuild
if: ${{ matrix.platform }} != 'win32'
# Run tests for binary
- name: Run binary tests
run: |
cd ../../binary
npm run test
- name: Upload logs
if: ${{ always() }}
uses: actions/upload-artifact@v2
with:
name: core-logs-${{ matrix.platform }}-${{ matrix.arch }}
path: binary/.continue/logs/core.log
# Run tests and upload a code coverage report
test:
name: Test
needs: [build]
runs-on: ubuntu-latest
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
# Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
with:
gradle-home-cache-cleanup: true
# Run tests
- name: Run Tests
run: ./gradlew check
# Collect Tests Result of failed tests
- name: Collect Tests Result
if: ${{ failure() }}
uses: actions/upload-artifact@v4
with:
name: tests-result
path: ${{ github.workspace }}/extensions/intellij/build/reports/tests
# Upload the Kover report to CodeCov
# - name: Upload Code Coverage Report
# uses: codecov/codecov-action@v4
# with:
# files: ${{ github.workspace }}/build/reports/kover/report.xml
# Run Qodana inspections and provide report
inspectCode:
if: false
name: Inspect code
needs: [build]
runs-on: ubuntu-latest
permissions:
contents: write
checks: write
pull-requests: write
steps:
# Free GitHub Actions Environment Disk Space
- name: Maximize Build Space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: false
large-packages: false
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2024.1.5
with:
cache-default-branch-only: true
# Run plugin structure verification along with IntelliJ Plugin Verifier
verify:
if: false
name: Verify plugin
needs: [build]
runs-on: ubuntu-latest
steps:
# Free GitHub Actions Environment Disk Space
- name: Maximize Build Space
uses: jlumbroso/free-disk-space@main
with:
tool-cache: false
large-packages: false
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
# Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
with:
gradle-home-cache-cleanup: true
# Cache Plugin Verifier IDEs
- name: Setup Plugin Verifier IDEs Cache
uses: actions/cache@v4
with:
path: ${{ needs.build.outputs.pluginVerifierHomeDir }}/ides
key: plugin-verifier-${{ hashFiles('build/listProductsReleases.txt') }}
# Run Verify Plugin task and IntelliJ Plugin Verifier tool
- name: Run Plugin Verification tasks
run: ./gradlew runPluginVerifier -Dplugin.verifier.home.dir=${{ needs.build.outputs.pluginVerifierHomeDir }}
# Collect Plugin Verifier Result
- name: Collect Plugin Verifier Result
if: ${{ always() }}
uses: actions/upload-artifact@v4
with:
name: pluginVerifier-result
path: ${{ github.workspace }}/build/reports/pluginVerifier
upload-release:
if: false
name: Upload Release
needs:
- build
- test-binaries
- test
runs-on: ubuntu-latest
steps:
# # Update Unreleased section with the current release note
# - name: Patch Changelog
# if: ${{ steps.properties.outputs.changelog != '' }}
# env:
# CHANGELOG: ${{ steps.properties.outputs.changelog }}
# run: |
# ./gradlew patchChangelog --release-note="$CHANGELOG"
- name: Download the plugin
uses: actions/download-artifact@v4
with:
name: ${{ steps.artifact.outputs.filename }}
path: ./build/distributions/
# Upload artifact as a release asset
- name: Upload Release Asset
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/*
# - name: Upload Release Asset
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/*
# Publish the plugin to JetBrains Marketplace
- name: Publish Plugin

View file

@ -1,14 +1,27 @@
name: Publish Extension
on:
create:
tags:
- "v0.8.*-vscode"
branches:
- main
release:
types: [released]
jobs:
check_release_name:
runs-on: ubuntu-latest
outputs:
should_run: ${{ steps.check.outputs.should_run }}
steps:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.8.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
fi
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
strategy:
matrix:
include:
@ -97,10 +110,12 @@ jobs:
cd gui
npm ci
# npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json
- name: Install Core Dependencies
run: |
cd core
npm ci
npm i vectordb
- name: Run core tests
run: |

View file

@ -1,14 +1,27 @@
name: Publish Preview Extension
on:
create:
tags:
- "v0.9.*-vscode"
branches:
- dev
release:
types: [prereleased]
jobs:
check_release_name:
runs-on: ubuntu-latest
outputs:
should_run: ${{ steps.check.outputs.should_run }}
steps:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.9.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
fi
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
strategy:
matrix:
include:
@ -92,10 +105,19 @@ jobs:
cd gui
npm ci
# npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json
- name: Install Core Dependencies
run: |
cd core
npm ci
npm i vectordb
# - name: Run core tests
# run: |
# cd core
# npm run test
# env:
# OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
# 2.5. Pre package
- name: Set var for environment info
@ -107,14 +129,6 @@ jobs:
cd extensions/vscode
npm run prepackage -- --target ${{ env.target }}
# 2.75 Run core tests
- name: Run core tests
run: |
cd core
npm run test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
# 3. Re-install esbuild (for cases that we force installed for another arch in prepackage.js)
- name: Re-install esbuild
run: |

View file

@ -5,7 +5,6 @@ on:
branches:
- main
- preview
- dev
jobs:
tsc-check:

2
.gitignore vendored
View file

@ -165,7 +165,5 @@ Icon?
.continue
# Sandbox env default file
extensions/vscode/manual-testing-sandbox/example.ts
.prompts/

5
.vscode/launch.json vendored
View file

@ -17,10 +17,7 @@
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],
"pauseForSourceMap": false,
"outFiles": [
"${workspaceFolder}/extensions/vscode/out/extension.js",
"/Users/natesesti/.continue/config.ts"
],
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
"preLaunchTask": "vscode-extension:build",
"env": {
// "CONTROL_PLANE_ENV": "local"

View file

@ -15,6 +15,7 @@
},
"search.exclude": {
"**/binary": true,
"binary/": false,
"**/core/vendor/**": true,
"**/gui/dist": true
}

9
.vscode/tasks.json vendored
View file

@ -45,8 +45,6 @@
}
]
},
// Tsc currently errors out due to testing setup issues, will be resolved in a different PR
// This will be useful for preventing debugging if there are compile errors
{
"label": "vscode-extension:tsc",
"type": "npm",
@ -164,6 +162,13 @@
"options": {
"cwd": "docs"
}
},
{
"label": "clean",
"type": "shell",
"command": "node",
"args": ["${workspaceFolder}/scripts/uninstall.js"],
"problemMatcher": []
}
]
}

View file

@ -3,4 +3,4 @@
Separate changelogs are kept for each extension:
- [VS Code Extension](./extensions/vscode/CHANGELOG.md)
- [Intellij Extension](./extensions/intellij/CHANGELOG.md)
- [JetBrains Extension](./extensions/intellij/CHANGELOG.md)

View file

@ -152,7 +152,7 @@ Pre-requisite: You should use the Intellij IDE, which can be downloaded [here](h
##### Debugging
Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The Intellij extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file.
Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The JetBrains extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file.
For the sake of rapid development, it is also possible to configure this communication to happen over local TCP sockets:

View file

@ -30,3 +30,15 @@ The build process is otherwise defined entirely in `build.js`.
## Debugging
To debug the binary with IntelliJ, set `useTcp` to `true` in `CoreMessenger.kt`, and then in VS Code run the "Core Binary" debug script. Instead of starting a subprocess for the binary and communicating over stdin/stdout, the IntelliJ extension will connect over TCP to the server started from the VS Code window. You can place breakpoints anywhere in the `core` or `binary` folders.
## Building
```bash
npm run build
```
## Testing
```bash
npm run test
```

View file

@ -162,6 +162,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
"../core/vendor/tree-sitter.wasm",
"../core/llm/llamaTokenizerWorkerPool.mjs",
"../core/llm/llamaTokenizer.mjs",
"../core/llm/tiktokenWorkerPool.mjs",
];
for (const f of filesToCopy) {
fs.copyFileSync(
@ -237,9 +238,20 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}.tar.gz`;
execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
fs.copyFileSync(
`${targetDir}/build/Release/node_sqlite3.node`,
`${targetDir}/node_sqlite3.node`,
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
fs.writeFileSync(
`${targetDir}/package.json`,
JSON.stringify(
{
name: "binary",
version: "1.0.0",
author: "Continue Dev, Inc",
license: "Apache-2.0",
},
undefined,
2,
),
);
// Copy to build directory for testing
@ -247,7 +259,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
const [platform, arch] = target.split("-");
if (platform === currentPlatform && arch === currentArch) {
fs.copyFileSync(
`${targetDir}/node_sqlite3.node`,
`${targetDir}/build/Release/node_sqlite3.node`,
`build/node_sqlite3.node`,
);
}
@ -257,10 +269,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
fs.unlinkSync(`${targetDir}/build.tar.gz`);
fs.rmSync(`${targetDir}/build`, {
recursive: true,
force: true,
});
// Download and unzip prebuilt esbuild binary for the target
console.log(`[info] Downloading esbuild for ${target}...`);
@ -299,9 +307,18 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
`${targetDir}/continue-binary${exe}`,
`${targetDir}/esbuild${exe}`,
`${targetDir}/index.node`, // @lancedb
`${targetDir}/node_sqlite3.node`,
"package.json", // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
`${targetDir}/build/Release/node_sqlite3.node`,
);
}
// Note that this doesn't verify they actually made it into the binary, just that they were in the expected folder before it was built
pathsToVerify.push("out/index.js");
pathsToVerify.push("out/llamaTokenizerWorkerPool.mjs");
pathsToVerify.push("out/tiktokenWorkerPool.mjs");
pathsToVerify.push("out/xhr-sync-worker.js");
pathsToVerify.push("out/tree-sitter.wasm");
validateFilesPresent(pathsToVerify);
console.log("[info] Done!");

View file

@ -49,6 +49,7 @@
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@crawlee/playwright": "^3.11.1",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@ -57,11 +58,11 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
"dotenv": "^16.4.5",
"extract-zip": "^2.0.1",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"handlebars": "^4.7.8",
@ -79,7 +80,9 @@
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.20.1",
"p-limit": "^6.1.0",
"pg": "^8.11.3",
"playwright": "^1.46.1",
"posthog-node": "^3.6.3",
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",

View file

@ -10,7 +10,10 @@
"assets": [
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*"
"../../out/tree-sitter-wasms/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
],
"targets": [
"node18-macos-arm64"

View file

@ -10,7 +10,10 @@
"assets": [
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*"
"../../out/tree-sitter-wasms/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
],
"targets": [
"node18-macos-x64"

View file

@ -10,7 +10,10 @@
"assets": [
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*"
"../../out/tree-sitter-wasms/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
],
"targets": [
"node18-linux-arm64"

View file

@ -10,7 +10,10 @@
"assets": [
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*"
"../../out/tree-sitter-wasms/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
],
"targets": [
"node18-linux-x64"

View file

@ -13,7 +13,10 @@
"../../out/tree-sitter-wasms/*",
"../../node_modules/win-ca/lib/crypt32-ia32.node",
"../../node_modules/win-ca/lib/crypt32-x64.node",
"../../node_modules/win-ca/lib/roots.exe"
"../../node_modules/win-ca/lib/roots.exe",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
],
"targets": [
"node18-win-arm64"

View file

@ -13,7 +13,10 @@
"../../out/tree-sitter-wasms/*",
"../../node_modules/win-ca/lib/crypt32-ia32.node",
"../../node_modules/win-ca/lib/crypt32-x64.node",
"../../node_modules/win-ca/lib/roots.exe"
"../../node_modules/win-ca/lib/roots.exe",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
],
"targets": [
"node18-win-x64"

View file

@ -38,7 +38,7 @@ class IPCMessengerBase<
}
this.send(msg.messageType, { done: true }, msg.messageId);
} else {
this.send(msg.messageType, response || {}, msg.messageId);
this.send(msg.messageType, response, msg.messageId);
}
} catch (e: any) {
console.warn(`Error running handler for "${msg.messageType}": `, e);

View file

@ -11,5 +11,6 @@ export function setupCoreLogging() {
console.log = logger;
console.error = logger;
console.warn = logger;
console.debug = logger;
console.log("[info] Starting Continue core...");
}

View file

@ -8,7 +8,7 @@
"plugins": ["@typescript-eslint", "import"],
"rules": {
"quotes": ["warn", "double", {}],
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",

3
core/.gitignore vendored
View file

@ -4,4 +4,5 @@ target
npm-debug.log*
.env
.continue-test
testDir
testDir
coverage

View file

@ -131,7 +131,7 @@ Follow these steps to ensure that everything is set up correctly:
3. Run `ollama run starcoder:3b` to verify that the model is downloaded.
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
5. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both.
6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/core.log in JetBrains).
6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains).
7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible.
### Completions are slow

View file

@ -84,9 +84,9 @@ export class BracketMatchingService {
// Add corresponding open brackets from suffix to stack
// because we overwrite them and the diff is displayed, and this allows something to be edited after that
for (let i = 0; i < suffix.length; i++) {
if (suffix[i] === " ") continue;
if (suffix[i] === " ") {continue;}
const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]];
if (!openBracket) break;
if (!openBracket) {break;}
stack.unshift(openBracket);
}

View file

@ -1,4 +1,4 @@
import { stopAtStopTokens } from "../../autocomplete/charStream.js";
import { stopAtStopTokens } from "./charStream";
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {

View file

@ -1,12 +1,24 @@
/**
* Asynchronous generator that yields characters from the input stream until it encounters
* an end-of-line character followed by a non-whitespace character.
*
* @param {AsyncGenerator<string>} stream - The input stream of characters.
* @param {string[]} endOfLine - An array of characters considered as end-of-line markers.
* @param {() => void} fullStop - A function to be called when the generator stops.
* @yields {string} Characters from the input stream.
* @returns {AsyncGenerator<string>} An async generator that yields characters.
*/
export async function* onlyWhitespaceAfterEndOfLine(
stream: AsyncGenerator<string>,
endOfLine: string[],
fullStop: () => void,
): AsyncGenerator<string> {
let pending = "";
for await (let chunk of stream) {
chunk = pending + chunk;
pending = "";
for (let i = 0; i < chunk.length - 1; i++) {
if (
endOfLine.includes(chunk[i]) &&
@ -17,6 +29,7 @@ export async function* onlyWhitespaceAfterEndOfLine(
return;
}
}
if (endOfLine.includes(chunk[chunk.length - 1])) {
pending = chunk[chunk.length - 1];
yield chunk.slice(0, chunk.length - 1);
@ -27,6 +40,11 @@ export async function* onlyWhitespaceAfterEndOfLine(
yield pending;
}
/**
* Yields characters from the stream, stopping if the first character is a newline.
* @param {AsyncGenerator<string>} stream - The input character stream.
* @yields {string} Characters from the stream.
*/
export async function* noFirstCharNewline(stream: AsyncGenerator<string>) {
let first = true;
for await (const char of stream) {
@ -40,6 +58,20 @@ export async function* noFirstCharNewline(stream: AsyncGenerator<string>) {
}
}
/**
* Asynchronously yields characters from the input stream, stopping if a stop token is encountered.
*
* @param {AsyncGenerator<string>} stream - The input stream of characters.
* @param {string[]} stopTokens - Array of tokens that signal when to stop yielding.
* @yields {string} Characters from the input stream.
* @returns {AsyncGenerator<string>} An async generator that yields characters until a stop condition is met.
* @description
* 1. If no stop tokens are provided, yields all characters from the stream.
* 2. Otherwise, buffers incoming chunks and checks for stop tokens.
* 3. Yields characters one by one if no stop token is found at the start of the buffer.
* 4. Stops yielding and returns if a stop token is encountered.
* 5. After the stream ends, yields any remaining buffered characters.
*/
export async function* stopAtStopTokens(
stream: AsyncGenerator<string>,
stopTokens: string[],

View file

@ -37,7 +37,7 @@ import {
import { isOnlyPunctuationAndWhitespace } from "./filter.js";
import { AutocompleteLanguageInfo } from "./languages.js";
import {
avoidPathLine,
avoidPathLineAndEmptyComments,
noTopLevelKeywordsMidline,
skipPrefixes,
stopAtLines,
@ -478,9 +478,9 @@ export class CompletionProvider {
const lines = fullPrefix.split("\n");
fullPrefix = `${lines.slice(0, -1).join("\n")}\n${
lang.singleLineComment
} ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${
lines[lines.length - 1]
}`;
} ${input.injectDetails
.split("\n")
.join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`;
}
const fullSuffix = getRangeInString(fileContents, {
@ -581,7 +581,10 @@ export class CompletionProvider {
prefix = `${formattedSnippets}\n\n${prefix}`;
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
// If it's an empty file, include the file name as a comment
prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n${prefix}`;
prefix = `${lang.singleLineComment} ${getLastNPathParts(
filepath,
2,
)}\n${prefix}`;
}
prompt = compiledTemplate({
@ -689,7 +692,10 @@ export class CompletionProvider {
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator, fullStop);
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment);
lineGenerator = avoidPathLineAndEmptyComments(
lineGenerator,
lang.singleLineComment,
);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = noTopLevelKeywordsMidline(
lineGenerator,

View file

@ -26,7 +26,7 @@ export const Python = {
name: "Python",
// """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks.
// This stops the model from trying to complete the start of a new markdown block
topLevelKeywords: ["def", "class", '"""#'],
topLevelKeywords: ["def", "class", "\"\"\"#"],
singleLineComment: "#",
endOfLine: [],
};

View file

@ -0,0 +1,421 @@
import { jest } from "@jest/globals";
import * as lineStream from "./lineStream";
describe("lineStream", () => {
let mockFullStop: jest.Mock;
async function getLineGenerator(lines: any) {
return (async function* () {
for (const line of lines) {
yield line;
}
})();
}
async function getFilteredLines(results: any) {
const output = [];
for await (const line of results) {
output.push(line);
}
return output;
}
beforeEach(() => {
mockFullStop = jest.fn();
});
describe("noTopLevelKeywordsMidline", () => {
it.todo("Need some sample inputs to properly test this");
});
describe("avoidPathLine", () => {
it("should filter out path lines and empty comments", async () => {
const linesGenerator = await getLineGenerator([
"// Path: src/index.ts",
"const x = 5;",
"//",
"console.log(x);",
]);
const result = lineStream.avoidPathLineAndEmptyComments(
linesGenerator,
"//",
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "console.log(x);"]);
});
});
describe("streamWithNewLines", () => {
it("should add newlines between lines", async () => {
const linesGenerator = await getLineGenerator([
"line1",
"line2",
"line3",
]);
const result = lineStream.streamWithNewLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]);
});
});
describe("lineIsRepeated", () => {
it("should return true for similar lines", () => {
expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe(
true,
);
});
it("should return false for different lines", () => {
expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe(
false,
);
});
it("should return false for short lines", () => {
expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false);
});
});
describe("stopAtSimilarLine", () => {
it("should stop at the exact same line", async () => {
const lineToTest = "const x = 6;";
const linesGenerator = await getLineGenerator([
"console.log();",
"const y = () => {};",
lineToTest,
]);
const result = lineStream.stopAtSimilarLine(
linesGenerator,
lineToTest,
mockFullStop,
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should stop at a similar line", async () => {
const lineToTest = "const x = 6;";
const linesGenerator = await getLineGenerator([
"console.log();",
"const y = () => {};",
lineToTest,
]);
const result = lineStream.stopAtSimilarLine(
linesGenerator,
"a" + lineToTest,
mockFullStop,
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should continue on bracket ending lines", async () => {
const linesGenerator = await getLineGenerator([
" if (x > 0) {",
" console.log(x);",
" }",
]);
const result = lineStream.stopAtSimilarLine(
linesGenerator,
"}",
mockFullStop,
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
" if (x > 0) {",
" console.log(x);",
" }",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
});
describe("stopAtLines", () => {
it("should stop at specified lines", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
lineStream.LINES_TO_STOP_AT[0],
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
});
describe("skipPrefixes", () => {
it("should skip specified prefixes", async () => {
const linesGenerator = await getLineGenerator([
`${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`,
"let y = 10;",
]);
const result = lineStream.skipPrefixes(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
});
});
describe("skipLines", () => {
it("should skip specified lines", async () => {
const linesGenerator = await getLineGenerator([
`${lineStream.LINES_TO_SKIP[0]}const x = 5;`,
"let y = 10;",
]);
const result = lineStream.skipLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["let y = 10;"]);
});
});
describe("filterCodeBlockLines", () => {
it("should remove lines before the first valid line", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it.todo("Need some sample inputs to properly test this");
});
describe("filterEnglishLinesAtStart", () => {
it("should skip initial empty line", async () => {
const linesGenerator = await getLineGenerator([
"",
"const x = 5;",
"let y = 10;",
]);
const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
});
it("should filter out English first line", async () => {
const linesGenerator = await getLineGenerator([
lineStream.ENGLISH_START_PHRASES[0],
"let y = 10;",
]);
const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["let y = 10;"]);
});
it("should not filter out non-English first line", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
]);
const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
});
it("should filter out empty newline after first line english word", async () => {
const linesGenerator = await getLineGenerator([
lineStream.ENGLISH_START_PHRASES[0],
"",
"const x = 5;",
]);
const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should filter out sentences ending in a semi-colon that are not code keywords", async () => {
const linesGenerator = await getLineGenerator([
"a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":",
"const x = 5;",
]);
const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should not filter out sentences ending in a semi-colon that are code keywords", async () => {
const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":";
const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]);
const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([keyword, "const x = 5;"]);
});
});
describe("filterEnglishLinesAtEnd", () => {
it("should stop at English explanation after code block", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```",
lineStream.ENGLISH_POST_PHRASES[0],
]);
const result = lineStream.filterEnglishLinesAtEnd(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```"]);
});
});
describe("fixCodeLlamaFirstLineIndentation", () => {
it("should fix indentation of the first line", async () => {
const linesGenerator = await getLineGenerator([
" const x = 5;",
"let y = 10;",
]);
const result =
lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
});
});
describe("filterLeadingAndTrailingNewLineInsertion", () => {
it("should ignore 'useless' new first lines", async () => {
const linesGenerator = await getLineGenerator([
{ type: "new", line: lineStream.USELESS_LINES[0] },
{ type: "new", line: "const x = 5;" },
]);
const result =
lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]);
});
it("should handle preserve newlines chars in old lines", async () => {
const linesGenerator = await getLineGenerator([
{ type: "new", line: "const x = 5;" },
{ type: "old", line: "let y = 10;" },
{ type: "old", line: "" },
{ type: "new", line: "const z = 15;" },
]);
const result =
lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
{ type: "new", line: "const x = 5;" },
{ type: "old", line: "let y = 10;" },
{ type: "old", line: "" },
{ type: "new", line: "const z = 15;" },
]);
});
it("should filter leading and trailing new line insertions", async () => {
const linesGenerator = await getLineGenerator([
{ type: "new", line: "" },
{ type: "new", line: "const x = 5;" },
{ type: "new", line: "let y = 10;" },
{ type: "new", line: "" },
]);
const result =
lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
{ type: "new", line: "const x = 5;" },
{ type: "new", line: "let y = 10;" },
]);
});
it("should buffer newline chars and then render them if we encounter another non-empty line", async () => {
const linesGenerator = await getLineGenerator([
{ type: "new", line: "const x = 5;" },
{ type: "new", line: "" },
{ type: "new", line: "let y = 10;" },
]);
const result =
lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
{ type: "new", line: "const x = 5;" },
{ type: "new", line: "" },
{ type: "new", line: "let y = 10;" },
]);
});
});
describe("stopAtRepeatingLines", () => {
it("should handle non-repeating lines correctly", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
"const z = 15;",
]);
const result = lineStream.stopAtRepeatingLines(
linesGenerator,
mockFullStop,
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"let y = 10;",
"const z = 15;",
]);
});
it("should stop at repeating lines", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
"let y = 10;",
"let y = 10;",
"const z = 15;",
]);
const result = lineStream.stopAtRepeatingLines(
linesGenerator,
mockFullStop,
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
});
});

View file

@ -1,12 +1,107 @@
import { distance } from "fastest-levenshtein";
import { LineStream } from "../diff/util.js";
import { DiffLine } from "../index.js";
import { LineStream } from "../diff/util";
import { DiffLine } from "../";
export type LineFilter = (args: {
lines: LineStream;
fullStop: () => void;
}) => LineStream;
function isBracketEnding(line: string): boolean {
return line
.trim()
.split("")
.some((char) => BRACKET_ENDING_CHARS.includes(char));
}
function commonPrefixLength(a: string, b: string): number {
let i = 0;
while (i < a.length && i < b.length && a[i] === b[i]) {
i++;
}
return i;
}
function isEnglishFirstLine(line: string) {
line = line.trim().toLowerCase();
if (
line.endsWith(":") &&
!CODE_KEYWORDS_ENDING_IN_SEMICOLON.some((keyword) =>
line.startsWith(keyword),
)
) {
return true;
}
return ENGLISH_START_PHRASES.some((phrase) => line.startsWith(phrase));
}
function isEnglishPostExplanation(line: string): boolean {
const lower = line.toLowerCase();
return ENGLISH_POST_PHRASES.some((phrase) => lower.startsWith(phrase));
}
function shouldRemoveLineBeforeStart(line: string): boolean {
return (
line.trimStart().startsWith("```") ||
LINES_TO_REMOVE_BEFORE_START.some((l) => line.trim() === l)
);
}
function shouldChangeLineAndStop(line: string): string | undefined {
if (line.trimStart() === "```") {
return line;
}
if (line.includes(CODE_START_BLOCK)) {
return line.split(CODE_START_BLOCK)[0].trimEnd();
}
return undefined;
}
function isUselessLine(line: string): boolean {
const trimmed = line.trim().toLowerCase();
const hasUselessLine = USELESS_LINES.some(
(uselessLine) => trimmed === uselessLine,
);
return hasUselessLine || trimmed.startsWith("// end");
}
export const USELESS_LINES = ["", "```"];
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
export const CODE_START_BLOCK = "[/CODE]";
export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
export const PREFIXES_TO_SKIP = ["<COMPLETION>"];
export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
export const LINES_TO_SKIP = ["</START EDITING HERE>"];
export const LINES_TO_REMOVE_BEFORE_START = [
"<COMPLETION>",
"[CODE]",
"<START EDITING HERE>",
];
export const ENGLISH_START_PHRASES = [
"here is",
"here's",
"sure, here",
"sure thing",
"sure!",
"to fill",
"certainly",
"of course",
"the code should",
];
export const ENGLISH_POST_PHRASES = [
"explanation:",
"here is",
"here's how",
"the above",
];
export async function* noTopLevelKeywordsMidline(
lines: LineStream,
topLevelKeywords: string[],
@ -15,6 +110,7 @@ export async function* noTopLevelKeywordsMidline(
for await (const line of lines) {
for (const keyword of topLevelKeywords) {
const indexOf = line.indexOf(`${keyword} `);
// TODO: What is this second clause for?
if (indexOf >= 0 && line.slice(indexOf - 1, indexOf).trim() !== "") {
yield line.slice(0, indexOf);
fullStop();
@ -25,7 +121,14 @@ export async function* noTopLevelKeywordsMidline(
}
}
export async function* avoidPathLine(
/**
* Filters out unwanted lines from a LineStream, specifically those starting with '// Path: <PATH>' or empty comments.
*
* @param {LineStream} stream - The input stream of lines to filter.
* @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments).
* @yields {string} The filtered lines, excluding unwanted path lines and empty comments.
*/
export async function* avoidPathLineAndEmptyComments(
stream: LineStream,
comment: string,
): LineStream {
@ -40,6 +143,12 @@ export async function* avoidPathLine(
}
}
/**
* Transforms a LineStream by adding newline characters between lines.
*
* @param {LineStream} stream - The input stream of lines.
* @yields {string} The lines from the input stream with newline characters added between them.
*/
export async function* streamWithNewLines(stream: LineStream): LineStream {
let firstLine = true;
for await (const nextLine of stream) {
@ -51,22 +160,19 @@ export async function* streamWithNewLines(stream: LineStream): LineStream {
}
}
const bracketEnding = [")", "]", "}", ";"];
function isBracketEnding(line: string): boolean {
return line
.trim()
.split("")
.some((char) => bracketEnding.includes(char));
}
function commonPrefixLength(a: string, b: string): number {
let i = 0;
while (i < a.length && i < b.length && a[i] === b[i]) {
i++;
}
return i;
}
/**
* Determines if two lines of text are considered repeated or very similar.
*
* @param {string} a - The first line of text to compare.
* @param {string} b - The second line of text to compare.
* @returns {boolean} True if the lines are considered repeated, false otherwise.
*
* @description
* This function checks if two lines are repeated or very similar based on two criteria:
* 1. They have a common prefix longer than 12 characters.
* 2. The Levenshtein distance between them is less than 10% of the length of the second line.
* Lines shorter than 5 characters are never considered repeated.
*/
export function lineIsRepeated(a: string, b: string): boolean {
if (a.length <= 4 || b.length <= 4) {
return false;
@ -80,6 +186,21 @@ export function lineIsRepeated(a: string, b: string): boolean {
);
}
/**
* Filters a LineStream, stopping when a line similar to the provided one is encountered.
*
* @param {LineStream} stream - The input stream of lines to filter.
* @param {string} line - The line to compare against for similarity.
* @param {() => void} fullStop - Function to call when stopping the stream.
* @yields {string} Filtered lines until a similar line is encountered.
*
* @description
* This generator function processes the input stream, yielding lines until it encounters:
* 1. An exact match to the provided line.
* 2. A line that is considered repeated or very similar to the provided line.
* 3. For lines ending with brackets, it allows exact matches of trimmed content.
* When any of these conditions are met, it calls the fullStop function and stops yielding.
*/
export async function* stopAtSimilarLine(
stream: LineStream,
line: string,
@ -87,6 +208,7 @@ export async function* stopAtSimilarLine(
): AsyncGenerator<string> {
const trimmedLine = line.trim();
const lineIsBracketEnding = isBracketEnding(trimmedLine);
for await (const nextLine of stream) {
if (nextLine === line) {
fullStop();
@ -102,12 +224,17 @@ export async function* stopAtSimilarLine(
fullStop();
break;
}
yield nextLine;
}
}
const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
/**
* Filters a LineStream, stopping when a line contains any of the specified stop phrases.
* @param {LineStream} stream - The input stream of lines.
* @param {() => void} fullStop - Function to call when stopping.
* @yields {string} Filtered lines until a stop phrase is encountered.
*/
export async function* stopAtLines(
stream: LineStream,
fullStop: () => void,
@ -121,7 +248,11 @@ export async function* stopAtLines(
}
}
const PREFIXES_TO_SKIP = ["<COMPLETION>"];
/**
* Filters a LineStream, skipping specified prefixes on the first line.
* @param {LineStream} lines - The input stream of lines.
* @yields {string} Filtered lines with prefixes removed from the first line if applicable.
*/
export async function* skipPrefixes(lines: LineStream): LineStream {
let isFirstLine = true;
for await (const line of lines) {
@ -137,8 +268,11 @@ export async function* skipPrefixes(lines: LineStream): LineStream {
}
}
const LINES_TO_SKIP = ["</START EDITING HERE>"];
/**
* Filters out lines starting with specified prefixes from a LineStream.
* @param {LineStream} stream - The input stream of lines.
* @yields {string} Filtered lines that don't start with any of the LINES_TO_SKIP prefixes.
*/
export async function* skipLines(stream: LineStream): LineStream {
for await (const line of stream) {
if (!LINES_TO_SKIP.some((skipAt) => line.startsWith(skipAt))) {
@ -147,34 +281,21 @@ export async function* skipLines(stream: LineStream): LineStream {
}
}
const LINES_TO_REMOVE_BEFORE_START = [
"<COMPLETION>",
"[CODE]",
"<START EDITING HERE>",
];
function shouldRemoveLineBeforeStart(line: string): boolean {
return (
line.trimStart().startsWith("```") ||
LINES_TO_REMOVE_BEFORE_START.some((l) => line.trim() === l)
);
}
function shouldChangeLineAndStop(line: string): string | undefined {
if (line.trimStart() === "```") {
return line;
}
if (line.includes("[/CODE]")) {
return line.split("[/CODE]")[0].trimEnd();
}
return undefined;
}
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
*
* @param {LineStream} rawLines - The input stream of lines to filter.
* @yields {string} Filtered and processed lines from the code block.
*
* @description
* This generator function performs the following tasks:
* 1. Removes initial lines that should be removed before the actual code starts.
* 2. Filters out ending code block markers (```) unless they are the last line.
* 3. Handles special cases where lines should be changed and the stream should stop.
* 4. Yields processed lines that are part of the actual code block content.
*/
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
let seenValidLine = false;
let waitingToSeeIfLineIsLast = undefined;
for await (const line of rawLines) {
@ -206,28 +327,19 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
}
}
function isEnglishFirstLine(line: string) {
line = line.trim().toLowerCase();
if (line.endsWith(":") && !line.trimStart().startsWith("def")) {
return true;
}
if (
line.startsWith("here is") ||
line.startsWith("here's") ||
line.startsWith("sure, here") ||
line.startsWith("sure thing") ||
line.startsWith("sure!") ||
line.startsWith("to fill") ||
line.startsWith("certainly") ||
line.startsWith("of course") ||
line.startsWith("the code should")
) {
return true;
}
return false;
}
/**
* Filters out English explanations at the start of a code block.
*
* @param {LineStream} lines - The input stream of lines.
* @yields {string} Filtered lines with English explanations removed from the start.
*
* @description
* This generator function performs the following tasks:
* 1. Skips initial blank lines.
* 2. Removes the first line if it's identified as an English explanation.
* 3. Removes a subsequent blank line if the first line was an English explanation.
* 4. Yields all remaining lines.
*/
export async function* filterEnglishLinesAtStart(lines: LineStream) {
let i = 0;
let wasEnglishFirstLine = false;
@ -235,6 +347,7 @@ export async function* filterEnglishLinesAtStart(lines: LineStream) {
if (i === 0 && line.trim() === "") {
continue;
}
if (i === 0) {
if (isEnglishFirstLine(line)) {
wasEnglishFirstLine = true;
@ -250,18 +363,14 @@ export async function* filterEnglishLinesAtStart(lines: LineStream) {
}
}
function isEnglishPostExplanation(line: string): boolean {
const lower = line.toLowerCase();
return (
lower.startsWith("explanation:") ||
lower.startsWith("here is") ||
lower.startsWith("here's how") ||
lower.startsWith("the above")
);
}
/**
* Filters out English explanations at the end of a code block.
* @param {LineStream} lines - The input stream of lines.
* @yields {string} Lines up to the end of the code block or start of English explanation.
*/
export async function* filterEnglishLinesAtEnd(lines: LineStream) {
let finishedCodeBlock = false;
for await (const line of lines) {
if (line.trim() === "```") {
finishedCodeBlock = true;
@ -273,8 +382,14 @@ export async function* filterEnglishLinesAtEnd(lines: LineStream) {
}
}
/**
* Removes leading indentation from the first line of a CodeLlama output.
* @param {LineStream} lines - The input stream of lines.
* @yields {string} Lines with the first line's indentation fixed if necessary.
*/
export async function* fixCodeLlamaFirstLineIndentation(lines: LineStream) {
let isFirstLine = true;
for await (const line of lines) {
if (isFirstLine && line.startsWith(" ")) {
yield line.slice(2);
@ -285,23 +400,36 @@ export async function* fixCodeLlamaFirstLineIndentation(lines: LineStream) {
}
}
function isUselessLine(line: string): boolean {
const trimmed = line.trim().toLowerCase();
return trimmed === "" || trimmed === "```" || trimmed.startsWith("// end");
}
/**
* Filters leading and trailing blank line insertions from a stream of diff lines.
*
* @param {AsyncGenerator<DiffLine>} diffLines - An async generator that yields DiffLine objects.
* @yields {DiffLine} Filtered DiffLine objects, with leading and trailing blank line insertions removed.
*
* @description
* This generator function processes a stream of diff lines, removing leading and trailing
* blank line insertions. It performs the following tasks:
* 1. Skips the first blank line insertion if it occurs at the beginning.
* 2. Buffers subsequent blank line insertions.
* 3. Yields buffered blank lines when a non-blank insertion is encountered.
* 4. Clears the buffer when an old line is encountered.
* 5. Yields all non-blank insertions and old lines.
*/
export async function* filterLeadingAndTrailingNewLineInsertion(
diffLines: AsyncGenerator<DiffLine>,
): AsyncGenerator<DiffLine> {
let isFirst = true;
let buffer: DiffLine[] = [];
for await (const diffLine of diffLines) {
const isBlankLineInsertion =
diffLine.type === "new" && isUselessLine(diffLine.line);
if (isFirst && isBlankLineInsertion) {
isFirst = false;
continue;
}
isFirst = false;
if (isBlankLineInsertion) {
@ -319,31 +447,38 @@ export async function* filterLeadingAndTrailingNewLineInsertion(
}
}
/**
* Filters a LineStream, stopping when a line repeats more than a specified number of times.
*
* @param {LineStream} lines - The input stream of lines to filter.
* @param {() => void} fullStop - Function to call when stopping the stream.
* @yields {string} Filtered lines until excessive repetition is detected.
*
* @description
* This function yields lines from the input stream until a line is repeated
* for a maximum of 3 consecutive times. When this limit is reached, it calls
* the fullStop function and stops yielding. Only the first of the repeating
* lines is yieled.
*/
export async function* stopAtRepeatingLines(
lines: LineStream,
fullStop: () => void,
): LineStream {
const repeatedLines: string[] = [];
let previousLine: string | undefined;
let repeatCount = 0;
const MAX_REPEATS = 3;
for await (const line of lines) {
if (repeatedLines.length === 0) {
repeatedLines.push(line);
} else if (repeatedLines.length < 3) {
if (repeatedLines[repeatedLines.length - 1] === line) {
repeatedLines.push(line);
} else {
while (repeatedLines.length > 0) {
yield repeatedLines.shift()!;
}
yield line;
if (line === previousLine) {
repeatCount++;
if (repeatCount === MAX_REPEATS) {
fullStop();
return;
}
} else {
yield repeatedLines[0];
fullStop();
return;
yield line;
repeatCount = 1;
}
}
while (repeatedLines.length > 0) {
yield repeatedLines.shift()!;
previousLine = line;
}
}

View file

@ -1,5 +1,5 @@
import { BranchAndDir, Chunk } from "../index.js";
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch.js";
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js";
export async function fullTextRetrieve(
prefix: string,

View file

@ -33,8 +33,8 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
"<fim_prefix>",
"<fim_suffix>",
"<fim_middle>",
"<|endoftext|>",
"<file_sep>",
"<|endoftext|>",
"</fim_middle>",
"</code>",
],
@ -70,7 +70,9 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
.map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`)
.join("\n\n");
return [
`${otherFiles}\n\n+++++ ${relativePaths[relativePaths.length - 1]}\n${prefix}`,
`${otherFiles}\n\n+++++ ${
relativePaths[relativePaths.length - 1]
}\n${prefix}`,
suffix,
];
},
@ -132,8 +134,8 @@ const starcoder2FimTemplate: AutocompleteTemplate = {
"<fim_prefix>",
"<fim_suffix>",
"<fim_middle>",
"<|endoftext|>",
"<file_sep>",
"<|endoftext|>",
],
},
};
@ -172,8 +174,10 @@ const codegeexFimTemplate: AutocompleteTemplate = {
...snippets.map((snippet) => snippet.filepath),
filepath,
]);
const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1]}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
if (snippets.length == 0) {
const baseTemplate = `###PATH:${
relativePaths[relativePaths.length - 1]
}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
if (snippets.length === 0) {
return `<|user|>\n${baseTemplate}<|assistant|>\n`;
}
const references = `###REFERENCE:\n${snippets

View file

@ -1,5 +1,5 @@
import { SlashCommand } from "../../index.js";
import EditSlashCommand from "./edit.js";
import { SlashCommand } from "../../";
import EditSlashCommand from "./edit";
const CommentSlashCommand: SlashCommand = {
name: "comment",

View file

@ -5,18 +5,18 @@ import {
fixCodeLlamaFirstLineIndentation,
stopAtLines,
streamWithNewLines,
} from "../../autocomplete/lineStream.js";
import { streamLines } from "../../diff/util.js";
import { ContextItemWithId, ILLM, SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
} from "../../autocomplete/lineStream";
import { streamLines } from "../../diff/util";
import { ContextItemWithId, ILLM, SlashCommand } from "../../";
import { stripImages } from "../../llm/images";
import {
dedentAndGetCommonWhitespace,
getMarkdownLanguageTagForFile,
} from "../../util/index.js";
} from "../../util/";
import {
contextItemToRangeInFileWithContents,
type RangeInFileWithContents,
} from "../util.js";
} from "../util";
const PROMPT = `Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The </modified_code_to_edit> tag should be written to indicate the end of the modified code section. Do not ever use nested tags.
@ -62,13 +62,6 @@ export async function getPromptParts(
) {
const maxTokens = Math.floor(model.contextLength / 2);
const TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = tokenLimit ?? 1200;
// if (model.countTokens(rif.contents) > TOKENS_TO_BE_CONSIDERED_LARGE_RANGE) {
// throw new Error(
// "\n\n**It looks like you've selected a large range to edit, which may take a while to complete. If you'd like to cancel, click the 'X' button above. If you highlight a more specific range, Continue will only edit within it.**"
// );
// }
const BUFFER_FOR_FUNCTIONS = 400;
let totalTokens =
model.countTokens(fullFileContents + PROMPT + input) +

View file

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { IDE, SlashCommand } from "../..";
import * as fs from "fs/promises";
import * as path from "path";

View file

@ -1,11 +1,11 @@
import fs from "node:fs";
import path from "node:path";
import { defaultConfig } from "../../config/default";
import { getConfigTsPath } from "../../util/paths";
import { testConfigHandler } from "../fixtures";
import { TEST_DIR } from "../testUtils/testDir";
import { defaultConfig } from "./default";
import { getConfigTsPath } from "../util/paths";
import { testConfigHandler } from "../test/util/fixtures";
import { TEST_DIR } from "../test/util/testDir";
describe("Test the ConfigHandler and E2E config loading", () => {
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.listProfiles();
expect(profiles.length).toBe(1);

View file

@ -51,12 +51,12 @@ class ProfileLifecycleManager {
}
// Clear saved config and reload
reloadConfig(): Promise<ContinueConfig> {
async reloadConfig(): Promise<ContinueConfig> {
this.savedConfig = undefined;
this.savedBrowserConfig = undefined;
this.pendingConfigPromise = undefined;
return this.profileLoader.doLoadConfig();
return await this.profileLoader.doLoadConfig();
}
async loadConfig(

View file

@ -355,9 +355,11 @@ async function intermediateToFinalConfig(
// These context providers are always included, regardless of what, if anything,
// the user has configured in config.json
const codebaseContextParams = ((config.contextProviders || []).filter(isContextProviderWithParams).find(cp => cp.name === "codebase") as ContextProviderWithParams | undefined)?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(

View file

@ -10,6 +10,7 @@ import {
import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js";
import { Telemetry } from "../../util/posthog.js";
import { TTS } from "../../util/tts.js";
import { loadFullConfigNode } from "../load.js";
export default async function doLoadConfig(
@ -48,9 +49,12 @@ export default async function doLoadConfig(
await Telemetry.setup(
newConfig.allowAnonymousTelemetry ?? true,
await ide.getUniqueId(),
ideInfo.extensionVersion,
ideInfo,
);
// TODO: pass config to pre-load non-system TTS models
await TTS.setup();
if (newConfig.analytics) {
await TeamAnalytics.setup(
newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all

View file

@ -4,8 +4,8 @@ import * as YAML from "yaml";
import type { IDE, SlashCommand } from "..";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/images";
import { getBasename } from "../util/index";
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
import { getBasename } from "../util/index";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";

View file

@ -37,7 +37,7 @@ class PostgresContextProvider extends BaseContextProvider {
let tablesInfoQuery = `
SELECT table_schema, table_name
FROM information_schema.tables`;
if (schema != null) {
if (schema !== null) {
tablesInfoQuery += ` WHERE table_schema = '${schema}'`;
}
const { rows: tablesInfo } = await pool.query(tablesInfoQuery);

View file

@ -26,7 +26,7 @@ export class HuggingFaceTEIReranker implements Reranker {
const resp = await fetch(new URL("rerank", apiBase), {
method: "POST",
headers: { 'Content-Type': 'application/json' },
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: query,
return_text: false,

View file

@ -1,5 +1,5 @@
import { BranchAndDir, Chunk } from "../../index.js";
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch.js";
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js";
export async function retrieveFts(
query: string,

View file

@ -6,7 +6,7 @@ export async function getHeaders() {
key: constants.c,
timestamp: getTimestamp(),
v: "1",
extensionVersion: Telemetry.extensionVersion ?? "0.0.0",
extensionVersion: Telemetry.ideInfo?.extensionVersion ?? "0.0.0",
os: Telemetry.os ?? "Unknown",
uniqueId: Telemetry.uniqueId ?? "None",
};

View file

@ -30,7 +30,8 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
async setup(config: Analytics, uniqueId: string): Promise<void> {
if (!config.url) {
throw new Error("Missing url in analytics config");
console.warn("LogStashAnalyticsProvider is missing a URL");
return;
}
const url = new URL(config.url);
this.host = url.hostname;

View file

@ -74,7 +74,7 @@ export class ControlPlaneClient {
}
try {
const resp = await this.request(`/workspaces`, {
const resp = await this.request("/workspaces", {
method: "GET",
});
return (await resp.json()) as any;

View file

@ -26,7 +26,9 @@ import historyManager from "./util/history";
import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { TTS } from "./util/tts";
import { streamDiffLines } from "./util/verticalEdit";
import DocsCrawler from "./indexing/docs/DocsCrawler";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -167,12 +169,19 @@ export class Core {
(..._) => Promise.resolve([]),
);
try {
DocsCrawler.verifyOrInstallChromium();
} catch (err) {
console.debug(`Failed to install Chromium: ${err}`);
}
const on = this.messenger.on.bind(this.messenger);
this.messenger.onError((err) => {
console.error(err);
Telemetry.capture("core_messenger_error", {
message: err.message,
stack: err.stack,
});
this.messenger.request("errorPopup", { message: err.message });
});
@ -359,6 +368,13 @@ export class Core {
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
) {
const config = await configHandler.loadConfig();
// Stop TTS on new StreamChat
if(config.experimental?.readResponseTTS) {
TTS.kill();
}
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamChat(
msg.data.messages,
@ -383,6 +399,10 @@ export class Core {
next = await gen.next();
}
if(config.experimental?.readResponseTTS && "completion" in next.value) {
TTS.read(next.value?.completion);
}
return { done: true, content: next.value };
}
@ -457,6 +477,13 @@ export class Core {
}
});
// Provide messenger to TTS so it can set GUI active / inactive state
TTS.messenger = this.messenger;
on("tts/kill", async () => {
TTS.kill();
});
async function* runNodeJsSlashCommand(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
@ -638,8 +665,13 @@ export class Core {
const rows = await DevDataSqliteDb.getTokensPerModel();
return rows;
});
on("index/forceReIndex", async (msg) => {
const dirs = msg.data ? [msg.data] : await this.ide.getWorkspaceDirs();
on("index/forceReIndex", async ({ data }) => {
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
await codebaseIndexer.clearIndexes();
}
const dirs = data?.dir ? [data.dir] : await this.ide.getWorkspaceDirs();
await this.refreshCodebaseIndex(dirs);
});
on("index/setPaused", (msg) => {
@ -690,6 +722,7 @@ export class Core {
"indexing_error",
{
error: update.desc,
stack: update.debugInfo,
},
false,
);

37
core/index.d.ts vendored
View file

@ -37,7 +37,9 @@ export interface Chunk extends ChunkWithoutID {
export interface IndexingProgressUpdate {
progress: number;
desc: string;
shouldClearIndexes?: boolean;
status: "loading" | "indexing" | "done" | "failed" | "paused" | "disabled";
debugInfo?: string;
}
export type PromptTemplate =
@ -56,6 +58,7 @@ export interface ILLM extends LLMOptions {
title?: string;
systemMessage?: string;
contextLength: number;
maxStopWords?: number;
completionOptions: CompletionOptions;
requestOptions?: RequestOptions;
promptTemplates?: Record<string, PromptTemplate>;
@ -319,6 +322,7 @@ export interface LLMOptions {
uniqueId?: string;
systemMessage?: string;
contextLength?: number;
maxStopWords?: number;
completionOptions?: CompletionOptions;
requestOptions?: RequestOptions;
template?: TemplateType;
@ -340,19 +344,23 @@ export interface LLMOptions {
apiVersion?: string;
apiType?: string;
// GCP Options
// AWS options
profile?: string;
modelArn?: string;
// AWS and GCP Options
region?: string;
// GCP Options
projectId?: string;
capabilities?: ModelCapability;
// WatsonX options
// IBM watsonx options
watsonxUrl?: string;
watsonxApiKey?: string;
watsonxZenApiKeyBase64?: string; // Required if using watsonx software with ZenApiKey auth
watsonxUsername?: string;
watsonxPassword?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -586,6 +594,7 @@ type ModelProvider =
| "ollama"
| "huggingface-tgi"
| "huggingface-inference-api"
| "kindo"
| "llama.cpp"
| "replicate"
| "text-gen-webui"
@ -594,6 +603,7 @@ type ModelProvider =
| "gemini"
| "mistral"
| "bedrock"
| "bedrockimport"
| "sagemaker"
| "deepinfra"
| "flowise"
@ -606,7 +616,8 @@ type ModelProvider =
| "azure"
| "openai-aiohttp"
| "msty"
| "watsonx";
| "watsonx"
| "openrouter";
export type ModelName =
| "AUTODETECT"
@ -745,6 +756,7 @@ export interface ModelDescription {
apiKey?: string;
apiBase?: string;
contextLength?: number;
maxStopWords?: number;
template?: TemplateType;
completionOptions?: BaseCompletionOptions;
systemMessage?: string;
@ -871,10 +883,14 @@ interface QuickActionConfig {
sendToChat: boolean;
}
export type DefaultContextProvider = ContextProviderWithParams & {
query?: string;
};
interface ExperimentalConfig {
contextMenuPrompts?: ContextMenuConfig;
modelRoles?: ModelRoles;
defaultContext?: "activeFile"[];
defaultContext?: DefaultContextProvider[];
promptPath?: string;
/**
@ -882,6 +898,11 @@ interface ExperimentalConfig {
* function and class declarations.
*/
quickActions?: QuickActionConfig[];
/**
* Automatically read LLM chat responses aloud using system TTS models
*/
readResponseTTS?: boolean;
}
interface AnalyticsConfig {

View file

@ -0,0 +1,83 @@
import { jest } from "@jest/globals";
import { testIde } from "../test/util/fixtures";
import {
insertMockChunks,
updateIndexAndAwaitGenerator,
mockPathAndCacheKey,
} from "../test/util/indexing";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
describe("CodeSnippetsCodebaseIndex", () => {
let index: CodeSnippetsCodebaseIndex;
let db: DatabaseConnection;
async function getAllSnippets() {
return await db.all("SELECT * FROM code_snippets");
}
async function getAllSnippetTags() {
return await db.all("SELECT * FROM code_snippets_tags");
}
beforeAll(async () => {
db = await SqliteDb.get();
index = new CodeSnippetsCodebaseIndex(testIde);
});
it("should update the index and maintain expected database state", async () => {
const mockMarkComplete = jest
.fn()
.mockImplementation(() => Promise.resolve()) as any;
const mockSnippet = {
title: "",
content: "",
startLine: 0,
endLine: 1,
};
// We mock this fn since currently in testing the directory structure to access the tree-sitter
// binaries does not match what is in the release environment.
jest
.spyOn(CodeSnippetsCodebaseIndex.prototype, "getSnippetsInFile")
.mockResolvedValue([mockSnippet]);
await insertMockChunks();
// Compute test
await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete);
expect((await getAllSnippetTags()).length).toBe(1);
expect((await getAllSnippets()).length).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.Compute,
);
// RemoveTag test
await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete);
expect((await getAllSnippetTags()).length).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.RemoveTag,
);
// AddTag test
await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete);
expect((await getAllSnippetTags()).length).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.AddTag,
);
// Delete test
await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete);
expect((await getAllSnippetTags()).length).toBe(0);
expect((await getAllSnippets()).length).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.Delete,
);
});
});

View file

@ -100,26 +100,30 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
contents: string,
): Promise<(ChunkWithoutID & { title: string })[]> {
const parser = await getParserForFile(filepath);
if (!parser) {
return [];
}
const ast = parser.parse(contents);
const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets);
const matches = query?.matches(ast.rootNode);
return (
matches?.flatMap((match) => {
const node = match.captures[0].node;
const title = match.captures[1].node.text;
const results = {
title,
content: node.text,
startLine: node.startPosition.row,
endLine: node.endPosition.row,
};
return results;
}) ?? []
);
if (!matches) {
return [];
}
return matches.flatMap((match) => {
const node = match.captures[0].node;
const title = match.captures[1].node.text;
const results = {
title,
content: node.text,
startLine: node.startPosition.row,
endLine: node.endPosition.row,
};
return results;
});
}
async *update(
@ -132,6 +136,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
await CodeSnippetsCodebaseIndex._createTables(db);
const tagString = tagToString(tag);
// Compute
for (let i = 0; i < results.compute.length; i++) {
const compute = results.compute[i];
@ -174,18 +179,29 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
markComplete([compute], IndexResultType.Compute);
}
// Delete
for (let i = 0; i < results.del.length; i++) {
const del = results.del[i];
const deleted = await db.run(
"DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?",
const snippets = await db.all(
"SELECT id FROM code_snippets WHERE path = ? AND cacheKey = ?",
[del.path, del.cacheKey],
);
await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [
deleted.lastID,
]);
if (snippets) {
const snippetIds = snippets.map((row) => row.id).join(",");
await db.run(`DELETE FROM code_snippets WHERE id IN (${snippetIds})`);
await db.run(
`DELETE FROM code_snippets_tags WHERE snippetId IN (${snippetIds})`,
);
}
markComplete([del], IndexResultType.Delete);
}
// Add tag
for (let i = 0; i < results.addTag.length; i++) {
const addTag = results.addTag[i];
let snippets: (ChunkWithoutID & { title: string })[] = [];
@ -220,19 +236,33 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
markComplete([results.addTag[i]], IndexResultType.AddTag);
}
// Remove tag
for (let i = 0; i < results.removeTag.length; i++) {
const item = results.removeTag[i];
await db.run(
`
DELETE FROM code_snippets_tags
WHERE tag = ?
AND snippetId IN (
SELECT id FROM code_snippets
WHERE cacheKey = ? AND path = ?
)
`,
[tagString, item.cacheKey, item.path],
const removeTag = results.removeTag[i];
let snippets = await db.get(
`SELECT id FROM code_snippets
WHERE cacheKey = ? AND path = ?`,
[removeTag.cacheKey, removeTag.path],
);
if (snippets) {
if (!Array.isArray(snippets)) {
snippets = [snippets];
}
const snippetIds = snippets.map((row: any) => row.id).join(",");
await db.run(
`
DELETE FROM code_snippets_tags
WHERE tag = ?
AND snippetId IN (${snippetIds})
`,
[tagString],
);
}
markComplete([results.removeTag[i]], IndexResultType.RemoveTag);
}
}

View file

@ -2,20 +2,20 @@ import { jest } from "@jest/globals";
import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { ContinueServerClient } from "../../continueServer/stubs/client.js";
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "../../indexing/refreshIndex.js";
import { TestCodebaseIndex } from "../../indexing/TestCodebaseIndex.js";
import { CodebaseIndex } from "../../indexing/types.js";
import { walkDir } from "../../indexing/walkDir.js";
import { getIndexSqlitePath } from "../../util/paths.js";
import { testConfigHandler, testIde } from "../fixtures.js";
import { ContinueServerClient } from "../continueServer/stubs/client.js";
import { testConfigHandler, testIde } from "../test/util/fixtures.js";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "../testUtils/testDir.js";
} from "../test/util/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
import { walkDir } from "./walkDir.js";
jest.useFakeTimers();
@ -71,6 +71,9 @@ describe("CodebaseIndexer", () => {
beforeAll(async () => {
tearDownTestDir();
setUpTestDir();
execSync('git config --global user.email "test@example.com"');
execSync('git config --global user.name "Test"');
});
afterAll(async () => {

View file

@ -1,9 +1,12 @@
import * as fs from "fs/promises";
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import {
@ -26,6 +29,24 @@ export class PauseToken {
}
export class CodebaseIndexer {
/**
* We batch for two reasons:
* - To limit memory usage for indexes that perform computations locally, e.g. FTS
* - To make as few requests as possible to the embeddings providers
*/
filesPerBatch = 1000;
// Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
// e.g. a `SQLITE_BUSY` error.
errorsRegexesToClearIndexesOn = [
/Invalid argument error: Values length (d+) is less than the length ((d+)) multiplied by the value size (d+)/,
/SQLITE_CONSTRAINT/,
/SQLITE_ERROR/,
/SQLITE_CORRUPT/,
/SQLITE_IOERR/,
/SQLITE_FULL/,
];
constructor(
private readonly configHandler: ConfigHandler,
protected readonly ide: IDE,
@ -33,6 +54,23 @@ export class CodebaseIndexer {
private readonly continueServerClient: IContinueServerClient,
) {}
async clearIndexes() {
const sqliteFilepath = getIndexSqlitePath();
const lanceDbFolder = getLanceDbPath();
try {
await fs.unlink(sqliteFilepath);
} catch (error) {
console.error(`Error deleting ${sqliteFilepath} folder: ${error}`);
}
try {
await fs.rm(lanceDbFolder, { recursive: true, force: true });
} catch (error) {
console.error(`Error deleting ${lanceDbFolder}: ${error}`);
}
}
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
const config = await this.configHandler.loadConfig();
const pathSep = await this.ide.pathSep();
@ -88,6 +126,12 @@ export class CodebaseIndexer {
results.removeTag = [];
results.addTag = [];
results.del = [];
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
if (results.compute.length === 0) {
continue;
}
for await (const _ of index.update(
tag,
results,
@ -203,7 +247,6 @@ export class CodebaseIndexer {
yield this.handleErrorAndGetProgressUpdate(err);
return;
}
completedDirs += 1;
}
yield {
progress: 100,
@ -223,24 +266,31 @@ export class CodebaseIndexer {
progress: 0,
desc: `Indexing failed: ${err}`,
status: "failed",
debugInfo: extractMinimalStackTraceInfo((err as any)?.stack),
};
}
private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
const errorRegex =
/Invalid argument error: Values length (\d+) is less than the length \((\d+)\) multiplied by the value size \(\d+\)/;
const match = err.message.match(errorRegex);
let errMsg: string;
if (match) {
const [_, valuesLength, expectedLength] = match;
errMsg = `Generated embedding had length ${valuesLength} but was expected to be ${expectedLength}. This may be solved by deleting ~/.continue/index and refreshing the window to re-index.`;
} else {
errMsg = `${err}`;
let errMsg: string = `${err}`;
let shouldClearIndexes = false;
// Check if any of the error regexes match
for (const regexStr of this.errorsRegexesToClearIndexesOn) {
const regex = new RegExp(regexStr);
const match = err.message.match(regex);
if (match !== null) {
shouldClearIndexes = true;
break;
}
}
return {
progress: 0,
desc: errMsg,
status: "failed",
shouldClearIndexes,
debugInfo: extractMinimalStackTraceInfo(err.stack),
};
}
@ -269,20 +319,14 @@ export class CodebaseIndexer {
}
}
private getBatchSize(workspaceSize: number): number {
return 100;
}
/*
* enables the indexing operation to be completed in small batches, this is important in large
* Enables the indexing operation to be completed in batches, this is important in large
* repositories where indexing can quickly use up all the memory available
*/
private *batchRefreshIndexResults(
results: RefreshIndexResults,
workspaceSize: number,
): Generator<RefreshIndexResults> {
let curPos = 0;
const batchSize = this.getBatchSize(workspaceSize);
while (
curPos < results.compute.length ||
curPos < results.del.length ||
@ -290,12 +334,12 @@ export class CodebaseIndexer {
curPos < results.removeTag.length
) {
yield {
compute: results.compute.slice(curPos, curPos + batchSize),
del: results.del.slice(curPos, curPos + batchSize),
addTag: results.addTag.slice(curPos, curPos + batchSize),
removeTag: results.removeTag.slice(curPos, curPos + batchSize),
compute: results.compute.slice(curPos, curPos + this.filesPerBatch),
del: results.del.slice(curPos, curPos + this.filesPerBatch),
addTag: results.addTag.slice(curPos, curPos + this.filesPerBatch),
removeTag: results.removeTag.slice(curPos, curPos + this.filesPerBatch),
};
curPos += batchSize;
curPos += this.filesPerBatch;
}
}
@ -333,31 +377,33 @@ export class CodebaseIndexer {
results.addTag.length +
results.removeTag.length;
let completedOps = 0;
for (const subResult of this.batchRefreshIndexResults(
results,
workspaceFiles.length,
)) {
for await (const { desc } of codebaseIndex.update(
tag,
subResult,
markComplete,
repoName,
)) {
yield {
progress: progress,
desc,
status: "indexing",
};
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
if (totalOps > 0) {
for (const subResult of this.batchRefreshIndexResults(results)) {
for await (const { desc } of codebaseIndex.update(
tag,
subResult,
markComplete,
repoName,
)) {
yield {
progress: progress,
desc,
status: "indexing",
};
}
completedOps +=
subResult.compute.length +
subResult.del.length +
subResult.addTag.length +
subResult.removeTag.length;
progress =
(completedIndexCount + completedOps / totalOps) *
(1 / indexesToBuild.length);
}
completedOps +=
subResult.compute.length +
subResult.del.length +
subResult.addTag.length +
subResult.removeTag.length;
progress =
(completedIndexCount + completedOps / totalOps) *
(1 / indexesToBuild.length);
}
await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
completedIndexCount += 1;
}

View file

@ -0,0 +1,67 @@
import { jest } from "@jest/globals";
import {
insertMockChunks,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
describe("FullTextSearchCodebaseIndex", () => {
let index: FullTextSearchCodebaseIndex;
let db: DatabaseConnection;
async function getFts() {
return await db.all("SELECT * FROM fts");
}
async function getFtsMetadata() {
return await db.all("SELECT * FROM fts_metadata");
}
beforeEach(async () => {
db = await SqliteDb.get();
index = new FullTextSearchCodebaseIndex();
});
it.skip("should update the index and maintain expected database state", async () => {
const mockMarkComplete = jest
.fn()
.mockImplementation(() => Promise.resolve()) as any;
await insertMockChunks();
// Compute test
await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete);
expect((await getFts()).length).toBe(1);
expect((await getFtsMetadata()).length).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.Compute,
);
// RemoveTag test - currently, we don't do anything other than mark complete
await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.RemoveTag,
);
// AddTag test - currently, we don't do anything other than mark complete
await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.AddTag,
);
// Delete test
await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete);
expect((await getFts()).length).toBe(0);
expect((await getFtsMetadata()).length).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.Delete,
);
});
});

View file

@ -1,23 +1,19 @@
import {
BranchAndDir,
Chunk,
IndexTag,
IndexingProgressUpdate,
} from "../index.js";
import { getBasename } from "../util/index.js";
import { RETRIEVAL_PARAMS } from "../util/parameters.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../";
import { getBasename } from "../util/index";
import { RETRIEVAL_PARAMS } from "../util/parameters";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types.js";
} from "./types";
export class FullTextSearchCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 0.2;
artifactId = "sqliteFts";
static artifactId = "sqliteFts";
artifactId: string = ChunkCodebaseIndex.artifactId;
private async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(
@ -90,11 +86,12 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
const { lastID } = await db.run(
"DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?",
[item.path, item.cacheKey],
);
await db.run("DELETE FROM fts WHERE rowid = ?", [lastID]);
await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
item.path,
item.cacheKey,
]);
await db.run("DELETE FROM fts WHERE path = ?", [item.path]);
markComplete([item], IndexResultType.Delete);
}

View file

@ -0,0 +1,115 @@
import { jest } from "@jest/globals";
import lance from "vectordb";
import { testConfigHandler, testIde } from "../test/util/fixtures";
import {
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
import { getLanceDbPath } from "../util/paths";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
jest.useFakeTimers();
describe("ChunkCodebaseIndex", () => {
let index: LanceDbIndex;
let sqliteDb: DatabaseConnection;
let lanceDb: lance.Connection;
async function getAllSqliteLanceDbCache() {
return await sqliteDb.all("SELECT * FROM lance_db_cache");
}
beforeAll(async () => {
const pathSep = await testIde.pathSep();
const mockConfig = await testConfigHandler.loadConfig();
index = new LanceDbIndex(
mockConfig.embeddingsProvider,
testIde.readFile.bind(testIde),
pathSep,
testContinueServerClient,
);
sqliteDb = await SqliteDb.get();
lanceDb = await lance.connect(getLanceDbPath());
});
/**
* Some notes on quirks of this test:
* - Currently, it appears that there is a race condition in LanceDB that
* requires us to re-open the table connection each time we want to read
* from it. Attempting to follow these docs did not resolve the issue:
* https://lancedb.github.io/lancedb/guides/tables/#consistency
*
* - We cannot open either the 'dev' or 'main' tag tables ubtil after we
* can assume they've been created through `updateIndexAndAwaitGenerator`
*/
it.skip("should update the index and maintain expected database state", async () => {
const mainTag = mockTag;
const mainTagTableName = index.tableNameForTag(mainTag);
const devTag = { ...mockTag, branch: "dev" };
const devTagTableName = index.tableNameForTag(devTag);
const mockMarkComplete = jest
.fn()
.mockImplementation(() => Promise.resolve()) as any;
// Compute test - inserts into both LanceDB and Sqlite
await updateIndexAndAwaitGenerator(
index,
"compute",
mockMarkComplete,
mainTag,
);
let mainTagTable = await lanceDb.openTable(mainTagTableName);
expect(await mainTagTable.countRows()).toBe(1);
expect((await getAllSqliteLanceDbCache()).length).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.Compute,
);
// AddTag test - only inserts into Lance DB
await updateIndexAndAwaitGenerator(
index,
"addTag",
mockMarkComplete,
devTag,
);
let devTagTable = await lanceDb.openTable(devTagTableName);
expect(await devTagTable.countRows()).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.AddTag,
);
// RemoveTag - only removes from Lance DB
await updateIndexAndAwaitGenerator(
index,
"removeTag",
mockMarkComplete,
devTag,
);
devTagTable = await lanceDb.openTable(devTagTableName);
expect(await devTagTable.countRows()).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.RemoveTag,
);
// Delete test - removes from LanceDB and Sqlite
await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete, mainTag);
mainTagTable = await lanceDb.openTable(mainTagTableName);
expect(await mainTagTable.countRows()).toBe(0);
expect((await getAllSqliteLanceDbCache()).length).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.Delete,
);
});
});

View file

@ -1,7 +1,7 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { RunResult } from "sqlite3";
import { v4 as uuidv4 } from "uuid";
import { Table } from "vectordb";
import lance, { Table } from "vectordb";
import { IContinueServerClient } from "../continueServer/interface.js";
import {
BranchAndDir,
@ -31,6 +31,10 @@ interface LanceDbRow {
[key: string]: any;
}
type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] };
type ChunkMap = Map<string, ItemWithChunks>;
export class LanceDbIndex implements CodebaseIndex {
relativeExpectedTime: number = 13;
get artifactId(): string {
@ -44,7 +48,7 @@ export class LanceDbIndex implements CodebaseIndex {
private readonly continueServerClient?: IContinueServerClient,
) {}
private tableNameForTag(tag: IndexTag) {
tableNameForTag(tag: IndexTag) {
return tagToString(tag).replace(/[^\w-_.]/g, "");
}
@ -85,77 +89,112 @@ export class LanceDbIndex implements CodebaseIndex {
);
}
private async packToRows(item: PathAndCacheKey): Promise<LanceDbRow[]> {
const content = await this.readFile(item.path);
if (!shouldChunk(this.pathSep, item.path, content)) {
return [];
private async computeRows(items: PathAndCacheKey[]): Promise<LanceDbRow[]> {
const chunkMap = await this.collectChunks(items);
const allChunks = Array.from(chunkMap.values()).flatMap(
({ chunks }) => chunks,
);
const embeddings = await this.getEmbeddings(allChunks);
// Remove undefined embeddings and their corresponding chunks
for (let i = embeddings.length - 1; i >= 0; i--) {
if (embeddings[i] === undefined) {
const chunk = allChunks[i];
const chunks = chunkMap.get(chunk.filepath)?.chunks;
if (chunks) {
const index = chunks.findIndex((c) => c === chunk);
if (index !== -1) {
chunks.splice(index, 1);
}
}
embeddings.splice(i, 1);
}
}
return this.createLanceDbRows(chunkMap, embeddings);
}
private async collectChunks(items: PathAndCacheKey[]): Promise<ChunkMap> {
const chunkMap: ChunkMap = new Map();
for (const item of items) {
try {
const content = await this.readFile(item.path);
if (!shouldChunk(this.pathSep, item.path, content)) {
continue;
}
const chunks = await this.getChunks(item, content);
chunkMap.set(item.path, { item, chunks });
} catch (err) {
console.log(`LanceDBIndex, skipping ${item.path}: ${err}`);
}
}
return chunkMap;
}
private async getChunks(
item: PathAndCacheKey,
content: string,
): Promise<Chunk[]> {
const chunks: Chunk[] = [];
const chunkParams = {
filepath: item.path,
contents: content,
maxChunkSize: this.embeddingsProvider.maxChunkSize,
digest: item.cacheKey,
};
for await (const chunk of chunkDocument(chunkParams)) {
if (chunk.content.length === 0) {
// File did not chunk properly, let's skip it.
throw new Error("did not chunk properly");
}
chunks.push(chunk);
}
const embeddings = await this.chunkListToEmbedding(chunks);
if (chunks.length !== embeddings.length) {
throw new Error(
`Unexpected lengths: chunks and embeddings do not match for ${item.path}`,
);
}
const results = [];
for (let i = 0; i < chunks.length; i++) {
results.push({
path: item.path,
cachekey: item.cacheKey,
uuid: uuidv4(),
vector: embeddings[i],
startLine: chunks[i].startLine,
endLine: chunks[i].endLine,
contents: chunks[i].content,
});
}
return results;
return chunks;
}
private async chunkListToEmbedding(chunks: Chunk[]): Promise<number[][]> {
let embeddings: number[][];
private async getEmbeddings(chunks: Chunk[]): Promise<number[][]> {
try {
embeddings = await this.embeddingsProvider.embed(
chunks.map((c) => c.content),
);
return await this.embeddingsProvider.embed(chunks.map((c) => c.content));
} catch (err) {
throw new Error(
`Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}: ${err}`,
`Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.id}: ${err}`,
{ cause: err },
);
}
if (embeddings.some((emb) => emb === undefined)) {
throw new Error(
`Empty embedding returned for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}`,
);
}
return embeddings;
}
private async computeRows(items: PathAndCacheKey[]): Promise<LanceDbRow[]> {
const rowChunkPromises = items.map(this.packToRows.bind(this));
const rowChunkLists = [];
for (let i = 0; i < items.length; i++) {
try {
rowChunkLists.push(await rowChunkPromises[i]);
} catch (err) {
console.log(`LanceDBIndex, skipping ${items[i].path}: ${err}`);
private createLanceDbRows(
chunkMap: ChunkMap,
embeddings: number[][],
): LanceDbRow[] {
const results: LanceDbRow[] = [];
let embeddingIndex = 0;
for (const [path, { item, chunks }] of chunkMap) {
for (const chunk of chunks) {
results.push({
path,
cachekey: item.cacheKey,
uuid: uuidv4(),
vector: embeddings[embeddingIndex],
startLine: chunk.startLine,
endLine: chunk.endLine,
contents: chunk.content,
});
embeddingIndex++;
}
}
return rowChunkLists.flat();
return results;
}
async *update(
@ -164,40 +203,39 @@ export class LanceDbIndex implements CodebaseIndex {
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const lancedb = await import("vectordb");
const tableName = this.tableNameForTag(tag);
const db = await lancedb.connect(getLanceDbPath());
const sqliteDb = await SqliteDb.get();
await this.createSqliteCacheTable(sqliteDb);
const sqlite = await SqliteDb.get();
await this.createSqliteCacheTable(sqlite);
const lanceTableName = this.tableNameForTag(tag);
const lanceDb = await lance.connect(getLanceDbPath());
const existingLanceTables = await lanceDb.tableNames();
let lanceTable: Table<number[]> | undefined = undefined;
let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName);
// Compute
let table: Table<number[]> | undefined = undefined;
const existingTables = await db.tableNames();
let needToCreateTable = !existingTables.includes(tableName);
const addComputedLanceDbRows = async (
pathAndCacheKey: PathAndCacheKey,
pathAndCacheKeys: PathAndCacheKey[],
computedRows: LanceDbRow[],
) => {
// Create table if needed, add computed rows
if (table) {
if (lanceTable) {
if (computedRows.length > 0) {
await table.add(computedRows);
await lanceTable.add(computedRows);
}
} else if (existingTables.includes(tableName)) {
table = await db.openTable(tableName);
needToCreateTable = false;
} else if (existingLanceTables.includes(lanceTableName)) {
lanceTable = await lanceDb.openTable(lanceTableName);
needToCreateLanceTable = false;
if (computedRows.length > 0) {
await table.add(computedRows);
await lanceTable.add(computedRows);
}
} else if (computedRows.length > 0) {
table = await db.createTable(tableName, computedRows);
needToCreateTable = false;
lanceTable = await lanceDb.createTable(lanceTableName, computedRows);
needToCreateLanceTable = false;
}
// Mark item complete
await markComplete([pathAndCacheKey], IndexResultType.Compute);
await markComplete(pathAndCacheKeys, IndexResultType.Compute);
};
// Check remote cache
@ -233,7 +271,7 @@ export class LanceDbIndex implements CodebaseIndex {
};
rows.push(row);
await sqlite.run(
await sqliteDb.run(
"INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
row.uuid,
row.cachekey,
@ -246,7 +284,7 @@ export class LanceDbIndex implements CodebaseIndex {
);
}
await addComputedLanceDbRows({ cacheKey, path }, rows);
await addComputedLanceDbRows([{ cacheKey, path }], rows);
}
// Remove items that don't need to be recomputed
@ -267,21 +305,13 @@ export class LanceDbIndex implements CodebaseIndex {
};
const dbRows = await this.computeRows(results.compute);
await this.insertRows(sqlite, dbRows);
await Promise.all(
results.compute.map((item) => {
addComputedLanceDbRows(
item,
dbRows.filter((row) => row.path === item.path),
);
}),
);
await markComplete(results.compute, IndexResultType.Compute);
await this.insertRows(sqliteDb, dbRows);
await addComputedLanceDbRows(results.compute, dbRows);
let accumulatedProgress = 0;
// Add tag - retrieve the computed info from lance sqlite cache
for (const { path, cacheKey } of results.addTag) {
const stmt = await sqlite.prepare(
const stmt = await sqliteDb.prepare(
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
cacheKey,
path,
@ -289,25 +319,28 @@ export class LanceDbIndex implements CodebaseIndex {
);
const cachedItems = await stmt.all();
const lanceRows: LanceDbRow[] = cachedItems.map((item) => {
return {
const lanceRows: LanceDbRow[] = cachedItems.map(
({ uuid, vector, startLine, endLine, contents }) => ({
path,
uuid,
startLine,
endLine,
contents,
cachekey: cacheKey,
uuid: item.uuid,
vector: JSON.parse(item.vector),
};
});
vector: JSON.parse(vector),
}),
);
if (lanceRows.length > 0) {
if (needToCreateTable) {
table = await db.createTable(tableName, lanceRows);
needToCreateTable = false;
} else if (!table) {
table = await db.openTable(tableName);
needToCreateTable = false;
await table.add(lanceRows);
if (needToCreateLanceTable) {
lanceTable = await lanceDb.createTable(lanceTableName, lanceRows);
needToCreateLanceTable = false;
} else if (!lanceTable) {
lanceTable = await lanceDb.openTable(lanceTableName);
needToCreateLanceTable = false;
await lanceTable.add(lanceRows);
} else {
await table?.add(lanceRows);
await lanceTable?.add(lanceRows);
}
}
@ -321,11 +354,18 @@ export class LanceDbIndex implements CodebaseIndex {
}
// Delete or remove tag - remove from lance table)
if (!needToCreateTable) {
if (!needToCreateLanceTable) {
const toDel = [...results.removeTag, ...results.del];
if (!lanceTable) {
lanceTable = await lanceDb.openTable(lanceTableName);
}
for (const { path, cacheKey } of toDel) {
// This is where the aforementioned lowercase conversion problem shows
await table?.delete(`cachekey = '${cacheKey}' AND path = '${path}'`);
await lanceTable.delete(
`cachekey = '${cacheKey}' AND path = '${path}'`,
);
accumulatedProgress += 1 / toDel.length / 3;
yield {
@ -335,11 +375,12 @@ export class LanceDbIndex implements CodebaseIndex {
};
}
}
await markComplete(results.removeTag, IndexResultType.RemoveTag);
// Delete - also remove from sqlite cache
for (const { path, cacheKey } of results.del) {
await sqlite.run(
await sqliteDb.run(
"DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
cacheKey,
path,
@ -354,6 +395,7 @@ export class LanceDbIndex implements CodebaseIndex {
}
await markComplete(results.del, IndexResultType.Delete);
yield {
progress: 1,
desc: "Completed Calculating Embeddings",
@ -375,8 +417,7 @@ export class LanceDbIndex implements CodebaseIndex {
return [];
}
const table = await db.openTable(tableName);
let query = table.search(vector);
let query = db.search(vector);
if (directory) {
// seems like lancedb is only post-filtering, so have to return a bunch of results and slice after
query = query.where(`path LIKE '${directory}%'`).limit(300);
@ -393,12 +434,8 @@ export class LanceDbIndex implements CodebaseIndex {
tags: BranchAndDir[],
filterDirectory: string | undefined,
): Promise<Chunk[]> {
const lancedb = await import("vectordb");
if (!lancedb.connect) {
throw new Error("LanceDB failed to load a native module");
}
const [vector] = await this.embeddingsProvider.embed([query]);
const db = await lancedb.connect(getLanceDbPath());
const db = await lance.connect(getLanceDbPath());
let allResults = [];
for (const tag of tags) {
@ -481,9 +518,10 @@ export class LanceDbIndex implements CodebaseIndex {
{ cause: err },
),
);
} else {
resolve();
}
});
resolve();
});
});
}

View file

@ -23,8 +23,8 @@ All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./
`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
`FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5
`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex`
`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite
`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.
## Known problems:
## Known problems
- `FullTextSearchCodebaseIndex` doesn't differentiate between tags (branch, repo), so results may come from any branch/repo. LanceDB does this by creating separate tables for each tag (see `tableNameForTag`). The chunk index does this with a second table

View file

@ -35,14 +35,14 @@ export class TestCodebaseIndex implements CodebaseIndex {
for (const item of [...results.compute, ...results.addTag]) {
await db.run(
`INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)`,
"INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)",
[item.path, tag.branch, tag.directory],
);
}
for (const item of [...results.del, ...results.removeTag]) {
await db.run(
`DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?`,
"DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?",
[item.path, tag.branch, tag.directory],
);
}

View file

@ -0,0 +1,83 @@
import { jest } from "@jest/globals";
import { testIde } from "../../test/util/fixtures";
import {
mockFileContents,
mockFilename,
mockPathAndCacheKey,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "../../test/util/indexing";
import { addToTestDir } from "../../test/util/testDir";
import { DatabaseConnection, SqliteDb } from "../refreshIndex";
import { IndexResultType } from "../types";
import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex";
jest.useFakeTimers();
describe("ChunkCodebaseIndex", () => {
let index: ChunkCodebaseIndex;
let db: DatabaseConnection;
async function getAllChunks() {
return await db.all("SELECT * FROM chunks");
}
async function getAllChunkTags() {
return await db.all("SELECT * FROM chunk_tags");
}
beforeAll(async () => {
const pathSep = await testIde.pathSep();
index = new ChunkCodebaseIndex(
testIde.readFile.bind(testIde),
pathSep,
testContinueServerClient,
1000,
);
addToTestDir([[mockFilename, mockFileContents]]);
db = await SqliteDb.get();
});
it.skip("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => {
const mockMarkComplete = jest
.fn()
.mockImplementation(() => Promise.resolve()) as any;
// Compute test
await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete);
expect((await getAllChunks()).length).toBe(1);
expect((await getAllChunkTags()).length).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.Compute,
);
// RemoveTag test
await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete);
expect((await getAllChunkTags()).length).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.RemoveTag,
);
// AddTag test
await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete);
expect((await getAllChunkTags()).length).toBe(1);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.AddTag,
);
// Delete test
await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete);
expect((await getAllChunks()).length).toBe(0);
expect((await getAllChunkTags()).length).toBe(0);
expect(mockMarkComplete).toHaveBeenCalledWith(
[mockPathAndCacheKey],
IndexResultType.Delete,
);
});
});

View file

@ -1,8 +1,8 @@
import * as path from "path";
import { RunResult } from "sqlite3";
import { IContinueServerClient } from "../../continueServer/interface.js";
import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
import { getBasename } from "../../util/index.js";
import { getLanguageForFile } from "../../util/treeSitter.js";
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js";
import {
IndexResultType,
@ -61,8 +61,11 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
let accumulatedProgress = 0;
if (results.compute.length > 0) {
const filepath = results.compute[0].path;
const folderName = path.basename(path.dirname(filepath));
yield {
desc: `Chunking ${results.compute.length} ${this.formatListPlurality("file", results.compute.length)}`,
desc: `Chunking files in ${folderName}`,
status: "indexing",
progress: accumulatedProgress,
};
@ -114,14 +117,21 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
const deleted = await db.run("DELETE FROM chunks WHERE cacheKey = ?", [
item.cacheKey,
]);
const chunkToDelete = await db.get(
"SELECT id FROM chunks WHERE cacheKey = ?",
[item.cacheKey],
);
// Delete from chunk_tags
await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [
deleted.lastID,
]);
if (chunkToDelete) {
await db.run("DELETE FROM chunks WHERE id = ?", [chunkToDelete.id]);
// Delete from chunk_tags
await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [
chunkToDelete.id,
]);
} else {
console.debug("Chunk to delete wasn't found in the table: ", item.path);
}
await markComplete([item], IndexResultType.Delete);
accumulatedProgress += 1 / results.del.length / 4;
@ -133,7 +143,6 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
}
}
private async createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@ -172,11 +181,17 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
}
private async computeChunks(paths: PathAndCacheKey[]): Promise<Chunk[]> {
const chunkLists = await Promise.all(paths.map(p => this.packToChunks(p)));
const chunkLists = await Promise.all(
paths.map((p) => this.packToChunks(p)),
);
return chunkLists.flat();
}
private async insertChunks(db: DatabaseConnection, tagString: string, chunks: Chunk[]) {
private async insertChunks(
db: DatabaseConnection,
tagString: string,
chunks: Chunk[],
) {
await new Promise<void>((resolve, reject) => {
db.db.serialize(() => {
db.db.exec("BEGIN", (err: Error | null) => {
@ -184,31 +199,50 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
reject(new Error("error creating transaction", { cause: err }));
}
});
const chunksSQL = "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)";
chunks.map(c => {
db.db.run(chunksSQL, [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content], (result: RunResult, err: Error) => {
if (err) {
reject(new Error("error inserting into chunks table", { cause: err }));
}
});
const chunkTagsSQL = "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)";
db.db.run(chunkTagsSQL, [ tagString ], (result: RunResult, err: Error) => {
if (err) {
reject(new Error("error inserting into chunk_tags table", { cause: err }));
}
});
const chunksSQL =
"INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)";
chunks.map((c) => {
db.db.run(
chunksSQL,
[c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content],
(result: RunResult, err: Error) => {
if (err) {
reject(
new Error("error inserting into chunks table", {
cause: err,
}),
);
}
},
);
const chunkTagsSQL =
"INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)";
db.db.run(
chunkTagsSQL,
[tagString],
(result: RunResult, err: Error) => {
if (err) {
reject(
new Error("error inserting into chunk_tags table", {
cause: err,
}),
);
}
},
);
});
db.db.exec("COMMIT", (err: Error | null) => {
if (err) {
reject(new Error("error while committing insert chunks transaction", { cause: err }));
reject(
new Error("error while committing insert chunks transaction", {
cause: err,
}),
);
} else {
resolve();
}
});
resolve();
});
});
}
private formatListPlurality(word: string, length: number): string {
return length <= 1 ? word : `${word}s`;
}
}

View file

@ -1,5 +1,5 @@
import path from "path";
import { shouldChunk } from "../../../indexing/chunk/chunk";
import { shouldChunk } from "./chunk";
describe("shouldChunk", () => {
test("should chunk a typescript file", () => {

View file

@ -1,5 +1,5 @@
import { ChunkWithoutID } from "../../../index.js";
import { codeChunker } from "../../../indexing/chunk/code.js";
import { ChunkWithoutID } from "../..";
import { codeChunker } from "./code";
async function genToArr<T>(generator: AsyncGenerator<T>): Promise<T[]> {
const result: T[] = [];
@ -29,7 +29,7 @@ describe.skip("codeChunker", () => {
test("should capture small class and function from large python file", async () => {
const extraLine = "# This is a comment";
const myClass = "class MyClass:\n def __init__(self):\n pass";
const myFunction = 'def my_function():\n return "Hello, World!"';
const myFunction = "def my_function():\n return \"Hello, World!\"";
const file =
Array(100).fill(extraLine).join("\n") +
@ -66,7 +66,7 @@ describe.skip("codeChunker", () => {
chunks[0].startsWith("class MyClass:\n def method1():\n ..."),
).toBe(true);
// The extra spaces seem to be a bug with tree-sitter-python
expect(chunks).toContain('def method1():\n return "Hello, 1!"');
expect(chunks).toContain('def method20():\n return "Hello, 20!"');
expect(chunks).toContain("def method1():\n return \"Hello, 1!\"");
expect(chunks).toContain("def method20():\n return \"Hello, 20!\"");
});
});

View file

@ -0,0 +1,130 @@
import DocsCrawler, { type PageData } from "./DocsCrawler";
import preIndexedDocs from "./preIndexedDocs";
// Temporary workaround until we have better caching of Chromium
// download between test runs
const TIMEOUT = 1_000_000;
// Skipped until we have a better way to cache Chromium installs
// between tests and in CI
describe.skip("crawl", () => {
describe("GitHub repositories", () => {
const repoUrl =
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
let crawlResults: PageData[];
beforeAll(async () => {
const docsCrawler = new DocsCrawler(new URL(repoUrl));
crawlResults = [];
for await (const page of docsCrawler.crawl()) {
crawlResults.push(page);
}
}, TIMEOUT);
test("finds expected markdown files", async () => {
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
true,
);
expect(
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
).toBe(true);
});
test("html includes the correct content", async () => {
const doc = crawlResults.find((page) =>
page.path.endsWith("docs-depth-1.md"),
);
expect(doc?.content.includes("Test body")).toBe(true);
expect(doc?.content.includes("Test H2 Header")).toBe(true);
});
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
false,
);
});
});
describe.only("Non-Github repository sites", () => {
it(
"succeeds in crawling a list of common sites",
async () => {
const TEST_SITES = [
"https://docs.nestjs.com/",
"https://docs.nestjs.com/",
"https://go.dev/doc/",
"https://clickhouse.com/docs",
"https://www.tensorflow.org/api_docs",
"https://www.rust-lang.org/learn",
"https://docs.anthropic.com/en/docs",
];
const NUM_PAGES_TO_CRAWL = 10;
for (const site of TEST_SITES) {
const crawlResults: PageData[] = [];
const docsCrawler = new DocsCrawler(
new URL(site),
NUM_PAGES_TO_CRAWL,
);
for await (const page of docsCrawler.crawl()) {
crawlResults.push(page);
}
// `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee
// an exact number of pages to crawl since it runs in parallel
expect(crawlResults.length).toBeGreaterThanOrEqual(
NUM_PAGES_TO_CRAWL,
);
}
},
TIMEOUT,
);
});
describe("Pre-indexed Docs", () => {
const results: { [url: string]: boolean } = {};
let totalTests = 0;
let passedTests = 0;
Object.keys(preIndexedDocs).forEach((url) => {
test(
`Crawl test for ${url}`,
async () => {
totalTests++;
let pageFound = false;
try {
const docsCrawler = new DocsCrawler(new URL(url), 1);
for await (const page of docsCrawler.crawl()) {
if (page.url === url) {
pageFound = true;
break;
}
}
} catch (error) {
console.error(`Error crawling ${url}:`, error);
}
results[url] = pageFound;
if (pageFound) {
passedTests++;
console.log(`✅ ${url}`);
} else {
console.log(`❌ ${url}`);
}
expect(pageFound).toBe(true);
},
TIMEOUT,
);
});
});
});

View file

@ -0,0 +1,248 @@
import { Octokit } from "@octokit/rest";
import * as fs from "fs";
import { URL } from "node:url";
import { Page } from "puppeteer";
import { getChromiumPath, getContinueUtilsPath } from "../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
export type PageData = {
url: string;
path: string;
content: string;
};
export default class DocsCrawler {
LINK_GROUP_SIZE = 2; // Controls parallelization of crawler
GITHUB_HOST = "github.com";
static MAX_REQUESTS_PER_CRAWL = 1000;
markdownRegex = new RegExp(/\.(md|mdx)$/);
octokit = new Octokit({
auth: undefined,
});
static PCR_CONFIG = {
downloadPath: getContinueUtilsPath(),
};
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number = DocsCrawler.MAX_REQUESTS_PER_CRAWL,
) {}
static verifyOrInstallChromium() {
if (!fs.existsSync(getChromiumPath())) {
PCR(DocsCrawler.PCR_CONFIG);
}
}
async *crawl(): AsyncGenerator<PageData> {
if (this.startUrl.host === this.GITHUB_HOST) {
yield* this.crawlGithubRepo();
} else {
yield* this.crawlSite();
}
}
private async getGithubRepoDefaultBranch(
owner: string,
repo: string,
): Promise<string> {
const repoInfo = await this.octokit.repos.get({
owner,
repo,
});
return repoInfo.data.default_branch;
}
private async getGitHubRepoPaths(
owner: string,
repo: string,
branch: string,
) {
const tree = await this.octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: branch,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
recursive: "true",
},
);
const paths = tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
return paths;
}
private async getGithubRepoFileContent(
path: string,
owner: string,
repo: string,
) {
try {
const response = await this.octokit.repos.getContent({
owner,
repo,
path,
headers: {
Accept: "application/vnd.github.raw+json",
},
});
return response.data as unknown as string;
} catch (error) {
console.debug("Error fetching file contents:", error);
return null;
}
}
private async *crawlGithubRepo() {
console.debug(`Crawling GitHub repo: ${this.startUrl.toString()}`);
const urlStr = this.startUrl.toString();
const [_, owner, repo] = this.startUrl.pathname.split("/");
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
for await (const path of paths) {
const content = await this.getGithubRepoFileContent(path, owner, repo);
yield {
path,
url: urlStr,
content: content ?? "",
};
}
}
private stripHashFromUrl(urlStr: string) {
try {
let url = new URL(urlStr);
url.hash = "";
return url;
} catch (err) {
return null;
}
}
private isValidHostAndPath(newUrl: URL, curUrl: URL) {
return (
newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host
);
}
private async getLinksFromPage(page: Page, curUrl: URL) {
const links = await page.$$eval("a", (links) => links.map((a) => a.href));
// This additional step is due to issues getting the URL module to work
// in an $$eval command
const cleanedLinks = links
.map(this.stripHashFromUrl)
.filter(
(newUrl) =>
newUrl !== null &&
this.isValidHostAndPath(newUrl, curUrl) &&
newUrl !== curUrl,
)
.map((newUrl) => (newUrl as URL).href);
const dedupedLinks = Array.from(new Set(cleanedLinks));
return dedupedLinks;
}
private async getLinkGroupsFromPage(page: Page, curUrl: URL) {
const links = await this.getLinksFromPage(page, curUrl);
const groups = links.reduce((acc, link, i) => {
const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE);
if (!acc[groupIndex]) {
acc.push([]);
}
acc[groupIndex].push(link);
return acc;
}, [] as string[][]);
return groups;
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
curRequestCount: number = 0,
): AsyncGenerator<PageData> {
if (curRequestCount >= this.maxRequestsPerCrawl) {
console.warn("Max requests per crawl reached. Stopping crawler.");
return;
}
if (visitedLinks.has(curUrl.toString())) {
return;
}
console.debug(`Crawling page: ${curUrl.toString()}`);
await page.goto(curUrl.toString());
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
const requestCount = curRequestCount + 1;
visitedLinks.add(curUrl.toString());
yield {
path: curUrl.pathname,
url: curUrl.toString(),
content: htmlContent,
};
for (const linkGroup of linkGroups) {
for (const link of linkGroup) {
yield* this.crawlSitePages(
page,
new URL(link),
visitedLinks,
requestCount,
);
}
}
}
private async *crawlSite(): AsyncGenerator<PageData> {
console.debug(`Crawling site repo: ${this.startUrl}`);
const stats = await PCR(DocsCrawler.PCR_CONFIG);
const browser = await stats.puppeteer.launch({
args: [
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
],
executablePath: stats.executablePath,
});
const page = await browser.newPage();
try {
yield* this.crawlSitePages(page, this.startUrl);
} catch (e) {
console.debug("Error getting links: ", e);
} finally {
await browser.close();
}
}
}

View file

@ -1,16 +1,14 @@
/**
* @jest-environment jsdom
*/
import * as fs from "fs";
import * as path from "path";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { SiteIndexingConfig } from "../../index.js";
import DocsService from "../../indexing/docs/DocsService.js";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js";
import FreeTrialEmbeddingsProvider from "../../indexing/embeddings/FreeTrialEmbeddingsProvider.js";
import DocsService from "./DocsService.js";
import preIndexedDocs from "./preIndexedDocs.js";
import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js";
import FileSystemIde from "../../util/filesystem.js";
import { editConfigJson, getConfigJsonPath } from "../../util/paths.js";
import { editConfigJson } from "../../util/paths.js";
describe.skip("DocsService Integration Tests", () => {
let ide: FileSystemIde;
@ -23,13 +21,6 @@ describe.skip("DocsService Integration Tests", () => {
faviconUrl: "https://github.com/favicon.ico",
};
async function clearConfigDir() {
const configFolder = path.dirname(getConfigJsonPath());
if (fs.existsSync(configFolder)) {
fs.rmSync(configFolder, { recursive: true, force: true });
}
}
/**
* We need to reload config explicitly to handle the scenario where the
* config file update listeners are not called before we attempt to
@ -43,8 +34,6 @@ describe.skip("DocsService Integration Tests", () => {
}
beforeEach(async () => {
await clearConfigDir();
ide = new FileSystemIde(process.cwd());
configHandler = new ConfigHandler(
@ -75,10 +64,6 @@ describe.skip("DocsService Integration Tests", () => {
await docsService.isInitialized;
});
afterAll(async () => {
await clearConfigDir();
});
test("Indexing, retrieval, and deletion of a new documentation site", async () => {
const generator = docsService.indexAndAdd(mockSiteConfig);
while (!(await generator.next()).done) {}

View file

@ -1,8 +1,8 @@
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import DocsContextProvider from "../../context/providers/DocsContextProvider.js";
import { ConfigHandler } from "../../config/ConfigHandler";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import {
Chunk,
ContinueConfig,
@ -10,27 +10,27 @@ import {
IDE,
IndexingProgressUpdate,
SiteIndexingConfig,
} from "../../index.js";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol/index.js";
import { GlobalContext } from "../../util/GlobalContext.js";
import { IMessenger } from "../../util/messenger.js";
} from "../..";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { GlobalContext } from "../../util/GlobalContext";
import { IMessenger } from "../../util/messenger";
import {
editConfigJson,
getDocsSqlitePath,
getLanceDbPath,
} from "../../util/paths.js";
import { Telemetry } from "../../util/posthog.js";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js";
import { Article, chunkArticle, pageToArticle } from "./article.js";
import { crawlPage } from "./crawl.js";
import { runLanceMigrations, runSqliteMigrations } from "./migrations.js";
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider";
import { Article, chunkArticle, pageToArticle } from "./article";
import DocsCrawler from "./DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import {
downloadFromS3,
getS3Filename,
S3Buckets,
SiteIndexingResults,
} from "./preIndexed.js";
import preIndexedDocs from "./preIndexedDocs.js";
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -112,8 +112,8 @@ export default class DocsService {
}
/*
* Currently, we generate and host embeddings for pre-indexed docs using transformers.js.
* However, we don't ship transformers.js with the JetBrains extension.
* 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() {
@ -202,11 +202,10 @@ export default class DocsService {
let processedPages = 0;
let maxKnownPages = 1;
const docsCrawler = new DocsCrawler(new URL(startUrl));
// Crawl pages and retrieve info as articles
for await (const page of crawlPage(
new URL(startUrl),
siteIndexingConfig.maxDepth,
)) {
for await (const page of docsCrawler.crawl()) {
processedPages++;
const article = pageToArticle(page);
@ -279,6 +278,8 @@ export default class DocsService {
status: "failed",
};
this.docsIndexingQueue.delete(startUrl);
return;
}
@ -291,8 +292,8 @@ export default class DocsService {
status: "indexing",
};
// Clear old index if re-indexing.
if (reIndex) {
// Delete indexed docs if re-indexing
if (reIndex && await this.has(startUrl.toString())) {
console.log("Deleting old embeddings");
await this.delete(startUrl);
}
@ -521,8 +522,9 @@ export default class DocsService {
private async getLanceTableNameFromEmbeddingsProvider(
isPreIndexedDoc: boolean,
) {
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
const embeddingsProvider = await this.getEmbeddingsProvider(
isPreIndexedDoc,
);
const embeddingsProviderId = this.removeInvalidLanceTableNameChars(
embeddingsProvider.id,
);
@ -722,12 +724,13 @@ export default class DocsService {
await this.isJetBrainsAndPreIndexedDocsProvider();
if (isJetBrainsAndPreIndexedDocsProvider) {
this.ide.errorPopup(
"The 'transformers.js' embeddings provider currently cannot be used to index " +
"documentation in JetBrains. To enable documentation indexing, you can use " +
"any of the other providers described in the docs: " +
"https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers",
);
// A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider
// this.ide.errorPopup(
// "The 'transformers.js' embeddings provider currently cannot be used to index " +
// "documentation in JetBrains. To enable documentation indexing, you can use " +
// "any of the other providers described in the docs: " +
// "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers",
// );
this.globalContext.update(
"curEmbeddingsProviderId",

View file

@ -1,8 +1,8 @@
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { Chunk } from "../../index.js";
import { cleanFragment, cleanHeader } from "../chunk/markdown.js";
import { PageData } from "./crawl.js";
import { Chunk } from "../../";
import { cleanFragment, cleanHeader } from "../chunk/markdown";
import { type PageData } from "./DocsCrawler";
export type ArticleComponent = {
title: string;
@ -148,7 +148,7 @@ export function stringToArticle(
export function pageToArticle(page: PageData): Article | undefined {
try {
return stringToArticle(page.url, page.html, page.path);
return stringToArticle(page.url, page.content, page.path);
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;

View file

@ -1,212 +0,0 @@
import { Octokit } from "@octokit/rest";
import cheerio from "cheerio";
import fetch from "node-fetch";
import { URL } from "node:url";
const IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
"genindex",
"py-modindex",
"search.html",
"search",
"genindex.html",
"changelog",
"changelog.html",
];
const markdownRegex = new RegExp(/\.(md|mdx)$/);
async function getDefaultBranch(owner: string, repo: string): Promise<string> {
const octokit = new Octokit({ auth: undefined });
const repoInfo = await octokit.repos.get({
owner,
repo,
});
return repoInfo.data.default_branch;
}
async function crawlGithubRepo(baseUrl: URL) {
const octokit = new Octokit({
auth: undefined,
});
const [_, owner, repo] = baseUrl.pathname.split("/");
const branch = await getDefaultBranch(owner, repo);
console.log("Github repo detected. Crawling", branch, "branch");
const tree = await octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: branch,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
recursive: "true",
},
);
const paths = tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && markdownRegex.test(file.path ?? ""),
)
.map((file: any) => baseUrl.pathname + "/tree/main/" + file.path);
return paths;
}
async function getLinksFromUrl(url: string, path: string) {
const baseUrl = new URL(url);
const location = new URL(path, url);
let response;
try {
response = await fetch(location.toString());
} catch (error: unknown) {
if (error instanceof Error && error.message.includes("maximum redirect")) {
console.error("Maximum redirect reached for: ", location.toString());
return {
html: "",
links: [],
};
}
console.error(error);
return {
html: "",
links: [],
};
}
const html = await response.text();
let links: string[] = [];
if (url.includes("github.com")) {
return {
html,
links,
};
}
const $ = cheerio.load(html);
$("a").each((_, element) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, url);
if (
parsedUrl.hostname === baseUrl.hostname
// parsedUrl.pathname.startsWith(baseUrl.pathname)
) {
links.push(parsedUrl.pathname);
}
});
links = [...new Set(links)].filter((link) => {
return (
!link.includes("#") &&
!IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
);
});
return {
html,
links,
};
}
function splitUrl(url: URL) {
const baseUrl = `${url.protocol}//${url.hostname}${
url.port ? ":" + url.port : ""
}`;
const basePath = url.pathname;
return {
baseUrl,
basePath,
};
}
export type PageData = {
url: string;
path: string;
html: string;
};
export async function* crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log(
`Starting crawl from: ${url.toString()} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = splitUrl(url);
let paths: { path: string; depth: number }[] = [{ path: basePath, depth: 0 }];
if (url.hostname === "github.com") {
const githubLinks = await crawlGithubRepo(url);
const githubLinkObjects = githubLinks.map((link) => ({
path: link,
depth: 0,
}));
paths = [...paths, ...githubLinkObjects];
}
let index = 0;
while (index < paths.length) {
const batch = paths.slice(index, index + 50);
try {
const promises = batch.map(({ path, depth }) =>
getLinksFromUrl(baseUrl, path).then((links) => ({
links,
path,
depth,
})),
); // Adjust for depth tracking
const results = await Promise.all(promises);
for (const {
links: { html, links: linksArray },
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
// Check depth
yield {
url: url.toString(),
path,
html,
};
}
// Ensure we only add links if within depth limit
if (depth < maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 }); // Increment depth for new paths
}
}
}
}
} catch (e) {
if (e instanceof TypeError) {
console.warn("Error while crawling page: ", e); // Likely an invalid url, continue with process
} else {
console.error("Error while crawling page: ", e);
}
}
index += batch.length; // Proceed to next batch
}
console.log("Crawl completed");
}

View file

@ -1,5 +1,4 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { SiteIndexingConfig } from "../../index.js";
import { SiteIndexingConfig } from "../../";
const preIndexedDocs: Record<
SiteIndexingConfig["startUrl"],

View file

@ -37,9 +37,7 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
requests,
}),
headers: {
// eslint-disable-next-line @typescript-eslint/naming-convention
"x-goog-api-key": this.options.apiKey,
// eslint-disable-next-line @typescript-eslint/naming-convention
"Content-Type": "application/json",
},
}),

View file

@ -19,13 +19,10 @@ export const allEmbeddingsProviders: Record<
EmbeddingsProviderConstructor
> = {
ollama: OllamaEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"transformers.js": TransformersJsEmbeddingsProvider,
openai: OpenAIEmbeddingsProvider,
cohere: CohereEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"free-trial": FreeTrialEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
gemini: GeminiEmbeddingsProvider,
"continue-proxy": ContinueProxyEmbeddingsProvider,

View file

@ -65,6 +65,8 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.continueignore",
"config.json",
"*.csv",
"*.uasset",
"*.pdb",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];

View file

@ -1,5 +1,6 @@
import crypto from "node:crypto";
import * as fs from "node:fs";
import plimit from "p-limit";
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import { IndexTag, IndexingProgressUpdate } from "../index.js";
@ -112,11 +113,6 @@ async function getSavedItemsForTag(
return rows;
}
interface PathAndOptionalCacheKey {
path: string;
cacheKey?: string;
}
enum AddRemoveResultType {
Add = "add",
Remove = "remove",
@ -143,7 +139,6 @@ async function getAddRemoveForTag(
const saved = await getSavedItemsForTag(tag);
const add: PathAndCacheKey[] = [];
const updateNewVersion: PathAndCacheKey[] = [];
const updateOldVersion: PathAndCacheKey[] = [];
const remove: PathAndCacheKey[] = [];
@ -178,15 +173,16 @@ async function getAddRemoveForTag(
}
}
// Any leftover in current files need to be added
add.push(
...(await Promise.all(
Object.keys(files).map(async (path) => {
const fileContents = await readFile(path);
return { path, cacheKey: calculateHash(fileContents) };
}),
)),
);
// limit to only 10 concurrent file reads to avoid issues such as
// "too many file handles". A large number here does not improve
// throughput due to the nature of disk or network i/o -- huge
// amounts of readers generally does not improve performance
const limit = plimit(10);
const promises = Object.keys(files).map(async (path) => {
const fileContents = await limit(() => readFile(path));
return { path, cacheKey: calculateHash(fileContents) };
});
const add: PathAndCacheKey[] = await Promise.all(promises);
// Create the markComplete callback function
const db = await SqliteDb.get();
@ -230,7 +226,7 @@ async function getAddRemoveForTag(
break;
case AddRemoveResultType.Add:
await db.run(
"INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)",
"REPLACE INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)",
path,
cacheKey,
newLastUpdatedTimestamp,
@ -395,7 +391,7 @@ export async function getComputeDeleteAddRemove(
lastUpdated,
async (items, resultType) => {
// Update tag catalog
markComplete(items, resultType);
await markComplete(items, resultType);
// Update the global cache
const results: any = {

View file

@ -1,12 +1,12 @@
import path from "path";
import { walkDir, WalkerOptions } from "../indexing/walkDir.js";
import FileSystemIde from "../util/filesystem.js";
import { walkDir, WalkerOptions } from "../indexing/walkDir";
import FileSystemIde from "../util/filesystem";
import {
addToTestDir,
TEST_DIR,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "./testUtils/testDir.js";
addToTestDir,
} from "../test/util/testDir";
const ide = new FileSystemIde(TEST_DIR);
@ -191,6 +191,22 @@ describe("walkDir", () => {
await expectPaths(["a.txt"], ["ignored_dir/b.txt", "ignored_dir/c/d.py"]);
});
test("gitignore in sub directory should only apply to subdirectory", async () => {
const files = [
[".gitignore", "abc"],
"a.txt",
"abc",
"xyz/",
["xyz/.gitignore", "xyz"],
"xyz/b.txt",
"xyz/c/",
"xyz/c/d.py",
"xyz/xyz",
];
addToTestDir(files);
await expectPaths(["a.txt", "xyz/b.txt", "xyz/c/d.py"], ["abc", "xyz/xyz"]);
});
test("should handle complex patterns in .gitignore", async () => {
const files = [
[".gitignore", "*.what\n!important.what\ntemp/\n/root_only.txt"],

View file

@ -29,7 +29,12 @@ type WalkableEntry = {
// helper struct used for the DFS walk
type WalkContext = {
walkableEntry: WalkableEntry;
ignoreContexts: IgnoreContext[];
};
type IgnoreContext = {
ignore: Ignore;
dirname: string;
};
class DFSWalker {
@ -51,30 +56,22 @@ class DFSWalker {
this.options.returnRelativePaths ? "" : this.path,
this.ide,
);
const root: WalkContext = {
walkableEntry: {
relPath: "",
absPath: this.path,
type: 2 as FileType.Directory,
entry: ["", 2 as FileType.Directory],
},
ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile),
};
const root = this.newRootWalkContext();
const stack = [root];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
const walkableEntries = await this.listDirForWalking(cur.walkableEntry);
const ignore = await this.getIgnoreToApplyInDir(
cur.ignore,
const ignoreContexts = await this.getIgnoreToApplyInDir(
cur,
walkableEntries,
);
for (const w of walkableEntries) {
if (!this.shouldInclude(w, ignore)) {
if (!this.shouldInclude(w, ignoreContexts)) {
continue;
}
if (this.entryIsDirectory(w.entry)) {
stack.push({
walkableEntry: w,
ignore: ignore,
ignoreContexts: ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
@ -87,6 +84,23 @@ class DFSWalker {
}
}
private newRootWalkContext(): WalkContext {
return {
walkableEntry: {
relPath: "",
absPath: this.path,
type: 2 as FileType.Directory,
entry: ["", 2 as FileType.Directory],
},
ignoreContexts: [
{
ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile),
dirname: "",
},
],
};
}
private async listDirForWalking(
walkableEntry: WalkableEntry,
): Promise<WalkableEntry[]> {
@ -102,15 +116,22 @@ class DFSWalker {
}
private async getIgnoreToApplyInDir(
parentIgnore: Ignore,
walkableEntries: WalkableEntry[],
): Promise<Ignore> {
const ignoreFilesInDir = await this.loadIgnoreFiles(walkableEntries);
curDir: WalkContext,
entriesInDir: WalkableEntry[],
): Promise<IgnoreContext[]> {
const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir);
if (ignoreFilesInDir.length === 0) {
return parentIgnore;
return curDir.ignoreContexts;
}
const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat();
return ignore().add(parentIgnore).add(patterns);
const newIgnoreContext = {
ignore: ignore().add(patterns),
dirname: curDir.walkableEntry.relPath,
};
return [
...curDir.ignoreContexts,
newIgnoreContext
];
}
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<string[]> {
@ -126,7 +147,7 @@ class DFSWalker {
return this.ignoreFileNames.has(p);
}
private shouldInclude(walkableEntry: WalkableEntry, ignore: Ignore) {
private shouldInclude(walkableEntry: WalkableEntry, ignoreContexts: IgnoreContext[]) {
if (this.entryIsSymlink(walkableEntry.entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it linksto something outside of the repository and
@ -141,7 +162,17 @@ class DFSWalker {
return false;
}
}
return !ignore.ignores(relPath);
for (const ig of ignoreContexts) {
// remove the directory name and path seperator from the match path, unless this an ignore file
// in the root directory
const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
if (ig.ignore.ignores(matchPath)) {
return false;
}
}
return true;
}
private entryIsDirectory(entry: Entry) {

View file

@ -1,9 +1,5 @@
import fs from "fs";
import path from "path";
export default async function () {
process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true });
}
}

View file

@ -1,7 +1,7 @@
// https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055
import { TextEncoder, TextDecoder } from "util";
import fetch, { Request, Response } from "node-fetch";
import { jest } from "@jest/globals";
import fetch, { Request, Response } from "node-fetch";
import { TextDecoder, TextEncoder } from "util";
if (process.env.DEBUG === "jest") {
jest.setTimeout(5 * 60 * 1000);
@ -14,3 +14,18 @@ globalThis.Request = Request;
globalThis.Response = Response;
globalThis.TextEncoder = TextEncoder;
globalThis.TextDecoder = TextDecoder;
// Trying to delete this when for some reason SQLite is still in use causes tests to fail
// globalThis.beforeAll(() => {
// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
// }
// });
// globalThis.afterAll(() => {
// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
// }
// });

View file

@ -0,0 +1,45 @@
import { LlamaAsyncEncoder, GPTAsyncEncoder } from "./asyncEncoder";
describe("llama encoder", () => {
var tokenizer: LlamaAsyncEncoder;
beforeAll(() => {
tokenizer = new LlamaAsyncEncoder();
});
afterAll(() => {
tokenizer.close();
});
test("hello world", async () => {
const input = "the quick brown fox jumped over the lazy dog";
const output = await tokenizer.encode(input);
expect(output).toEqual([
1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203,
]);
const decoded = await tokenizer.decode(output);
expect(decoded).toBe(input);
});
});
describe("tiktoken encoder", () => {
var tokenizer: GPTAsyncEncoder;
beforeAll(() => {
tokenizer = new GPTAsyncEncoder();
});
afterAll(() => {
tokenizer.close();
});
test("hello world", async () => {
const input = "the quick brown fox jumped over the lazy dog";
const output = await tokenizer.encode(input);
expect(output).toEqual([
1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679,
]);
const decoded = await tokenizer.decode(output);
expect(decoded).toBe(input);
});
});

View file

@ -1,7 +1,5 @@
import llamaTokenizer from "./llamaTokenizer.js";
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import path from "path";
import workerpool from "workerpool";
import * as path from "path";
export interface AsyncEncoder {
encode(text: string): Promise<number[]>;
@ -13,7 +11,9 @@ export class LlamaAsyncEncoder implements AsyncEncoder {
private workerPool: workerpool.Pool;
constructor() {
this.workerPool = workerpool.pool(workerCodeFilePath("llamaTokenizerWorkerPool.mjs"));
this.workerPool = workerpool.pool(
workerCodeFilePath("llamaTokenizerWorkerPool.mjs"),
);
}
async encode(text: string): Promise<number[]> {
@ -35,7 +35,9 @@ export class GPTAsyncEncoder implements AsyncEncoder {
private workerPool: workerpool.Pool;
constructor() {
this.workerPool = workerpool.pool(workerCodeFilePath("tiktokenWorkerPool.mjs"));
this.workerPool = workerpool.pool(
workerCodeFilePath("tiktokenWorkerPool.mjs"),
);
}
async encode(text: string): Promise<number[]> {
@ -58,4 +60,4 @@ function workerCodeFilePath(workerFileName: string): string {
return path.join(__dirname, "llm", workerFileName);
}
return path.join(__dirname, workerFileName);
}
}

View file

@ -80,7 +80,7 @@ function modelSupportsImages(
title: string | undefined,
capabilities: ModelCapability | undefined
): boolean {
if (capabilities?.uploadImage !== undefined) return capabilities.uploadImage
if (capabilities?.uploadImage !== undefined) {return capabilities.uploadImage;}
if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) {
return false;
}

View file

@ -24,18 +24,37 @@ class LlamaEncoding implements Encoding {
}
}
class NonWorkerAsyncEncoder implements AsyncEncoder {
constructor(private readonly encoding: Encoding) {}
async close(): Promise<void> {}
async encode(text: string): Promise<number[]> {
return this.encoding.encode(text);
}
async decode(tokens: number[]): Promise<string> {
return this.encoding.decode(tokens);
}
}
let gptEncoding: Encoding | null = null;
const gptAsyncEncoder = new GPTAsyncEncoder();
const llamaEncoding = new LlamaEncoding();
const llamaAsyncEncoder = new LlamaAsyncEncoder();
function asyncEncoderForModel(modelName: string): AsyncEncoder {
// Temporary due to issues packaging the worker files
if (process.env.IS_BINARY) {
const encoding = encodingForModel(modelName);
return new NonWorkerAsyncEncoder(encoding);
}
const modelType = autodetectTemplateType(modelName);
if (!modelType || modelType === "none") {
return gptAsyncEncoder;
}
// Temporary due to issues packaging the worker files
return process.env.IS_BINARY ? gptAsyncEncoder : llamaAsyncEncoder;
return llamaAsyncEncoder;
}
function encodingForModel(modelName: string): Encoding {

View file

@ -1,5 +1,5 @@
import { ChatMessage, LLMOptions, ModelProvider } from "../index.js";
import { BaseLLM } from "../llm/index.js";
import { ChatMessage, LLMOptions, ModelProvider } from "..";
import { BaseLLM } from ".";
class DummyLLM extends BaseLLM {
static providerName: ModelProvider = "openai";

View file

@ -91,6 +91,7 @@ export abstract class BaseLLM implements ILLM {
title?: string;
systemMessage?: string;
contextLength: number;
maxStopWords?: number | undefined;
completionOptions: CompletionOptions;
requestOptions?: RequestOptions;
template?: TemplateType;
@ -110,15 +111,12 @@ export abstract class BaseLLM implements ILLM {
accountId?: string;
aiGatewaySlug?: string;
// For WatsonX only.
// For IBM watsonx only.
watsonxUrl?: string;
watsonxApiKey?: string;
watsonxZenApiKeyBase64?: string = "YOUR_WATSONX_ZENAPIKEY"; // Required if using watsonx software with ZenApiKey auth
watsonxUsername?: string;
watsonxPassword?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
private _llmOptions: LLMOptions;
@ -143,6 +141,7 @@ export abstract class BaseLLM implements ILLM {
this.systemMessage = options.systemMessage;
this.contextLength =
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
this.maxStopWords = options.maxStopWords ?? this.maxStopWords;
this.completionOptions = {
...options.completionOptions,
model: options.model || "gpt-4",
@ -171,13 +170,13 @@ export abstract class BaseLLM implements ILLM {
this.apiKey = options.apiKey;
this.aiGatewaySlug = options.aiGatewaySlug;
this.apiBase = options.apiBase;
// for watsonx only
this.watsonxUrl = options.watsonxUrl;
this.watsonxApiKey = options.watsonxApiKey;
this.watsonxCreds = options.watsonxCreds;
this.watsonxProjectId = options.watsonxProjectId;
this.watsonxUsername = options.watsonxUsername;
this.watsonxPassword = options.watsonxPassword;
this.watsonxStopToken = options.watsonxStopToken;
this.watsonxApiVersion = options.watsonxApiVersion;
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;

View file

@ -14,19 +14,24 @@ import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
class Bedrock extends BaseLLM {
private static PROFILE_NAME: string = "bedrock";
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
contextLength: 200_000
};
profile?: string | undefined;
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "bedrock";
}
}
protected async *_streamComplete(
@ -124,11 +129,11 @@ class Bedrock extends BaseLLM {
private async _getCredentials() {
try {
return await fromIni({
profile: Bedrock.PROFILE_NAME,
profile: this.profile,
})();
} catch (e) {
console.warn(
`AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}

View file

@ -0,0 +1,96 @@
import {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../../index.js";
import { BaseLLM } from "../index.js";
class BedrockImport extends BaseLLM {
static providerName: ModelProvider = "bedrockimport";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1"
};
// the BedRock imported custom model ARN
modelArn?: string | undefined;
profile?: string | undefined;
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
if (options.modelArn) {
this.modelArn = options.modelArn;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "bedrock";
}
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const input = this._generateInvokeModelCommandInput(prompt, options);
const command = new InvokeModelWithResponseStreamCommand(input);
const response = await client.send(command);
if (response.body) {
for await (const item of response.body) {
const chunk = JSON.parse(new TextDecoder().decode(item.chunk?.bytes));
if (chunk.outputs[0].text) {
yield chunk.outputs[0].text;
}
}
}
}
private _generateInvokeModelCommandInput(
prompt: string,
options: CompletionOptions,
): any {
const payload = {
prompt: prompt
};
return {
body: JSON.stringify(payload),
modelId: this.modelArn,
accept: "application/json",
contentType: "application/json"
};
}
private async _getCredentials() {
try {
return await
fromIni({
profile: this.profile
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
}
export default BedrockImport;

View file

@ -13,7 +13,7 @@ class Deepseek extends OpenAI {
},
useLegacyCompletionsEndpoint: false,
};
protected maxStopWords: number | undefined = 16;
maxStopWords: number | undefined = 16;
supportsFim(): boolean {
return true;

View file

@ -2,7 +2,6 @@ import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
import { getHeaders } from "../../continueServer/stubs/headers.js";
import { constants } from "../../deploy/constants.js";
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { Telemetry } from "../../util/posthog.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
@ -29,18 +28,19 @@ class FreeTrial extends BaseLLM {
}
private async _countTokens(prompt: string, model: string, isPrompt: boolean) {
if (!Telemetry.client) {
throw new Error(
'In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set "allowAnonymousTelemetry": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.',
);
}
const event = isPrompt
? "free_trial_prompt_tokens"
: "free_trial_completion_tokens";
Telemetry.capture(event, {
tokens: this.countTokens(prompt),
model,
});
// Removed to reduce PostHog bill
// if (!Telemetry.client) {
// throw new Error(
// "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.",
// );
// }
// const event = isPrompt
// ? "free_trial_prompt_tokens"
// : "free_trial_completion_tokens";
// Telemetry.capture(event, {
// tokens: this.countTokens(prompt),
// model,
// });
}
private _convertArgs(options: CompletionOptions): any {

View file

@ -6,7 +6,7 @@ class Groq extends OpenAI {
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.groq.com/openai/v1/",
};
protected maxStopWords: number | undefined = 4;
maxStopWords: number | undefined = 4;
private static modelConversion: { [key: string]: string } = {
"llama2-70b": "llama2-70b-4096",

16
core/llm/llms/Kindo.ts Normal file
View file

@ -0,0 +1,16 @@
import { LLMOptions, ModelProvider } from "../..";
import OpenAI from "./OpenAI";
class Kindo extends OpenAI {
static providerName: ModelProvider = "kindo";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://llm.kindo.ai/v1",
requestOptions: {
headers: {
"kindo-token-transaction-type": "CONTINUE"
}
}
};
}
export default Kindo;

View file

@ -20,6 +20,10 @@ class Mistral extends OpenAI {
) {
this.apiBase = options.apiBase ?? "https://codestral.mistral.ai/v1/";
}
if (!this.apiBase?.endsWith("/")) {
this.apiBase += "/";
}
}
private static modelConversion: { [key: string]: string } = {

View file

@ -50,7 +50,8 @@ class Ollama extends BaseLLM {
let value = parts[2];
switch (key) {
case "num_ctx":
this.contextLength = Number.parseInt(value);
this.contextLength =
options.contextLength ?? Number.parseInt(value);
break;
case "stop":
if (!this.completionOptions.stop) {
@ -60,7 +61,7 @@ class Ollama extends BaseLLM {
this.completionOptions.stop.push(JSON.parse(value));
} catch (e) {
console.warn(
'Error parsing stop parameter value "{value}: ${e}',
"Error parsing stop parameter value \"{value}: ${e}",
);
}
break;

View file

@ -42,7 +42,7 @@ const CHAT_ONLY_MODELS = [
class OpenAI extends BaseLLM {
public useLegacyCompletionsEndpoint: boolean | undefined = undefined;
protected maxStopWords: number | undefined = undefined;
maxStopWords: number | undefined = undefined;
constructor(options: LLMOptions) {
super(options);
@ -104,13 +104,13 @@ class OpenAI extends BaseLLM {
this.maxStopWords !== undefined
? options.stop?.slice(0, this.maxStopWords)
: url.host === "api.deepseek.com"
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
};
return finalOptions;

View file

@ -0,0 +1,17 @@
import { LLMOptions, ModelProvider } from "../../index.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
class OpenRouter extends OpenAI {
static providerName: ModelProvider = "openrouter";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://openrouter.ai/api/v1/",
model: "gpt-4o-mini",
promptTemplates: {
edit: osModelsEditPrompt,
},
useLegacyCompletionsEndpoint: false,
};
}
export default OpenRouter;

View file

@ -55,7 +55,7 @@ class SageMaker extends BaseLLM {
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
const data = JSON.parse(line.replace(/^data:/, ''));
const data = JSON.parse(line.replace(/^data:/, ""));
if ("choices" in data) {
yield data.choices[0].delta.content;
}
@ -94,7 +94,7 @@ class SageMaker extends BaseLLM {
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
const data = JSON.parse(line.replace(/^data:/, ''));
const data = JSON.parse(line.replace(/^data:/, ""));
if ("choices" in data) {
yield { role: "assistant", content: data.choices[0].delta.content };
}
@ -143,7 +143,7 @@ class MessageAPIToolkit implements SageMakerModelToolkit {
let prompt = jinja.compile(this.sagemaker.completionOptions.chat_template).render(
{ messages: messages, add_generation_prompt: true },
{ autoEscape: false }
)
);
const payload = {
inputs: prompt,
parameters: this.sagemaker.completionOptions,

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