Merge branch 'continuedev:dev' into dev
This commit is contained in:
commit
55afbf5236
388 changed files with 19718 additions and 7501 deletions
8
.changes/extensions/intellij/0.0.53.md
Normal file
8
.changes/extensions/intellij/0.0.53.md
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
## 0.0.53 - 2024-07-10
|
||||
### Added
|
||||
* Support for .prompt files
|
||||
* New onboarding experience
|
||||
### Fixed
|
||||
* Indexing fixes from VS Code versions merged into IntelliJ
|
||||
* Improved codebase indexing reliability and testing
|
||||
* Fixes for autocomplete text positioning and timing
|
||||
6
.changes/extensions/intellij/0.0.54.md
Normal file
6
.changes/extensions/intellij/0.0.54.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
## 0.0.54 - 2024-07-13
|
||||
### Added
|
||||
* Partial autocomplete acceptance
|
||||
* Autocomplete status bar spinner
|
||||
### Fixed
|
||||
* Fixed duplicate completion bug and others
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
## 0.8.40 - 2024-07-02
|
||||
### Added
|
||||
* Support for Gemini 1.5 Pro
|
||||
* Link to code in the sidebar when using codebase retrieval
|
||||
* Smoother onboarding experience
|
||||
* .prompt files, a way of saving and sharing slash commands
|
||||
* Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
|
||||
* Support for comments in config.json
|
||||
* Specify multiple autocomplete models and switch between them
|
||||
* Improved bracket matching strategy reduces noisy completions
|
||||
### Fixed
|
||||
* Numerous reliability upgrades to codebase indexing
|
||||
16
.changes/extensions/vscode/0.8.42.md
Normal file
16
.changes/extensions/vscode/0.8.42.md
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
## 0.8.42 - 2024-07-02
|
||||
|
||||
### Added
|
||||
|
||||
- Support for Gemini 1.5 Pro
|
||||
- Link to code in the sidebar when using codebase retrieval
|
||||
- Smoother onboarding experience
|
||||
- .prompt files, a way of saving and sharing slash commands
|
||||
- Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
|
||||
- Support for comments in config.json
|
||||
- Specify multiple autocomplete models and switch between them
|
||||
- Improved bracket matching strategy reduces noisy completions
|
||||
|
||||
### Fixed
|
||||
|
||||
- Numerous reliability upgrades to codebase indexing
|
||||
4
.changes/extensions/vscode/0.8.43.md
Normal file
4
.changes/extensions/vscode/0.8.43.md
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
## 0.8.43 - 2024-07-08
|
||||
### Added
|
||||
* Improved indexing reliability and testing
|
||||
* Quick Actions: use CodeLens to quickly take common actions like adding docstrings
|
||||
12
.changes/extensions/vscode/0.8.45.md
Normal file
12
.changes/extensions/vscode/0.8.45.md
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
## 0.8.45 - 2024-08-05
|
||||
### Added
|
||||
* Support for Llama 3.1 and gpt-4o-mini
|
||||
* Support for WatsonX+Granite models
|
||||
### Changed
|
||||
* Significant improvements to indexing performance
|
||||
* Improved @codebase quality by more accurately searching over file names and paths
|
||||
* Improved @codebase accuracy
|
||||
* Further improvements to indexing performance
|
||||
### Fixed
|
||||
* Improved docs indexing and management
|
||||
* Fixed Gemini embeddings provider
|
||||
6
.changes/extensions/vscode/0.8.46.md
Normal file
6
.changes/extensions/vscode/0.8.46.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
## 0.8.46 - 2024-08-11
|
||||
### Added
|
||||
* new /onboard slash command
|
||||
### Fixed
|
||||
* Fixed problem loading config.ts
|
||||
* Fixed bug causing duplicate indexing work
|
||||
8
.changes/extensions/vscode/0.8.47.md
Normal file
8
.changes/extensions/vscode/0.8.47.md
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
## 0.8.47 - 2024-08-27
|
||||
### Added
|
||||
* Use headless browser for crawling to get better results
|
||||
* TTS support in the chat window
|
||||
### Changed
|
||||
* Improved support for WatsonX models
|
||||
### Fixed
|
||||
* Fixed several small indexing bugs
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
## v0.1.104 - 2023-12-25
|
||||
|
||||
### Added
|
||||
|
||||
- Continuous and faster syncing of codebase index
|
||||
|
||||
### Removed
|
||||
|
||||
- No longer using Continue Python server
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.1.99 - 2023-11-19
|
||||
|
||||
### Changed
|
||||
|
||||
- migrated to .json config file format
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Support for Llama 3.1 and gpt-4o-mini
|
||||
time: 2024-07-26T15:35:14.411895-07:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Changed
|
||||
body: Significant improvements to indexing performance
|
||||
time: 2024-07-26T15:34:58.457908-07:00
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Changed
|
||||
body: Improved @codebase quality by more accurately searching over file names and
|
||||
paths
|
||||
time: 2024-07-26T15:35:42.390496-07:00
|
||||
4
.github/pull_request_template.md
vendored
4
.github/pull_request_template.md
vendored
|
|
@ -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. ]
|
||||
|
|
|
|||
4
.github/workflows/README.md
vendored
4
.github/workflows/README.md
vendored
|
|
@ -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
92
.github/workflows/dev_pr.yaml
vendored
Normal 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
|
||||
476
.github/workflows/jetbrains-build.yaml
vendored
476
.github/workflows/jetbrains-build.yaml
vendored
|
|
@ -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
|
||||
418
.github/workflows/jetbrains-release.yaml
vendored
418
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -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
|
||||
name: JetBrains Release
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [prereleased, released]
|
||||
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
|
||||
|
|
|
|||
83
.github/workflows/main.yaml
vendored
83
.github/workflows/main.yaml
vendored
|
|
@ -1,16 +1,27 @@
|
|||
name: Publish Extension
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
types: [closed]
|
||||
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:
|
||||
|
|
@ -49,8 +60,13 @@ jobs:
|
|||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
# 1. Check-out repository
|
||||
- name: Check-out repository
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # This ensures all tags are fetched
|
||||
|
||||
- name: Checkout tag
|
||||
run: git checkout ${GITHUB_REF#refs/tags/}
|
||||
|
||||
- name: Make sure version isn't odd
|
||||
run: |
|
||||
|
|
@ -94,18 +110,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
|
||||
|
||||
# 2.25 Run core tests
|
||||
- name: Run core tests
|
||||
run: |
|
||||
cd core
|
||||
npm run test
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
# - 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
|
||||
|
|
@ -125,19 +142,19 @@ jobs:
|
|||
|
||||
# 4. Run tests for the extension
|
||||
# - name: Install Xvfb for Linux and run tests
|
||||
run: |
|
||||
sudo apt-get install -y xvfb # Install Xvfb
|
||||
Xvfb :99 & # Start Xvfb
|
||||
export DISPLAY=:99 # Export the display number to the environment
|
||||
cd extensions/vscode
|
||||
npm run test
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
# run: |
|
||||
# sudo apt-get install -y xvfb # Install Xvfb
|
||||
# Xvfb :99 & # Start Xvfb
|
||||
# export DISPLAY=:99 # Export the display number to the environment
|
||||
# cd extensions/vscode
|
||||
# npm run test
|
||||
# if: matrix.os == 'ubuntu-latest'
|
||||
|
||||
- name: Run extension tests
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npm run test
|
||||
if: matrix.os != 'ubuntu-latest'
|
||||
# - name: Run extension tests
|
||||
# run: |
|
||||
# cd extensions/vscode
|
||||
# npm run test
|
||||
# if: matrix.os != 'ubuntu-latest'
|
||||
|
||||
# 5. Package the extension
|
||||
- name: Package the extension
|
||||
|
|
@ -167,20 +184,10 @@ jobs:
|
|||
# Download the .vsix artifacts
|
||||
- uses: actions/download-artifact@v3
|
||||
|
||||
- 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$(grep -o '"version": "[^"]*' extensions/vscode/package.json | cut -d'"' -f4)-vscode
|
||||
echo "$TAG"
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
git tag -a $TAG -m "Published version $TAG" ${GITHUB_SHA}
|
||||
git push origin $TAG
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.tag.outputs.tag }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
files: |
|
||||
alpine-x64/*.vsix
|
||||
darwin-arm64/*.vsix
|
||||
|
|
|
|||
57
.github/workflows/preview.yaml
vendored
57
.github/workflows/preview.yaml
vendored
|
|
@ -1,12 +1,27 @@
|
|||
name: Publish Preview Extension
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- preview
|
||||
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:
|
||||
|
|
@ -45,8 +60,13 @@ jobs:
|
|||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
# 1. Check-out repository
|
||||
- name: Check-out repository
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # This ensures all tags are fetched
|
||||
|
||||
- name: Checkout tag
|
||||
run: git checkout ${GITHUB_REF#refs/tags/}
|
||||
|
||||
# 2. Install npm dependencies
|
||||
- name: Use Node.js from .nvmrc
|
||||
|
|
@ -85,18 +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
|
||||
|
||||
# 2.25 Run core tests
|
||||
- name: Run core tests
|
||||
run: |
|
||||
cd core
|
||||
npm run test
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
# - 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
|
||||
|
|
@ -158,20 +179,10 @@ jobs:
|
|||
# Download the .vsix artifacts
|
||||
- uses: actions/download-artifact@v3
|
||||
|
||||
- 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$(grep -o '"version": "[^"]*' extensions/vscode/package.json | cut -d'"' -f4)-vscode
|
||||
echo "$TAG"
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
git tag -a $TAG -m "Published version $TAG" ${GITHUB_SHA}
|
||||
git push origin $TAG
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.tag.outputs.tag }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
files: |
|
||||
alpine-x64/*.vsix
|
||||
darwin-arm64/*.vsix
|
||||
|
|
@ -202,7 +213,7 @@ jobs:
|
|||
git config --local user.name "GitHub Action"
|
||||
|
||||
- name: Pull latest changes
|
||||
run: git pull origin preview
|
||||
run: git pull origin dev
|
||||
|
||||
# 1. Download the artifacts
|
||||
- uses: actions/download-artifact@v3
|
||||
|
|
|
|||
1
.github/workflows/ts-check.yaml
vendored
1
.github/workflows/ts-check.yaml
vendored
|
|
@ -5,7 +5,6 @@ on:
|
|||
branches:
|
||||
- main
|
||||
- preview
|
||||
- dev
|
||||
|
||||
jobs:
|
||||
tsc-check:
|
||||
|
|
|
|||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -165,5 +165,5 @@ Icon?
|
|||
|
||||
.continue
|
||||
|
||||
# Sandbox env default file
|
||||
extensions/vscode/manual-testing-sandbox/example.ts
|
||||
|
||||
.prompts/
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
extensions/vscode/continue_rc_schema.json
|
||||
**/.continueignore
|
||||
**/.continueignore
|
||||
CHANGELOG.md
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
temperature: 0.5
|
||||
maxTokens: 4096
|
||||
name: jest
|
||||
description: Write Jest unit tests
|
||||
---
|
||||
<system>
|
||||
You are an expert programmer
|
||||
</system>
|
||||
|
||||
{{{ input }}}
|
||||
|
||||
Write unit tests for the above selected code, following each of these instructions:
|
||||
- Use `jest`
|
||||
- Properly set up and tear down
|
||||
- Include important edge cases
|
||||
- The tests should be complete and sophisticated
|
||||
- Give the tests just as chat output, don't edit any file
|
||||
- Don't explain how to set up `jest`
|
||||
- Write a single code block, making sure to label with the language being used (e.g. "```typscript")
|
||||
- Do not under any circumstances mock any functions or modules
|
||||
85
.vscode/launch.json
vendored
85
.vscode/launch.json
vendored
|
|
@ -5,6 +5,24 @@
|
|||
"version": "0.2.0",
|
||||
"compounds": [],
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch extension",
|
||||
"type": "extensionHost",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}/extensions/vscode",
|
||||
"args": [
|
||||
// Pass a directory to manually test in
|
||||
"${workspaceFolder}/manual-testing-sandbox",
|
||||
"${workspaceFolder}/manual-testing-sandbox/test.js",
|
||||
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
|
||||
],
|
||||
"pauseForSourceMap": false,
|
||||
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
|
||||
"preLaunchTask": "vscode-extension:build",
|
||||
"env": {
|
||||
// "CONTROL_PLANE_ENV": "local"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
|
|
@ -22,7 +40,6 @@
|
|||
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/binary/.continue"
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
"name": "Debug Jest Tests",
|
||||
"type": "node",
|
||||
|
|
@ -35,6 +52,7 @@
|
|||
"--config",
|
||||
"${workspaceRoot}/core/jest.config.js"
|
||||
],
|
||||
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen"
|
||||
},
|
||||
|
|
@ -52,27 +70,9 @@
|
|||
"sourceMaps": true
|
||||
// "preLaunchTask": "gui:dev"
|
||||
},
|
||||
{
|
||||
"name": "Extension (VSCode)",
|
||||
"type": "extensionHost",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}/extensions/vscode",
|
||||
"args": [
|
||||
// Pass a directory to manually test in
|
||||
"${workspaceFolder}/extensions/vscode",
|
||||
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox/test.js",
|
||||
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
|
||||
],
|
||||
"pauseForSourceMap": false,
|
||||
"outFiles": [
|
||||
"${workspaceFolder}/extensions/vscode/out/extension.js",
|
||||
"/Users/natesesti/.continue/config.ts"
|
||||
],
|
||||
"preLaunchTask": "vscode-extension:build"
|
||||
},
|
||||
// Has to be run after starting the server (separately or using the compound configuration)
|
||||
{
|
||||
"name": "Tests (VSCode)",
|
||||
"name": "Run tests",
|
||||
"type": "extensionHost",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}/extensions/vscode",
|
||||
|
|
@ -110,7 +110,50 @@
|
|||
],
|
||||
"cwd": "${workspaceRoot}/core",
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen"
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"env": {
|
||||
"NODE_OPTIONS": "--experimental-vm-modules",
|
||||
"CI": "true",
|
||||
"DEBUG": "jest"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "[openai-adapters] Jest Test Debugger, Current Open File",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"runtimeArgs": [
|
||||
"--inspect-brk",
|
||||
"${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
|
||||
"--runInBand",
|
||||
"--config",
|
||||
"${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
|
||||
"${relativeFile}"
|
||||
],
|
||||
"cwd": "${workspaceRoot}/packages/openai-adapters",
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"env": {
|
||||
"NODE_OPTIONS": "--experimental-vm-modules"
|
||||
}
|
||||
}
|
||||
// {
|
||||
// "name": "[openai-adapters] Jest Test Debugger, Current Open File",
|
||||
// "type": "node",
|
||||
// "request": "launch",
|
||||
// "runtimeArgs": [
|
||||
// "--inspect-brk",
|
||||
// "${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
|
||||
// "--runInBand",
|
||||
// "--config",
|
||||
// "${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
|
||||
// "${relativeFile}"
|
||||
// ],
|
||||
// "cwd": "${workspaceRoot}/packages/openai-adapters",
|
||||
// "console": "integratedTerminal",
|
||||
// "internalConsoleOptions": "neverOpen",
|
||||
// "env": {
|
||||
// "NODE_OPTIONS": "--experimental-vm-modules"
|
||||
// }
|
||||
// }
|
||||
]
|
||||
}
|
||||
|
|
|
|||
6
.vscode/settings.json
vendored
6
.vscode/settings.json
vendored
|
|
@ -14,7 +14,9 @@
|
|||
}
|
||||
},
|
||||
"search.exclude": {
|
||||
"./binary": true,
|
||||
"**/core/vendor/**": true
|
||||
"**/binary": true,
|
||||
"binary/": false,
|
||||
"**/core/vendor/**": true,
|
||||
"**/gui/dist": true
|
||||
}
|
||||
}
|
||||
|
|
|
|||
9
.vscode/tasks.json
vendored
9
.vscode/tasks.json
vendored
|
|
@ -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": []
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@ You can run the documentation server locally using either of the following metho
|
|||
1. Open your terminal and navigate to the root directory of the project.
|
||||
|
||||
2. Run the following command to start the documentation server:
|
||||
|
||||
```bash
|
||||
npm run start --prefix docs
|
||||
```
|
||||
|
|
@ -116,7 +117,7 @@ nvm use
|
|||
2. Start debugging:
|
||||
|
||||
1. Switch to Run and Debug view
|
||||
2. Select `Extension (VS Code)` from drop down
|
||||
2. Select `Launch extension` from drop down
|
||||
3. Hit play button
|
||||
4. This will start the extension in debug mode and open a new VS Code window with it installed
|
||||
1. The new VS Code window with the extension is referred to as the _Host VS Code_
|
||||
|
|
@ -151,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:
|
||||
|
||||
|
|
@ -162,6 +163,10 @@ For the sake of rapid development, it is also possible to configure this communi
|
|||
|
||||
If you make changes to Kotlin code, they can often be hot-reloaded with "Run -> Debugging Actions -> Reload Changed Classes".
|
||||
|
||||
### Our Git Workflow
|
||||
|
||||
We keep two permanent branches: `main` and `dev`. All contributions should be made as pull requests to the `dev` branch. When we are ready to create a "pre-release" version, we create a tag on the `dev` branch, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will merge its tag into the `main` branch. Creating a tag on the `main` branch will then trigger a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question.
|
||||
|
||||
### Formatting
|
||||
|
||||
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
```
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
@ -184,7 +185,14 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
entryPoints: ["src/index.ts"],
|
||||
bundle: true,
|
||||
outfile: esbuildOutputFile,
|
||||
external: ["esbuild", "./xhr-sync-worker.js", "vscode", "./index.node"],
|
||||
external: [
|
||||
"esbuild",
|
||||
"./xhr-sync-worker.js",
|
||||
"llamaTokenizerWorkerPool.mjs",
|
||||
"tiktokenWorkerPool.mjs",
|
||||
"vscode",
|
||||
"./index.node",
|
||||
],
|
||||
format: "cjs",
|
||||
platform: "node",
|
||||
sourcemap: true,
|
||||
|
|
@ -204,6 +212,11 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
"../core/node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js",
|
||||
"out/xhr-sync-worker.js",
|
||||
);
|
||||
fs.cpSync("../core/llm/tiktokenWorkerPool.mjs", "out/tiktokenWorkerPool.mjs");
|
||||
fs.cpSync(
|
||||
"../core/llm/llamaTokenizerWorkerPool.mjs",
|
||||
"out/llamaTokenizerWorkerPool.mjs",
|
||||
);
|
||||
|
||||
if (esbuildOnly) {
|
||||
return;
|
||||
|
|
@ -225,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
|
||||
|
|
@ -235,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`,
|
||||
);
|
||||
}
|
||||
|
|
@ -245,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}...`);
|
||||
|
|
@ -287,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!");
|
||||
|
|
|
|||
26
binary/package-lock.json
generated
26
binary/package-lock.json
generated
|
|
@ -44,32 +44,32 @@
|
|||
"version": "1.0.13",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
|
||||
"@aws-sdk/credential-providers": "^3.596.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
|
||||
"@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",
|
||||
"@types/jsdom": "^21.1.6",
|
||||
"@types/mozilla-readability": "^0.2.1",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
"@typescript-eslint/parser": "^7.8.0",
|
||||
"@xenova/transformers": "2.14.0",
|
||||
"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",
|
||||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"ignore": "^5.3.1",
|
||||
"jinja-js": "0.1.8",
|
||||
"js-tiktoken": "^1.0.8",
|
||||
"jsdom": "^24.0.0",
|
||||
"launchdarkly-node-client-sdk": "^3.2.0",
|
||||
|
|
@ -80,8 +80,11 @@
|
|||
"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",
|
||||
"request": "^2.88.2",
|
||||
"socket.io-client": "^4.7.3",
|
||||
|
|
@ -91,8 +94,9 @@
|
|||
"tree-sitter-wasms": "^0.1.11",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.20",
|
||||
"web-tree-sitter": "^0.22.0",
|
||||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
|
|
@ -103,12 +107,20 @@
|
|||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jquery": "^3.5.29",
|
||||
"@types/jsdom": "^21.1.6",
|
||||
"@types/mozilla-readability": "^0.2.1",
|
||||
"@types/mustache": "^4.2.5",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
"@types/pg": "^8.11.6",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
"cross-env": "^7.0.3",
|
||||
"esbuild": "0.17.19",
|
||||
"eslint": "^8",
|
||||
"eslint-plugin-import": "^2.29.1",
|
||||
"jest": "^29.7.0",
|
||||
"jest-environment-jsdom": "^29.7.0",
|
||||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
{
|
||||
"name": "binary",
|
||||
"version": "1.0.0",
|
||||
"author": "Continue Dev, Inc",
|
||||
"description": "",
|
||||
"main": "out/index.js",
|
||||
"bin": "out/index.js",
|
||||
|
|
@ -26,7 +27,6 @@
|
|||
"build:dev": "tsc",
|
||||
"esbuild": "node build.js --esbuild-only"
|
||||
},
|
||||
"author": "",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "1.6.4",
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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...");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "ES2020",
|
||||
"target": "ES2022",
|
||||
"outDir": "out",
|
||||
"lib": ["ES2020", "dom", "es6", "es5", "dom.iterable", "scripthost"],
|
||||
"lib": ["ES2022", "dom", "es6", "es5", "dom.iterable", "scripthost"],
|
||||
"sourceMap": true,
|
||||
"rootDirs": ["src", "../core"],
|
||||
"allowJs": true,
|
||||
|
|
|
|||
26
biome.json
26
biome.json
|
|
@ -1,26 +0,0 @@
|
|||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.6.4/schema.json",
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"suspicious": {
|
||||
"noExplicitAny": "off",
|
||||
"noConfusingVoidType": "off"
|
||||
},
|
||||
"style": {
|
||||
"noUselessElse": "off",
|
||||
"noNonNullAssertion": "off"
|
||||
},
|
||||
"complexity": {
|
||||
"noForEach": "off"
|
||||
}
|
||||
}
|
||||
},
|
||||
"formatter": {
|
||||
"indentStyle": "space"
|
||||
}
|
||||
}
|
||||
|
|
@ -3,18 +3,19 @@
|
|||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 6,
|
||||
"sourceType": "module"
|
||||
"sourceType": "module",
|
||||
"project": "./tsconfig.json"
|
||||
},
|
||||
"plugins": ["@typescript-eslint", "import"],
|
||||
"rules": {
|
||||
"quotes": ["warn", "double", {}],
|
||||
"import/extensions": ["error", "ignorePackages"],
|
||||
"@typescript-eslint/naming-convention": "warn",
|
||||
"@typescript-eslint/naming-convention": "off",
|
||||
"@typescript-eslint/semi": "warn",
|
||||
"curly": "warn",
|
||||
"eqeqeq": "warn",
|
||||
"no-throw-literal": "warn",
|
||||
"semi": "off"
|
||||
"semi": "off",
|
||||
"@typescript-eslint/no-floating-promises": "warn"
|
||||
},
|
||||
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
|
||||
}
|
||||
|
|
|
|||
4
core/.gitignore
vendored
4
core/.gitignore
vendored
|
|
@ -3,4 +3,6 @@ target
|
|||
**/.DS_Store
|
||||
npm-debug.log*
|
||||
.env
|
||||
.continue-test
|
||||
.continue-test
|
||||
testDir
|
||||
coverage
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { IDE, Location } from "..";
|
||||
import { LANGUAGES } from "./languages";
|
||||
import { getSymbolsForSnippet } from "./ranking";
|
||||
import { IDE, Location } from "../index.js";
|
||||
import { LANGUAGES } from "./languages.js";
|
||||
import { getSymbolsForSnippet } from "./ranking.js";
|
||||
|
||||
interface FileInfo {
|
||||
filepath: string;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { stopAtStopTokens } from "../../autocomplete/charStream";
|
||||
import { stopAtStopTokens } from "./charStream";
|
||||
|
||||
describe("stopAtStopTokens", () => {
|
||||
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
|
||||
|
|
@ -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[],
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ import {
|
|||
import { isOnlyPunctuationAndWhitespace } from "./filter.js";
|
||||
import { AutocompleteLanguageInfo } from "./languages.js";
|
||||
import {
|
||||
avoidPathLine,
|
||||
avoidPathLineAndEmptyComments,
|
||||
noTopLevelKeywordsMidline,
|
||||
skipPrefixes,
|
||||
stopAtLines,
|
||||
|
|
@ -52,6 +52,7 @@ import { getTemplateForModel } from "./templates.js";
|
|||
import { GeneratorReuseManager } from "./util.js";
|
||||
// @prettier-ignore
|
||||
import Handlebars from "handlebars";
|
||||
import { getConfigJsonPath } from "../util/paths.js";
|
||||
|
||||
export interface AutocompleteInput {
|
||||
completionId: string;
|
||||
|
|
@ -249,6 +250,11 @@ export class CompletionProvider {
|
|||
...config.tabAutocompleteOptions,
|
||||
};
|
||||
|
||||
// Check whether we're in the continue config.json file
|
||||
if (input.filepath === getConfigJsonPath()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Check whether autocomplete is disabled for this file
|
||||
if (options.disableInFiles) {
|
||||
// Relative path needed for `ignore`
|
||||
|
|
@ -266,7 +272,8 @@ export class CompletionProvider {
|
|||
filepath = getBasename(filepath);
|
||||
}
|
||||
|
||||
const pattern = ignore().add(options.disableInFiles);
|
||||
// @ts-ignore
|
||||
const pattern = ignore.default().add(options.disableInFiles);
|
||||
if (pattern.ignores(filepath)) {
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -451,12 +458,12 @@ export class CompletionProvider {
|
|||
if (
|
||||
!shownGptClaudeWarning &&
|
||||
nonAutocompleteModels.some((model) => llm.model.includes(model)) &&
|
||||
!llm.model.includes("deepseek") &&
|
||||
!llm.model.includes("codestral")
|
||||
!llm.model.toLowerCase().includes("deepseek") &&
|
||||
!llm.model.toLowerCase().includes("codestral")
|
||||
) {
|
||||
shownGptClaudeWarning = true;
|
||||
throw new Error(
|
||||
`Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/walkthroughs/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
|
||||
`Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -471,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, {
|
||||
|
|
@ -574,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({
|
||||
|
|
@ -586,7 +596,14 @@ export class CompletionProvider {
|
|||
});
|
||||
} else {
|
||||
// Let the template function format snippets
|
||||
prompt = template(prefix, suffix, filepath, reponame, snippets);
|
||||
prompt = template(
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
lang.name,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
// Completion
|
||||
|
|
@ -675,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,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { LineFilter } from "./lineStream";
|
||||
import type { LineFilter } from "./lineStream.js";
|
||||
|
||||
export interface AutocompleteLanguageInfo {
|
||||
name: string;
|
||||
|
|
@ -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: [],
|
||||
};
|
||||
|
|
|
|||
421
core/autocomplete/lineStream.test.ts
Normal file
421
core/autocomplete/lineStream.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { ILLM } from "..";
|
||||
import { longestCommonSubsequence } from "../util/lcs";
|
||||
import { lineIsRepeated } from "./lineStream";
|
||||
import type { ILLM } from "../index.js";
|
||||
import { longestCommonSubsequence } from "../util/lcs.js";
|
||||
import { lineIsRepeated } from "./lineStream.js";
|
||||
|
||||
function rewritesLineAbove(completion: string, prefix: string): boolean {
|
||||
const lineAbove = prefix
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ interface AutocompleteTemplate {
|
|||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
) => string);
|
||||
completionOptions?: Partial<CompletionOptions>;
|
||||
|
|
@ -32,8 +33,8 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
|
|||
"<fim_prefix>",
|
||||
"<fim_suffix>",
|
||||
"<fim_middle>",
|
||||
"<|endoftext|>",
|
||||
"<file_sep>",
|
||||
"<|endoftext|>",
|
||||
"</fim_middle>",
|
||||
"</code>",
|
||||
],
|
||||
|
|
@ -69,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,
|
||||
];
|
||||
},
|
||||
|
|
@ -78,6 +81,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
|
|||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
): string => {
|
||||
return `[SUFFIX]${suffix}[PREFIX]${prefix}`;
|
||||
|
|
@ -109,6 +113,7 @@ const starcoder2FimTemplate: AutocompleteTemplate = {
|
|||
suffix: string,
|
||||
filename: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
): string => {
|
||||
const otherFiles =
|
||||
|
|
@ -129,8 +134,8 @@ const starcoder2FimTemplate: AutocompleteTemplate = {
|
|||
"<fim_prefix>",
|
||||
"<fim_suffix>",
|
||||
"<fim_middle>",
|
||||
"<|endoftext|>",
|
||||
"<file_sep>",
|
||||
"<|endoftext|>",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
|
@ -162,14 +167,17 @@ const codegeexFimTemplate: AutocompleteTemplate = {
|
|||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
): string => {
|
||||
const relativePaths = shortestRelativePaths([
|
||||
...snippets.map((snippet) => snippet.filepath),
|
||||
filepath,
|
||||
]);
|
||||
const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1]}\n###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
|
||||
|
|
@ -205,6 +213,7 @@ const holeFillerTemplate: AutocompleteTemplate = {
|
|||
suffix: string,
|
||||
filename: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
) => {
|
||||
// From https://github.com/VictorTaelin/AI-scripts
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.6.4/schema.json",
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true
|
||||
}
|
||||
},
|
||||
"formatter": {
|
||||
"indentStyle": "space"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +1,7 @@
|
|||
import {
|
||||
CustomCommand,
|
||||
SlashCommand,
|
||||
SlashCommandDescription,
|
||||
} from "../index.js";
|
||||
import { stripImages } from "../llm/images.js";
|
||||
import { renderTemplatedString } from "../llm/llms/index.js";
|
||||
import SlashCommands from "./slash/index.js";
|
||||
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
|
||||
import { stripImages } from "../llm/images";
|
||||
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
|
||||
import SlashCommands from "./slash";
|
||||
|
||||
export function slashFromCustomCommand(
|
||||
customCommand: CustomCommand,
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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) +
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
import GenerateTerminalCommand from "./cmd.js";
|
||||
import CommentSlashCommand from "./comment.js";
|
||||
import CommitMessageCommand from "./commit.js";
|
||||
import DraftIssueCommand from "./draftIssue.js";
|
||||
import EditSlashCommand from "./edit.js";
|
||||
import HttpSlashCommand from "./http.js";
|
||||
import ReviewMessageCommand from "./review.js";
|
||||
import ShareSlashCommand from "./share.js";
|
||||
import StackOverflowSlashCommand from "./stackOverflow.js";
|
||||
import GenerateTerminalCommand from "./cmd";
|
||||
import CommentSlashCommand from "./comment";
|
||||
import CommitMessageCommand from "./commit";
|
||||
import DraftIssueCommand from "./draftIssue";
|
||||
import EditSlashCommand from "./edit";
|
||||
import HttpSlashCommand from "./http";
|
||||
import ReviewMessageCommand from "./review";
|
||||
import ShareSlashCommand from "./share";
|
||||
import StackOverflowSlashCommand from "./stackOverflow";
|
||||
import OnboardSlashCommand from "./onboard";
|
||||
|
||||
export default [
|
||||
DraftIssueCommand,
|
||||
|
|
@ -18,4 +19,5 @@ export default [
|
|||
HttpSlashCommand,
|
||||
CommitMessageCommand,
|
||||
ReviewMessageCommand,
|
||||
OnboardSlashCommand,
|
||||
];
|
||||
|
|
|
|||
155
core/commands/slash/onboard.ts
Normal file
155
core/commands/slash/onboard.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
import { IDE, SlashCommand } from "../..";
|
||||
import * as fs from "fs/promises";
|
||||
import * as path from "path";
|
||||
import { stripImages } from "../../llm/images";
|
||||
import ignore from "ignore";
|
||||
import {
|
||||
defaultIgnoreDir,
|
||||
defaultIgnoreFile,
|
||||
gitIgArrayFromFile,
|
||||
} from "../../indexing/ignore";
|
||||
|
||||
const LANGUAGE_DEP_MGMT_FILENAMES = [
|
||||
"package.json", // JavaScript (Node.js)
|
||||
"requirements.txt", // Python
|
||||
"Gemfile", // Ruby
|
||||
"pom.xml", // Java (Maven)
|
||||
"build.gradle", // Java (Gradle)
|
||||
"composer.json", // PHP
|
||||
"Cargo.toml", // Rust
|
||||
"go.mod", // Go
|
||||
"packages.config", // C# (.NET)
|
||||
"*.csproj", // C# (.NET Core)
|
||||
"pubspec.yaml", // Dart
|
||||
"Project.toml", // Julia
|
||||
"mix.exs", // Elixir
|
||||
"rebar.config", // Erlang
|
||||
"shard.yml", // Crystal
|
||||
"Package.swift", // Swift
|
||||
"dependencies.gradle", // Kotlin (when using Gradle)
|
||||
"Podfile", // Objective-C/Swift (CocoaPods)
|
||||
"*.cabal", // Haskell
|
||||
"dub.json", // D
|
||||
];
|
||||
|
||||
const MAX_EXPLORE_DEPTH = 2;
|
||||
|
||||
const OnboardSlashCommand: SlashCommand = {
|
||||
name: "onboard",
|
||||
description: "Familiarize yourself with the codebase",
|
||||
run: async function* ({ llm, ide }) {
|
||||
const [workspaceDir] = await ide.getWorkspaceDirs();
|
||||
|
||||
const context = await gatherProjectContext(workspaceDir, ide);
|
||||
const prompt = createOnboardingPrompt(context);
|
||||
|
||||
for await (const chunk of llm.streamChat([
|
||||
{ role: "user", content: prompt },
|
||||
])) {
|
||||
yield stripImages(chunk.content);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
|
||||
const entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
|
||||
let ig = ignore().add(defaultIgnoreDir).add(defaultIgnoreFile);
|
||||
|
||||
const gitIgnorePath = path.join(dir, ".gitignore");
|
||||
|
||||
const hasIgnoreFile = await fs
|
||||
.access(gitIgnorePath)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
|
||||
if (hasIgnoreFile) {
|
||||
const gitIgnore = await ide.readFile(gitIgnorePath);
|
||||
const igPatterns = gitIgArrayFromFile(gitIgnore);
|
||||
|
||||
ig = ig.add(igPatterns);
|
||||
}
|
||||
|
||||
const filteredEntries = entries.filter((entry) => !ig.ignores(entry.name));
|
||||
|
||||
return filteredEntries;
|
||||
}
|
||||
|
||||
async function gatherProjectContext(
|
||||
workspaceDir: string,
|
||||
ide: IDE,
|
||||
): Promise<string> {
|
||||
let context = "";
|
||||
|
||||
async function exploreDirectory(dir: string, currentDepth: number = 0) {
|
||||
if (currentDepth > MAX_EXPLORE_DEPTH) {
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = await getEntriesFilteredByIgnore(dir, ide);
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
const relativePath = path.relative(workspaceDir, fullPath);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
context += `\nFolder: ${relativePath}\n`;
|
||||
await exploreDirectory(fullPath, currentDepth + 1);
|
||||
} else {
|
||||
if (entry.name.toLowerCase() === "readme.md") {
|
||||
const content = await fs.readFile(fullPath, "utf-8");
|
||||
context += `README for ${relativePath}:\n${content}\n\n`;
|
||||
} else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.name)) {
|
||||
const content = await fs.readFile(fullPath, "utf-8");
|
||||
context += `${entry.name} for ${relativePath}:\n${content}\n\n`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await exploreDirectory(workspaceDir);
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
function createOnboardingPrompt(context: string): string {
|
||||
return `
|
||||
As a helpful AI assistant, your task is to onboard a new developer to this project.
|
||||
Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview:
|
||||
|
||||
${context}
|
||||
|
||||
Please provide an overview of the project with the following guidelines:
|
||||
- Determine the most important folders in the project, at most 10
|
||||
- Go through each important folder step-by-step:
|
||||
- Explain what each folder does in isolation by summarzing the README or package.json file, if available
|
||||
- Mention the most popular or common packages used in that folder and their roles.
|
||||
- After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture:
|
||||
- How different parts of the codebase fit together.
|
||||
- The overall project architecture or design patterns evident from the folder structure and dependencies.
|
||||
- Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown.
|
||||
|
||||
Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole.
|
||||
|
||||
Here is an example of a valid response:
|
||||
|
||||
## Important folders
|
||||
|
||||
### /folder1
|
||||
- Description: Contains the main application logic.
|
||||
- Key packages: Express.js for routing, Mongoose for database operations.
|
||||
|
||||
#### /folder1/folder2
|
||||
|
||||
## Project Architecture
|
||||
- The frontend is built using React and Redux for state management.
|
||||
- The backend is a Node.js application using Express.js for routing and Mongoose for database operations.
|
||||
- The application follows a Model-View-Controller (MVC) architecture.
|
||||
|
||||
## Additional Insights
|
||||
- The project is using a monorepo structure.
|
||||
- The project uses TypeScript for type checking.
|
||||
`;
|
||||
}
|
||||
|
||||
export default OnboardSlashCommand;
|
||||
42
core/config/ConfigHandler.test.ts
Normal file
42
core/config/ConfigHandler.test.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { defaultConfig } from "./default";
|
||||
import { getConfigTsPath } from "../util/paths";
|
||||
import { testConfigHandler } from "../test/util/fixtures";
|
||||
import { TEST_DIR } from "../test/util/testDir";
|
||||
|
||||
describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
||||
test("should show only local profile", () => {
|
||||
const profiles = testConfigHandler.listProfiles();
|
||||
expect(profiles.length).toBe(1);
|
||||
expect(profiles[0].id).toBe("local");
|
||||
|
||||
const currentProfile = testConfigHandler.currentProfile;
|
||||
expect(currentProfile.profileId).toBe("local");
|
||||
});
|
||||
|
||||
test("should load the default config successfully", async () => {
|
||||
const config = await testConfigHandler.loadConfig();
|
||||
expect(config.models.length).toBe(defaultConfig.models.length);
|
||||
});
|
||||
|
||||
test.skip("should add a system message from config.ts", async () => {
|
||||
const configTs = `export function modifyConfig(config: Config): Config {
|
||||
config.systemMessage = "SYSTEM";
|
||||
return config;
|
||||
}`;
|
||||
fs.writeFileSync(getConfigTsPath(), configTs);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
const config = await testConfigHandler.reloadConfig();
|
||||
expect(config.systemMessage).toBe("SYSTEM");
|
||||
});
|
||||
|
||||
test.skip("should acknowledge override from .continuerc.json", async () => {
|
||||
fs.writeFileSync(
|
||||
path.join(TEST_DIR, ".continuerc.json"),
|
||||
JSON.stringify({ systemMessage: "SYSTEM2" }),
|
||||
);
|
||||
const config = await testConfigHandler.reloadConfig();
|
||||
expect(config.systemMessage).toBe("SYSTEM2");
|
||||
});
|
||||
});
|
||||
|
|
@ -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(
|
||||
|
|
@ -105,6 +105,37 @@ export class ConfigHandler {
|
|||
private profiles: ProfileLifecycleManager[];
|
||||
private selectedProfileId: string;
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly writeLog: (text: string) => Promise<void>,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
this.writeLog = writeLog;
|
||||
|
||||
// Set local profile as default
|
||||
const localProfileLoader = new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
controlPlaneClient,
|
||||
writeLog,
|
||||
);
|
||||
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
|
||||
this.selectedProfileId = localProfileLoader.profileId;
|
||||
|
||||
// Always load local profile immediately in case control plane doesn't load
|
||||
try {
|
||||
this.loadConfig();
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
|
||||
// Load control plane profiles
|
||||
this.fetchControlPlaneProfiles();
|
||||
}
|
||||
|
||||
// This will be the local profile
|
||||
private get fallbackProfile() {
|
||||
return this.profiles[0];
|
||||
|
|
@ -163,37 +194,6 @@ export class ConfigHandler {
|
|||
});
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly writeLog: (text: string) => Promise<void>,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
this.writeLog = writeLog;
|
||||
|
||||
// Set local profile as default
|
||||
const localProfileLoader = new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
controlPlaneClient,
|
||||
writeLog,
|
||||
);
|
||||
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
|
||||
this.selectedProfileId = localProfileLoader.profileId;
|
||||
|
||||
// Always load local profile immediately in case control plane doesn't load
|
||||
try {
|
||||
this.loadConfig();
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
|
||||
// Load control plane profiles
|
||||
this.fetchControlPlaneProfiles();
|
||||
}
|
||||
|
||||
async setSelectedProfile(profileId: string) {
|
||||
this.selectedProfileId = profileId;
|
||||
const newConfig = await this.loadConfig();
|
||||
|
|
@ -225,7 +225,9 @@ export class ConfigHandler {
|
|||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
Promise.resolve(sessionInfo),
|
||||
);
|
||||
this.fetchControlPlaneProfiles();
|
||||
this.fetchControlPlaneProfiles().catch((e) => {
|
||||
console.error("Failed to fetch control plane profiles: ", e);
|
||||
});
|
||||
}
|
||||
|
||||
private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = [];
|
||||
|
|
@ -258,6 +260,7 @@ export class ConfigHandler {
|
|||
const newConfig = await this.currentProfile.reloadConfig();
|
||||
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
|
||||
this.notifyConfigListeners(newConfig);
|
||||
return newConfig;
|
||||
}
|
||||
|
||||
getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ import CustomLLMClass from "../llm/llms/CustomLLM.js";
|
|||
import FreeTrial from "../llm/llms/FreeTrial.js";
|
||||
import { llmFromDescription } from "../llm/llms/index.js";
|
||||
|
||||
import { execSync } from "child_process";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider.js";
|
||||
import { fetchwithRequestOptions } from "../util/fetchWithOptions.js";
|
||||
|
|
@ -62,8 +63,6 @@ import {
|
|||
slashCommandFromPromptFile,
|
||||
} from "./promptFile.js";
|
||||
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
|
||||
let content = fs.readFileSync(filepath, "utf8");
|
||||
const config = JSONC.parse(content) as unknown as SerializedContinueConfig;
|
||||
|
|
@ -356,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(
|
||||
|
|
@ -465,6 +466,7 @@ function finalToBrowserConfig(
|
|||
systemMessage: m.systemMessage,
|
||||
requestOptions: m.requestOptions,
|
||||
promptTemplates: m.promptTemplates as any,
|
||||
capabilities: m.capabilities,
|
||||
})),
|
||||
systemMessage: final.systemMessage,
|
||||
completionOptions: final.completionOptions,
|
||||
|
|
@ -534,7 +536,7 @@ async function buildConfigTs() {
|
|||
);
|
||||
} else {
|
||||
// Dynamic import esbuild so potentially disastrous errors can be caught
|
||||
const esbuild = require("esbuild");
|
||||
const esbuild = await import("esbuild");
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [getConfigTsPath()],
|
||||
|
|
@ -586,8 +588,10 @@ async function loadFullConfigNode(
|
|||
try {
|
||||
// Try config.ts first
|
||||
const configJsPath = getConfigJsPath();
|
||||
const module = await require(configJsPath);
|
||||
delete require.cache[require.resolve(configJsPath)];
|
||||
const module = await import(configJsPath);
|
||||
if (typeof require !== "undefined") {
|
||||
delete require.cache[require.resolve(configJsPath)];
|
||||
}
|
||||
if (!module.modifyConfig) {
|
||||
throw new Error("config.ts does not export a modifyConfig function.");
|
||||
}
|
||||
|
|
@ -603,8 +607,10 @@ async function loadFullConfigNode(
|
|||
const configJsPathForRemote = getConfigJsPathForRemote(
|
||||
ideSettings.remoteConfigServerUrl,
|
||||
);
|
||||
const module = await require(configJsPathForRemote);
|
||||
delete require.cache[require.resolve(configJsPathForRemote)];
|
||||
const module = await import(configJsPathForRemote);
|
||||
if (typeof require !== "undefined") {
|
||||
delete require.cache[require.resolve(configJsPathForRemote)];
|
||||
}
|
||||
if (!module.modifyConfig) {
|
||||
throw new Error("config.ts does not export a modifyConfig function.");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
import { ConfigJson } from "@continuedev/config-types";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import {
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
SerializedContinueConfig,
|
||||
} from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { IProfileLoader } from "./IProfileLoader";
|
||||
import doLoadConfig from "./doLoadConfig";
|
||||
} from "../../index.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
|
||||
export default class ControlPlaneProfileLoader implements IProfileLoader {
|
||||
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
|
||||
|
|
@ -50,6 +50,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
serializedConfig,
|
||||
this.workspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// ProfileHandlers manage the loading of a config, allowing us to abstract over different ways of getting to a ContinueConfig
|
||||
|
||||
import { ContinueConfig } from "../..";
|
||||
import { ContinueConfig } from "../../index.js";
|
||||
|
||||
// After we have the ContinueConfig, the ConfigHandler takes care of everything else (loading models, lifecycle, etc.)
|
||||
export interface IProfileLoader {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { ContinueConfig, IDE, IdeSettings } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import doLoadConfig from "./doLoadConfig";
|
||||
import { IProfileLoader } from "./IProfileLoader";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
export default class LocalProfileLoader implements IProfileLoader {
|
||||
static ID = "local";
|
||||
|
|
|
|||
|
|
@ -1,14 +1,17 @@
|
|||
import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
|
||||
import {
|
||||
ContinueRcJson,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
SerializedContinueConfig,
|
||||
} from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { loadFullConfigNode } from "../load";
|
||||
} from "../../index.js";
|
||||
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(
|
||||
ide: IDE,
|
||||
|
|
@ -16,6 +19,7 @@ export default async function doLoadConfig(
|
|||
controlPlaneClient: ControlPlaneClient,
|
||||
writeLog: (message: string) => Promise<void>,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
workspaceId?: string,
|
||||
) {
|
||||
let workspaceConfigs: ContinueRcJson[] = [];
|
||||
try {
|
||||
|
|
@ -46,14 +50,18 @@ 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
|
||||
uniqueId,
|
||||
ideInfo.extensionVersion,
|
||||
workspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -65,5 +73,16 @@ export default async function doLoadConfig(
|
|||
},
|
||||
);
|
||||
|
||||
if (newConfig.embeddingsProvider?.providerName === "continue-proxy") {
|
||||
(
|
||||
newConfig.embeddingsProvider as ContinueProxyEmbeddingsProvider
|
||||
).workOsAccessToken = workOsAccessToken;
|
||||
}
|
||||
|
||||
if (newConfig.reranker?.name === "continue-proxy") {
|
||||
(newConfig.reranker as ContinueProxyReranker).workOsAccessToken =
|
||||
workOsAccessToken;
|
||||
}
|
||||
|
||||
return newConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 { renderTemplatedString } from "../llm/llms/index.js";
|
||||
import { getBasename } from "../util/index.js";
|
||||
import { renderTemplatedString } from "../promptFiles/renderTemplatedString";
|
||||
import { getBasename } from "../util/index";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
|
||||
|
||||
|
|
@ -15,6 +15,7 @@ export async function getPromptFiles(
|
|||
): Promise<{ path: string; content: string }[]> {
|
||||
try {
|
||||
const exists = await ide.fileExists(dir);
|
||||
|
||||
if (!exists) {
|
||||
return [];
|
||||
}
|
||||
|
|
@ -34,7 +35,7 @@ export async function getPromptFiles(
|
|||
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
# Continue will automatically create a slash command for each prompt in the .prompts folder
|
||||
# To learn more, see the full .prompt file reference: https://docs.continue.dev/walkthroughs/prompt-files
|
||||
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
|
||||
temperature: 0.0
|
||||
---
|
||||
{{{ diff }}}
|
||||
|
|
@ -89,6 +90,32 @@ export function slashCommandFromPromptFile(
|
|||
path: string,
|
||||
content: string,
|
||||
): SlashCommand {
|
||||
const { name, description, systemMessage, prompt } = parsePromptFile(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
run: async function* (context) {
|
||||
const userInput = extractUserInput(context.input, name);
|
||||
const renderedPrompt = await renderPrompt(prompt, context, userInput);
|
||||
const messages = updateChatHistory(
|
||||
context.history,
|
||||
name,
|
||||
renderedPrompt,
|
||||
systemMessage,
|
||||
);
|
||||
|
||||
for await (const chunk of context.llm.streamChat(messages)) {
|
||||
yield stripImages(chunk.content);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parsePromptFile(path: string, content: string) {
|
||||
let [preambleRaw, prompt] = content.split("\n---\n");
|
||||
if (prompt === undefined) {
|
||||
prompt = preambleRaw;
|
||||
|
|
@ -105,114 +132,122 @@ export function slashCommandFromPromptFile(
|
|||
prompt = prompt.split("</system>")[1].trim();
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
run: async function* ({
|
||||
input,
|
||||
llm,
|
||||
history,
|
||||
ide,
|
||||
config,
|
||||
fetch,
|
||||
selectedCode,
|
||||
addContextItem,
|
||||
}) {
|
||||
// Remove slash command prefix from input
|
||||
let userInput = input;
|
||||
if (userInput.startsWith(`/${name}`)) {
|
||||
userInput = userInput
|
||||
.slice(name.length + 1, userInput.length)
|
||||
.trimStart();
|
||||
}
|
||||
return { name, description, systemMessage, prompt };
|
||||
}
|
||||
|
||||
// Render prompt template
|
||||
const helpers: [string, Handlebars.HelperDelegate][] | undefined =
|
||||
config.contextProviders?.map((provider) => {
|
||||
return [
|
||||
provider.description.title,
|
||||
async (context: any) => {
|
||||
const items = await provider.getContextItems(context, {
|
||||
embeddingsProvider: config.embeddingsProvider,
|
||||
fetch,
|
||||
fullInput: userInput,
|
||||
ide,
|
||||
llm,
|
||||
reranker: config.reranker,
|
||||
selectedCode,
|
||||
});
|
||||
items.forEach((item) =>
|
||||
addContextItem({
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
}),
|
||||
);
|
||||
return items.map((item) => item.content).join("\n\n");
|
||||
},
|
||||
];
|
||||
});
|
||||
function extractUserInput(input: string, commandName: string): string {
|
||||
if (input.startsWith(`/${commandName}`)) {
|
||||
return input.slice(commandName.length + 1).trimStart();
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
// A few context providers that don't need to be in config.json to work in .prompt files
|
||||
const diff = await ide.getDiff();
|
||||
const currentFilePath = await ide.getCurrentFile();
|
||||
const promptUserInput = await renderTemplatedString(
|
||||
prompt,
|
||||
ide.readFile.bind(ide),
|
||||
{
|
||||
input: userInput,
|
||||
diff,
|
||||
currentFile: currentFilePath
|
||||
? await ide.readFile(currentFilePath)
|
||||
: undefined,
|
||||
},
|
||||
helpers,
|
||||
async function renderPrompt(prompt: string, context: any, userInput: string) {
|
||||
const helpers = getContextProviderHelpers(context);
|
||||
|
||||
// A few context providers that don't need to be in config.json to work in .prompt files
|
||||
const diff = await context.ide.getDiff();
|
||||
const currentFilePath = await context.ide.getCurrentFile();
|
||||
const currentFile = currentFilePath
|
||||
? await context.ide.readFile(currentFilePath)
|
||||
: undefined;
|
||||
|
||||
return renderTemplatedString(
|
||||
prompt,
|
||||
context.ide.readFile.bind(context.ide),
|
||||
{ diff, currentFile, input: userInput },
|
||||
helpers,
|
||||
);
|
||||
}
|
||||
|
||||
function getContextProviderHelpers(
|
||||
context: any,
|
||||
): Array<[string, Handlebars.HelperDelegate]> | undefined {
|
||||
return context.config.contextProviders?.map((provider: any) => [
|
||||
provider.description.title,
|
||||
async (helperContext: any) => {
|
||||
const items = await provider.getContextItems(helperContext, {
|
||||
config: context.config,
|
||||
embeddingsProvider: context.config.embeddingsProvider,
|
||||
fetch: context.fetch,
|
||||
fullInput: context.input,
|
||||
ide: context.ide,
|
||||
llm: context.llm,
|
||||
reranker: context.config.reranker,
|
||||
selectedCode: context.selectedCode,
|
||||
});
|
||||
|
||||
items.forEach((item: any) =>
|
||||
context.addContextItem(createContextItem(item, provider)),
|
||||
);
|
||||
|
||||
const messages = [...history];
|
||||
// Find the last chat message with this slash command and replace it with the user input
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const { role, content } = messages[i];
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
return items.map((item: any) => item.content).join("\n\n");
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
if (
|
||||
Array.isArray(content) &&
|
||||
content.some((part) => part.text?.startsWith(`/${name}`))
|
||||
) {
|
||||
messages[i] = {
|
||||
...messages[i],
|
||||
content: content.map((part) => {
|
||||
return part.text?.startsWith(`/${name}`)
|
||||
? { ...part, text: promptUserInput }
|
||||
: part;
|
||||
}),
|
||||
};
|
||||
break;
|
||||
} else if (
|
||||
typeof content === "string" &&
|
||||
content.startsWith(`/${name}`)
|
||||
) {
|
||||
messages[i] = { ...messages[i], content: promptUserInput };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// System message
|
||||
if (systemMessage) {
|
||||
if (messages[0]?.role === "system") {
|
||||
messages[0].content = systemMessage;
|
||||
} else {
|
||||
messages.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of llm.streamChat(messages)) {
|
||||
yield stripImages(chunk.content);
|
||||
}
|
||||
function createContextItem(item: any, provider: any) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function updateChatHistory(
|
||||
history: any[],
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
systemMessage?: string,
|
||||
) {
|
||||
const messages = [...history];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const { role, content } = messages[i];
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
|
||||
messages[i] = updateArrayContent(
|
||||
messages[i],
|
||||
commandName,
|
||||
renderedPrompt,
|
||||
);
|
||||
break;
|
||||
}
|
||||
} else if (
|
||||
typeof content === "string" &&
|
||||
content.startsWith(`/${commandName}`)
|
||||
) {
|
||||
messages[i] = { ...messages[i], content: renderedPrompt };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (systemMessage) {
|
||||
messages[0]?.role === "system"
|
||||
? (messages[0].content = systemMessage)
|
||||
: messages.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
function updateArrayContent(
|
||||
message: any,
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
) {
|
||||
return {
|
||||
...message,
|
||||
content: message.content.map((part: any) =>
|
||||
part.text?.startsWith(`/${commandName}`)
|
||||
? { ...part, text: renderedPrompt }
|
||||
: part,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,28 +1,5 @@
|
|||
const Types = `
|
||||
declare global {
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
windowId: string;
|
||||
serverUrl: string;
|
||||
vscMachineId: string;
|
||||
vscMediaUrl: string;
|
||||
fullColorTheme?: {
|
||||
rules?: {
|
||||
token?: string;
|
||||
foreground?: string;
|
||||
}[];
|
||||
};
|
||||
colorThemeName?: string;
|
||||
workspacePaths?: string[];
|
||||
postIntellijMessage?: (
|
||||
messageType: string,
|
||||
data: any,
|
||||
messageIde: string,
|
||||
) => void;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChunkWithoutID {
|
||||
content: string;
|
||||
startLine: number;
|
||||
|
|
@ -507,6 +484,7 @@ declare global {
|
|||
| "gemini"
|
||||
| "mistral"
|
||||
| "bedrock"
|
||||
| "sagemaker"
|
||||
| "deepinfra"
|
||||
| "flowise"
|
||||
| "groq"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import {
|
|||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
import getDatabaseAdapter from "dbinfoz";
|
||||
|
||||
class DatabaseContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
|
|
@ -30,10 +31,9 @@ class DatabaseContextProvider extends BaseContextProvider {
|
|||
|
||||
const [connectionName, table] = query.split(".");
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
if (connection.name === connectionName) {
|
||||
// @ts-ignore (incorrect typings on module's declaration file)
|
||||
const adapter = getDatabaseAdapter(
|
||||
connection.connection_type,
|
||||
connection.connection,
|
||||
|
|
@ -87,9 +87,8 @@ class DatabaseContextProvider extends BaseContextProvider {
|
|||
return contextItems;
|
||||
}
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
// @ts-ignore (incorrect typings on module's declaration file)
|
||||
const adapter = getDatabaseAdapter(
|
||||
connection.connection_type,
|
||||
connection.connection,
|
||||
|
|
|
|||
|
|
@ -1,21 +1,19 @@
|
|||
import { BaseContextProvider } from "../";
|
||||
import {
|
||||
Chunk,
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
EmbeddingsProvider,
|
||||
LoadSubmenuItemsArgs,
|
||||
Reranker,
|
||||
} from "../../index.js";
|
||||
import { DocsService } from "../../indexing/docs/DocsService.js";
|
||||
import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js";
|
||||
import { Telemetry } from "../../util/posthog.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
} from "../..";
|
||||
import DocsService from "../../indexing/docs/DocsService";
|
||||
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
|
||||
class DocsContextProvider extends BaseContextProvider {
|
||||
static DEFAULT_N_RETRIEVE = 30;
|
||||
static DEFAULT_N_FINAL = 15;
|
||||
static nRetrieve = 30;
|
||||
static nFinal = 15;
|
||||
static description: ContextProviderDescription = {
|
||||
title: "docs",
|
||||
displayTitle: "Docs",
|
||||
|
|
@ -23,11 +21,8 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
private docsService: DocsService;
|
||||
|
||||
constructor(options: any) {
|
||||
super(options);
|
||||
this.docsService = DocsService.getInstance();
|
||||
}
|
||||
|
||||
private async _rerankChunks(
|
||||
|
|
@ -46,14 +41,14 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
|
||||
chunksCopy = chunksCopy.splice(
|
||||
0,
|
||||
this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL,
|
||||
this.options?.nFinal ?? DocsContextProvider.nFinal,
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn(`Failed to rerank docs results: ${e}`);
|
||||
|
||||
chunksCopy = chunksCopy.splice(
|
||||
0,
|
||||
this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL,
|
||||
this.options?.nFinal ?? DocsContextProvider.nFinal,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -84,14 +79,15 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ideInfo = await extras.ide.getIdeInfo();
|
||||
const isJetBrains = ideInfo.ideType === "jetbrains";
|
||||
const docsService = DocsService.getSingleton();
|
||||
|
||||
if (!docsService) {
|
||||
console.error(`${DocsService.name} has not been initialized`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const isJetBrainsAndPreIndexedDocsProvider =
|
||||
this.docsService.isJetBrainsAndPreIndexedDocsProvider(
|
||||
ideInfo,
|
||||
extras.embeddingsProvider.id,
|
||||
);
|
||||
await docsService.isJetBrainsAndPreIndexedDocsProvider();
|
||||
|
||||
if (isJetBrainsAndPreIndexedDocsProvider) {
|
||||
extras.ide.errorPopup(
|
||||
|
|
@ -106,29 +102,25 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
|
||||
const preIndexedDoc = preIndexedDocs[query];
|
||||
|
||||
let embeddingsProvider: EmbeddingsProvider;
|
||||
|
||||
if (!!preIndexedDoc && !isJetBrains) {
|
||||
// Pre-indexed docs should be filtered out in `loadSubmenuItems`,
|
||||
// for JetBrains users, but we sanity check that here
|
||||
if (!!preIndexedDoc) {
|
||||
Telemetry.capture("docs_pre_indexed_doc_used", {
|
||||
doc: preIndexedDoc["title"],
|
||||
});
|
||||
|
||||
embeddingsProvider = DocsService.preIndexedDocsEmbeddingsProvider;
|
||||
} else {
|
||||
embeddingsProvider = extras.embeddingsProvider;
|
||||
}
|
||||
|
||||
const embeddingsProvider =
|
||||
await docsService.getEmbeddingsProvider(!!preIndexedDoc);
|
||||
|
||||
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
|
||||
|
||||
let chunks = await this.docsService.retrieve(
|
||||
let chunks = await docsService.retrieveChunks(
|
||||
query,
|
||||
vector,
|
||||
this.options?.nRetrieve ?? DocsContextProvider.DEFAULT_N_RETRIEVE,
|
||||
embeddingsProvider.id,
|
||||
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
|
||||
);
|
||||
|
||||
const favicon = await docsService.getFavicon(query);
|
||||
|
||||
if (extras.reranker) {
|
||||
chunks = await this._rerankChunks(
|
||||
chunks,
|
||||
|
|
@ -140,6 +132,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
return [
|
||||
...chunks
|
||||
.map((chunk) => ({
|
||||
icon: favicon,
|
||||
name: chunk.filepath.includes("/tree/main") // For display of GitHub files
|
||||
? chunk.filepath
|
||||
.split("/")
|
||||
|
|
@ -168,17 +161,19 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const ideInfo = await args.ide.getIdeInfo();
|
||||
const isJetBrains = ideInfo.ideType === "jetbrains";
|
||||
const configSites = [
|
||||
...new Set([...(this.options?.sites || []), ...(args.config.docs || [])]),
|
||||
];
|
||||
const docsService = DocsService.getSingleton();
|
||||
|
||||
if (!docsService) {
|
||||
console.error(`${DocsService.name} has not been initialized`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const docs = (await docsService.list()) ?? [];
|
||||
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
|
||||
|
||||
const submenuItemsMap = new Map<string, ContextSubmenuItem>();
|
||||
|
||||
if (!isJetBrains) {
|
||||
// Currently, we generate and host embeddings for pre-indexed docs using transformers.js.
|
||||
// However, we don't ship transformers.js with the JetBrains extension.
|
||||
// So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs.
|
||||
if (canUsePreindexedDocs) {
|
||||
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
|
||||
submenuItemsMap.set(startUrl, {
|
||||
title,
|
||||
|
|
@ -191,25 +186,18 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
}
|
||||
}
|
||||
|
||||
for (const { title, baseUrl } of await this.docsService.list()) {
|
||||
submenuItemsMap.set(baseUrl, {
|
||||
title,
|
||||
id: baseUrl,
|
||||
description: new URL(baseUrl).hostname,
|
||||
});
|
||||
}
|
||||
|
||||
for (const { startUrl, title } of configSites) {
|
||||
for (const { startUrl, title, favicon } of docs) {
|
||||
submenuItemsMap.set(startUrl, {
|
||||
title,
|
||||
id: startUrl,
|
||||
description: new URL(startUrl).hostname,
|
||||
icon: favicon,
|
||||
});
|
||||
}
|
||||
|
||||
const submenuItems = Array.from(submenuItemsMap.values());
|
||||
|
||||
if (!isJetBrains) {
|
||||
if (canUsePreindexedDocs) {
|
||||
return this._sortByPreIndexedDocs(submenuItems);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { RequestOptions } from "../../../index.js";
|
||||
const { convert: adf2md } = require("adf-to-md");
|
||||
|
||||
// @ts-ignore
|
||||
import adf2md from "adf-to-md";
|
||||
interface JiraClientOptions {
|
||||
domain: string;
|
||||
username: string;
|
||||
|
|
|
|||
|
|
@ -20,7 +20,9 @@ class PostgresContextProvider extends BaseContextProvider {
|
|||
static DEFAULT_SAMPLE_ROWS = 3;
|
||||
|
||||
private async getPool() {
|
||||
const pg = await require("pg");
|
||||
// @ts-ignore
|
||||
const pg = await import("pg");
|
||||
|
||||
return new pg.Pool({
|
||||
host: this.options.host,
|
||||
port: this.options.port,
|
||||
|
|
@ -35,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);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { ContextProviderName } from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
import CodeContextProvider from "./CodeContextProvider.js";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider.js";
|
||||
import ContinueProxyContextProvider from "./ContinueProxyContextProvider.js";
|
||||
import CurrentFileContextProvider from "./CurrentFileContextProvider.js";
|
||||
import DatabaseContextProvider from "./DatabaseContextProvider.js";
|
||||
|
|
|
|||
46
core/context/rerankers/ContinueProxyReranker.ts
Normal file
46
core/context/rerankers/ContinueProxyReranker.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import fetch from "node-fetch";
|
||||
import { CONTROL_PLANE_URL } from "../../control-plane/client.js";
|
||||
import { Chunk, Reranker } from "../../index.js";
|
||||
|
||||
export class ContinueProxyReranker implements Reranker {
|
||||
name = "continue-proxy";
|
||||
|
||||
private _workOsAccessToken: string | undefined = undefined;
|
||||
|
||||
get workOsAccessToken(): string | undefined {
|
||||
return this._workOsAccessToken;
|
||||
}
|
||||
|
||||
set workOsAccessToken(value: string | undefined) {
|
||||
if (this._workOsAccessToken !== value) {
|
||||
this._workOsAccessToken = value;
|
||||
this.params.apiKey = value!;
|
||||
}
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly params: {
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
},
|
||||
) {}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
const url = new URL("/model-proxy/v1/rerank", CONTROL_PLANE_URL);
|
||||
const resp = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.params.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
model: this.params.model,
|
||||
}),
|
||||
});
|
||||
const data: any = await resp.json();
|
||||
const results = data.data.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,16 @@
|
|||
import { RerankerName } from "../../index.js";
|
||||
import { CohereReranker } from "./cohere.js";
|
||||
import { ContinueProxyReranker } from "./ContinueProxyReranker.js";
|
||||
import { FreeTrialReranker } from "./freeTrial.js";
|
||||
import { LLMReranker } from "./llm.js";
|
||||
import { HuggingFaceTEIReranker } from "./tei.js";
|
||||
import { VoyageReranker } from "./voyage.js";
|
||||
import {HuggingFaceTEIReranker} from "./tei.js"
|
||||
|
||||
export const AllRerankers: { [key in RerankerName]: any } = {
|
||||
cohere: CohereReranker,
|
||||
llm: LLMReranker,
|
||||
voyage: VoyageReranker,
|
||||
"free-trial": FreeTrialReranker,
|
||||
"huggingface-tei": HuggingFaceTEIReranker
|
||||
"huggingface-tei": HuggingFaceTEIReranker,
|
||||
"continue-proxy": ContinueProxyReranker,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -12,6 +12,9 @@ export class VoyageReranker implements Reranker {
|
|||
) {}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || chunks.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const resp = await fetch("https://api.voyageai.com/v1/rerank", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import {
|
|||
} from "../../../index.js";
|
||||
import { chunkDocument } from "../../../indexing/chunk/chunk.js";
|
||||
import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js";
|
||||
import { MAX_CHUNK_SIZE } from "../../../llm/constants.js";
|
||||
import { retrieveFts } from "../fullTextSearch.js";
|
||||
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js";
|
||||
|
||||
|
|
@ -20,6 +19,7 @@ export interface RetrievalPipelineOptions {
|
|||
nRetrieve: number;
|
||||
nFinal: number;
|
||||
tags: BranchAndDir[];
|
||||
pathSep: string;
|
||||
filterDirectory?: string;
|
||||
}
|
||||
|
||||
|
|
@ -30,8 +30,10 @@ export interface IRetrievalPipeline {
|
|||
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
||||
private lanceDbIndex: LanceDbIndex;
|
||||
constructor(protected readonly options: RetrievalPipelineOptions) {
|
||||
this.lanceDbIndex = new LanceDbIndex(options.embeddingsProvider, (path) =>
|
||||
options.ide.readFile(path),
|
||||
this.lanceDbIndex = new LanceDbIndex(
|
||||
options.embeddingsProvider,
|
||||
(path) => options.ide.readFile(path),
|
||||
options.pathSep,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -60,7 +62,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
const fileChunks = chunkDocument({
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize: MAX_CHUNK_SIZE,
|
||||
maxChunkSize: this.options.embeddingsProvider.maxChunkSize,
|
||||
digest: filepath,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
nFinal,
|
||||
nRetrieve,
|
||||
tags,
|
||||
pathSep: await extras.ide.pathSep(),
|
||||
embeddingsProvider: extras.embeddingsProvider,
|
||||
reranker: extras.reranker,
|
||||
filterDirectory,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Chunk } from "../..";
|
||||
import { deduplicateArray } from "../../util";
|
||||
import { Chunk } from "../../index.js";
|
||||
import { deduplicateArray } from "../../util/index.js";
|
||||
|
||||
export function deduplicateChunks(chunks: Chunk[]): Chunk[] {
|
||||
return deduplicateArray(chunks, (a, b) => {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import { constants, getTimestamp } from "../../deploy/constants";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { constants, getTimestamp } from "../../deploy/constants.js";
|
||||
import { Telemetry } from "../../util/posthog.js";
|
||||
|
||||
export async function getHeaders() {
|
||||
return {
|
||||
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",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import os from "node:os";
|
||||
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider";
|
||||
import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider";
|
||||
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider";
|
||||
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider";
|
||||
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js";
|
||||
import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider.js";
|
||||
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js";
|
||||
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js";
|
||||
|
||||
function createAnalyticsProvider(
|
||||
config: Analytics,
|
||||
|
|
@ -39,6 +39,7 @@ export class TeamAnalytics {
|
|||
config: Analytics,
|
||||
uniqueId: string,
|
||||
extensionVersion: string,
|
||||
workspaceId?: string,
|
||||
) {
|
||||
TeamAnalytics.uniqueId = uniqueId;
|
||||
TeamAnalytics.os = os.platform();
|
||||
|
|
@ -49,7 +50,7 @@ export class TeamAnalytics {
|
|||
TeamAnalytics.provider = undefined;
|
||||
} else {
|
||||
TeamAnalytics.provider = createAnalyticsProvider(config);
|
||||
await TeamAnalytics.provider?.setup(config, uniqueId);
|
||||
await TeamAnalytics.provider?.setup(config, uniqueId, workspaceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,19 +1,19 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import fetch from "node-fetch";
|
||||
import { CONTROL_PLANE_URL } from "../client";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider";
|
||||
import { CONTROL_PLANE_URL } from "../client.js";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
|
||||
|
||||
export default class ContinueProxyAnalyticsProvider
|
||||
implements IAnalyticsProvider
|
||||
{
|
||||
uniqueId?: string;
|
||||
addOnId?: string;
|
||||
workspaceId?: string;
|
||||
|
||||
async capture(
|
||||
event: string,
|
||||
properties: { [key: string]: any },
|
||||
): Promise<void> {
|
||||
fetch(new URL(`/proxy/analytics/${this.addOnId}`, CONTROL_PLANE_URL), {
|
||||
fetch(new URL(`/proxy/analytics/${this.workspaceId}`, CONTROL_PLANE_URL), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
event,
|
||||
|
|
@ -23,9 +23,13 @@ export default class ContinueProxyAnalyticsProvider
|
|||
});
|
||||
}
|
||||
|
||||
async setup(config: Analytics, uniqueId: string): Promise<void> {
|
||||
async setup(
|
||||
config: Analytics,
|
||||
uniqueId: string,
|
||||
workspaceId?: string,
|
||||
): Promise<void> {
|
||||
this.uniqueId = uniqueId;
|
||||
this.addOnId = config.url?.split("/").slice(-1)[0];
|
||||
this.workspaceId = workspaceId;
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ export interface AnalyticsMetadata {
|
|||
|
||||
export interface IAnalyticsProvider {
|
||||
capture(event: string, properties: { [key: string]: any }): Promise<void>;
|
||||
setup(config: Analytics, uniqueId: string): Promise<void>;
|
||||
setup(
|
||||
config: Analytics,
|
||||
uniqueId: string,
|
||||
workspaceId?: string,
|
||||
): Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import net from "node:net";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
|
||||
|
||||
export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
|
||||
private host?: string;
|
||||
|
|
@ -28,9 +28,14 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
|
|||
});
|
||||
}
|
||||
|
||||
async setup(config: Analytics, uniqueId: string): Promise<void> {
|
||||
async setup(
|
||||
config: Analytics,
|
||||
uniqueId: string,
|
||||
workspaceId?: 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;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
|
||||
|
||||
export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
|
||||
client?: any;
|
||||
|
|
@ -16,7 +16,11 @@ export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
|
|||
});
|
||||
}
|
||||
|
||||
async setup(config: Analytics, uniqueId: string): Promise<void> {
|
||||
async setup(
|
||||
config: Analytics,
|
||||
uniqueId: string,
|
||||
workspaceId?: string,
|
||||
): Promise<void> {
|
||||
if (!config || !config.clientKey || !config.url) {
|
||||
this.client = undefined;
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { ConfigJson } from "@continuedev/config-types";
|
||||
import fetch, { RequestInit, Response } from "node-fetch";
|
||||
import { ModelDescription } from "..";
|
||||
import { ModelDescription } from "../index.js";
|
||||
|
||||
export interface ControlPlaneSessionInfo {
|
||||
accessToken: string;
|
||||
|
|
@ -18,9 +18,10 @@ export interface ControlPlaneWorkspace {
|
|||
|
||||
export interface ControlPlaneModelDescription extends ModelDescription {}
|
||||
|
||||
// export const CONTROL_PLANE_URL = "http://localhost:3001";
|
||||
export const CONTROL_PLANE_URL =
|
||||
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app";
|
||||
process.env.CONTROL_PLANE_ENV === "local"
|
||||
? "http://localhost:3001"
|
||||
: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app";
|
||||
|
||||
export class ControlPlaneClient {
|
||||
private static URL = CONTROL_PLANE_URL;
|
||||
|
|
@ -73,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;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ const modelDescriptionSchema = z.object({
|
|||
"gemini",
|
||||
"mistral",
|
||||
"bedrock",
|
||||
"sagemaker",
|
||||
"cloudflare",
|
||||
"azure",
|
||||
]),
|
||||
|
|
|
|||
274
core/core.ts
274
core/core.ts
|
|
@ -1,38 +1,34 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
import type {
|
||||
ContextItemId,
|
||||
EmbeddingsProvider,
|
||||
IDE,
|
||||
IndexingProgressUpdate,
|
||||
SiteIndexingConfig,
|
||||
} from ".";
|
||||
import { CompletionProvider } from "./autocomplete/completionProvider.js";
|
||||
import { ConfigHandler } from "./config/ConfigHandler.js";
|
||||
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
|
||||
import { CompletionProvider } from "./autocomplete/completionProvider";
|
||||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import {
|
||||
setupApiKeysMode,
|
||||
setupFreeTrialMode,
|
||||
setupLocalAfterFreeTrial,
|
||||
setupLocalMode,
|
||||
} from "./config/onboarding.js";
|
||||
import { createNewPromptFile } from "./config/promptFile.js";
|
||||
import { addModel, addOpenAIKey, deleteModel } from "./config/util.js";
|
||||
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache.js";
|
||||
import { ContinueServerClient } from "./continueServer/stubs/client.js";
|
||||
import { getAuthUrlForTokenPage } from "./control-plane/auth/index.js";
|
||||
} from "./config/onboarding";
|
||||
import { createNewPromptFile } from "./config/promptFile";
|
||||
import { addModel, addOpenAIKey, deleteModel } from "./config/util";
|
||||
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
|
||||
import { ContinueServerClient } from "./continueServer/stubs/client";
|
||||
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
||||
import { ControlPlaneClient } from "./control-plane/client";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer.js";
|
||||
import { DocsService } from "./indexing/docs/DocsService.js";
|
||||
import Ollama from "./llm/llms/Ollama.js";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
|
||||
import DocsCrawler from "./indexing/docs/DocsCrawler";
|
||||
import DocsService from "./indexing/docs/DocsService";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { GlobalContext } from "./util/GlobalContext.js";
|
||||
import { logDevData } from "./util/devdata.js";
|
||||
import { DevDataSqliteDb } from "./util/devdataSqlite.js";
|
||||
import { fetchwithRequestOptions } from "./util/fetchWithOptions.js";
|
||||
import historyManager from "./util/history.js";
|
||||
import { GlobalContext } from "./util/GlobalContext";
|
||||
import { logDevData } from "./util/devdata";
|
||||
import { DevDataSqliteDb } from "./util/devdataSqlite";
|
||||
import { fetchwithRequestOptions } from "./util/fetchWithOptions";
|
||||
import historyManager from "./util/history";
|
||||
import type { IMessenger, Message } from "./util/messenger";
|
||||
import { editConfigJson } from "./util/paths.js";
|
||||
import { Telemetry } from "./util/posthog.js";
|
||||
import { streamDiffLines } from "./util/verticalEdit.js";
|
||||
import { editConfigJson } from "./util/paths";
|
||||
import { Telemetry } from "./util/posthog";
|
||||
import { TTS } from "./util/tts";
|
||||
import { streamDiffLines } from "./util/verticalEdit";
|
||||
|
||||
export class Core {
|
||||
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
|
||||
|
|
@ -42,8 +38,9 @@ export class Core {
|
|||
continueServerClientPromise: Promise<ContinueServerClient>;
|
||||
indexingState: IndexingProgressUpdate;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
private docsService: DocsService;
|
||||
private globalContext = new GlobalContext();
|
||||
private docsService = DocsService.getInstance();
|
||||
|
||||
private readonly indexingPauseToken = new PauseToken(
|
||||
this.globalContext.get("indexingPaused") === true,
|
||||
);
|
||||
|
|
@ -98,20 +95,16 @@ export class Core {
|
|||
this.controlPlaneClient,
|
||||
);
|
||||
|
||||
this.docsService = DocsService.createSingleton(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.messenger,
|
||||
);
|
||||
|
||||
this.configHandler.onConfigUpdate(
|
||||
(() => this.messenger.send("configUpdate", undefined)).bind(this),
|
||||
);
|
||||
|
||||
this.configHandler.onConfigUpdate(async ({ embeddingsProvider }) => {
|
||||
if (
|
||||
await this.shouldReindexDocsOnNewEmbeddingsProvider(
|
||||
embeddingsProvider.id,
|
||||
)
|
||||
) {
|
||||
await this.reindexDocsOnNewEmbeddingsProvider(embeddingsProvider);
|
||||
}
|
||||
});
|
||||
|
||||
this.configHandler.onDidChangeAvailableProfiles((profiles) =>
|
||||
this.messenger.send("didChangeAvailableProfiles", { profiles }),
|
||||
);
|
||||
|
|
@ -176,10 +169,20 @@ 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 });
|
||||
});
|
||||
|
||||
|
|
@ -209,12 +212,15 @@ export class Core {
|
|||
on("history/list", (msg) => {
|
||||
return historyManager.list(msg.data);
|
||||
});
|
||||
|
||||
on("history/delete", (msg) => {
|
||||
historyManager.delete(msg.data.id);
|
||||
});
|
||||
|
||||
on("history/load", (msg) => {
|
||||
return historyManager.load(msg.data.id);
|
||||
});
|
||||
|
||||
on("history/save", (msg) => {
|
||||
historyManager.save(msg.data);
|
||||
});
|
||||
|
|
@ -230,14 +236,17 @@ export class Core {
|
|||
addModel(model);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/addOpenAiKey", (msg) => {
|
||||
addOpenAIKey(msg.data);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/deleteModel", (msg) => {
|
||||
deleteModel(msg.data.title);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/newPromptFile", async (msg) => {
|
||||
createNewPromptFile(
|
||||
this.ide,
|
||||
|
|
@ -245,10 +254,12 @@ export class Core {
|
|||
);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/reload", (msg) => {
|
||||
this.configHandler.reloadConfig();
|
||||
return this.configHandler.getSerializedConfig();
|
||||
});
|
||||
|
||||
on("config/ideSettingsUpdate", (msg) => {
|
||||
this.configHandler.updateIdeSettings(msg.data);
|
||||
});
|
||||
|
|
@ -258,43 +269,36 @@ export class Core {
|
|||
|
||||
// Context providers
|
||||
on("context/addDocs", async (msg) => {
|
||||
await this.getEmbeddingsProviderAndIndexDoc(msg.data);
|
||||
let hasFailed = false;
|
||||
|
||||
this.ide.infoPopup(`Successfully indexed ${msg.data.title}`);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
for await (const result of this.docsService.indexAndAdd(msg.data)) {
|
||||
if (result.status === "failed") {
|
||||
hasFailed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasFailed) {
|
||||
this.ide.infoPopup(`Failed to index ${msg.data.startUrl}`);
|
||||
} else {
|
||||
this.ide.infoPopup(`Successfully indexed ${msg.data.startUrl}`);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
}
|
||||
});
|
||||
|
||||
on("context/removeDocs", async (msg) => {
|
||||
const baseUrl = msg.data.baseUrl;
|
||||
await this.docsService.delete(baseUrl);
|
||||
await this.docsService.delete(msg.data.startUrl);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
});
|
||||
|
||||
on("context/indexDocs", async (msg) => {
|
||||
const config = await this.config();
|
||||
const provider: any = config.contextProviders?.find(
|
||||
(provider) => provider.description.title === "docs",
|
||||
);
|
||||
|
||||
if (!provider) {
|
||||
this.ide.infoPopup("No docs in configuration");
|
||||
return;
|
||||
}
|
||||
|
||||
const siteIndexingOptions: SiteIndexingConfig[] = ((mProvider) => [
|
||||
...new Set([
|
||||
...(mProvider?.options?.sites || []),
|
||||
...(config.docs || []),
|
||||
]),
|
||||
])({ ...provider });
|
||||
|
||||
for (const site of siteIndexingOptions) {
|
||||
await this.getEmbeddingsProviderAndIndexDoc(site, msg.data.reIndex);
|
||||
}
|
||||
|
||||
this.ide.infoPopup("Docs indexing completed");
|
||||
await this.docsService.indexAllDocs(msg.data.reIndex);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
});
|
||||
|
||||
on("context/loadSubmenuItems", async (msg) => {
|
||||
const config = await this.config();
|
||||
const items = config.contextProviders
|
||||
const items = await config.contextProviders
|
||||
?.find((provider) => provider.description.title === msg.data.title)
|
||||
?.loadSubmenuItems({
|
||||
config,
|
||||
|
|
@ -304,6 +308,7 @@ export class Core {
|
|||
});
|
||||
return items || [];
|
||||
});
|
||||
|
||||
on("context/getContextItems", async (msg) => {
|
||||
const { name, query, fullInput, selectedCode } = msg.data;
|
||||
const config = await this.config();
|
||||
|
|
@ -320,7 +325,9 @@ export class Core {
|
|||
providerTitle: provider.description.title,
|
||||
itemId: uuidv4(),
|
||||
};
|
||||
|
||||
const items = await provider.getContextItems(query, {
|
||||
config,
|
||||
llm,
|
||||
embeddingsProvider: config.embeddingsProvider,
|
||||
fullInput,
|
||||
|
|
@ -361,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,
|
||||
|
|
@ -371,6 +385,7 @@ export class Core {
|
|||
if (abortedMessageIds.has(msg.messageId)) {
|
||||
abortedMessageIds.delete(msg.messageId);
|
||||
next = await gen.return({
|
||||
modelTitle: model.title ?? model.model,
|
||||
completion: "",
|
||||
prompt: "",
|
||||
completionOptions: {
|
||||
|
|
@ -384,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 };
|
||||
}
|
||||
|
||||
|
|
@ -407,6 +426,7 @@ export class Core {
|
|||
if (abortedMessageIds.has(msg.messageId)) {
|
||||
abortedMessageIds.delete(msg.messageId);
|
||||
next = await gen.return({
|
||||
modelTitle: model.title ?? model.model,
|
||||
completion: "",
|
||||
prompt: "",
|
||||
completionOptions: {
|
||||
|
|
@ -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) => {
|
||||
|
|
@ -656,6 +688,7 @@ export class Core {
|
|||
|
||||
on("didChangeSelectedProfile", (msg) => {
|
||||
this.configHandler.setSelectedProfile(msg.data.id);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
on("didChangeControlPlaneSessionInfo", async (msg) => {
|
||||
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
|
||||
|
|
@ -683,104 +716,19 @@ export class Core {
|
|||
)) {
|
||||
this.messenger.request("indexProgress", update);
|
||||
this.indexingState = update;
|
||||
|
||||
if (update.status === "failed") {
|
||||
Telemetry.capture(
|
||||
"indexing_error",
|
||||
{
|
||||
error: update.desc,
|
||||
stack: update.debugInfo,
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
}
|
||||
|
||||
private async shouldReindexDocsOnNewEmbeddingsProvider(
|
||||
curEmbeddingsProviderId: EmbeddingsProvider["id"],
|
||||
): Promise<boolean> {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
const isJetBrainsAndPreIndexedDocsProvider =
|
||||
this.docsService.isJetBrainsAndPreIndexedDocsProvider(
|
||||
ideInfo,
|
||||
curEmbeddingsProviderId,
|
||||
);
|
||||
|
||||
if (isJetBrainsAndPreIndexedDocsProvider) {
|
||||
try {
|
||||
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",
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to show error popup:", error);
|
||||
}
|
||||
this.globalContext.update(
|
||||
"curEmbeddingsProviderId",
|
||||
curEmbeddingsProviderId,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const lastEmbeddingsProviderId = this.globalContext.get(
|
||||
"curEmbeddingsProviderId",
|
||||
);
|
||||
|
||||
if (!lastEmbeddingsProviderId) {
|
||||
// If it's the first time we're setting the `curEmbeddingsProviderId`
|
||||
// global state, we don't need to reindex docs
|
||||
this.globalContext.update(
|
||||
"curEmbeddingsProviderId",
|
||||
curEmbeddingsProviderId,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return lastEmbeddingsProviderId !== curEmbeddingsProviderId;
|
||||
}
|
||||
|
||||
private async getEmbeddingsProviderAndIndexDoc(
|
||||
site: SiteIndexingConfig,
|
||||
reIndex: boolean = false,
|
||||
): Promise<void> {
|
||||
const config = await this.config();
|
||||
const { embeddingsProvider } = config;
|
||||
|
||||
for await (const update of this.docsService.indexAndAdd(
|
||||
site,
|
||||
embeddingsProvider,
|
||||
reIndex,
|
||||
)) {
|
||||
// Temporary disabled posting progress updates to the UI due to
|
||||
// possible collision with code indexing progress updates.
|
||||
// this.messenger.request("indexProgress", update);
|
||||
// this.indexingState = update;
|
||||
}
|
||||
}
|
||||
|
||||
private async reindexDocsOnNewEmbeddingsProvider(
|
||||
embeddingsProvider: EmbeddingsProvider,
|
||||
) {
|
||||
const docs = await this.docsService.list();
|
||||
|
||||
if (docs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.ide.infoPopup("Reindexing docs with new embeddings provider");
|
||||
|
||||
for (const { title, baseUrl } of docs) {
|
||||
await this.docsService.delete(baseUrl);
|
||||
|
||||
const generator = this.docsService.indexAndAdd(
|
||||
{ title, startUrl: baseUrl, rootUrl: baseUrl },
|
||||
embeddingsProvider,
|
||||
);
|
||||
|
||||
while (!(await generator.next()).done) {}
|
||||
}
|
||||
|
||||
// Important that this only is invoked after we have successfully
|
||||
// cleared and reindex the docs so that the table cannot end up in an
|
||||
// invalid state.
|
||||
this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id);
|
||||
|
||||
this.ide.infoPopup("Completed reindexing of all docs");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
67
core/index.d.ts
vendored
67
core/index.d.ts
vendored
|
|
@ -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>;
|
||||
|
|
@ -127,6 +130,7 @@ export interface ContextProviderDescription {
|
|||
export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
|
||||
|
||||
export interface ContextProviderExtras {
|
||||
config: ContinueConfig;
|
||||
fullInput: string;
|
||||
embeddingsProvider: EmbeddingsProvider;
|
||||
reranker: Reranker | undefined;
|
||||
|
|
@ -161,21 +165,21 @@ export interface ContextSubmenuItem {
|
|||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
iconUrl?: string;
|
||||
icon?: string;
|
||||
metadata?: any;
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
startUrl: string;
|
||||
rootUrl: string;
|
||||
title: string;
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
startUrl: string;
|
||||
rootUrl: string;
|
||||
rootUrl?: string;
|
||||
title: string;
|
||||
maxDepth?: number;
|
||||
}
|
||||
|
|
@ -269,6 +273,7 @@ export interface ContextItem {
|
|||
description: string;
|
||||
editing?: boolean;
|
||||
editable?: boolean;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export interface ContextItemWithId {
|
||||
|
|
@ -278,6 +283,7 @@ export interface ContextItemWithId {
|
|||
id: ContextItemId;
|
||||
editing?: boolean;
|
||||
editable?: boolean;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export interface InputModifiers {
|
||||
|
|
@ -286,6 +292,7 @@ export interface InputModifiers {
|
|||
}
|
||||
|
||||
export interface PromptLog {
|
||||
modelTitle: string;
|
||||
completionOptions: CompletionOptions;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
|
|
@ -315,6 +322,7 @@ export interface LLMOptions {
|
|||
uniqueId?: string;
|
||||
systemMessage?: string;
|
||||
contextLength?: number;
|
||||
maxStopWords?: number;
|
||||
completionOptions?: CompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
template?: TemplateType;
|
||||
|
|
@ -336,9 +344,25 @@ 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;
|
||||
|
||||
// IBM watsonx options
|
||||
watsonxUrl?: string;
|
||||
watsonxCreds?: string;
|
||||
watsonxProjectId?: string;
|
||||
watsonxStopToken?: string;
|
||||
watsonxApiVersion?: string;
|
||||
|
||||
cacheSystemMessage?: boolean;
|
||||
}
|
||||
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
|
||||
T,
|
||||
|
|
@ -572,6 +596,7 @@ type ModelProvider =
|
|||
| "ollama"
|
||||
| "huggingface-tgi"
|
||||
| "huggingface-inference-api"
|
||||
| "kindo"
|
||||
| "llama.cpp"
|
||||
| "replicate"
|
||||
| "text-gen-webui"
|
||||
|
|
@ -580,6 +605,8 @@ type ModelProvider =
|
|||
| "gemini"
|
||||
| "mistral"
|
||||
| "bedrock"
|
||||
| "bedrockimport"
|
||||
| "sagemaker"
|
||||
| "deepinfra"
|
||||
| "flowise"
|
||||
| "groq"
|
||||
|
|
@ -590,7 +617,9 @@ type ModelProvider =
|
|||
| "deepseek"
|
||||
| "azure"
|
||||
| "openai-aiohttp"
|
||||
| "msty";
|
||||
| "msty"
|
||||
| "watsonx"
|
||||
| "openrouter";
|
||||
|
||||
export type ModelName =
|
||||
| "AUTODETECT"
|
||||
|
|
@ -718,6 +747,10 @@ interface BaseCompletionOptions {
|
|||
stream?: boolean;
|
||||
}
|
||||
|
||||
export interface ModelCapability {
|
||||
uploadImage?: boolean;
|
||||
}
|
||||
|
||||
export interface ModelDescription {
|
||||
title: string;
|
||||
provider: ModelProvider;
|
||||
|
|
@ -725,11 +758,13 @@ export interface ModelDescription {
|
|||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
contextLength?: number;
|
||||
maxStopWords?: number;
|
||||
template?: TemplateType;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
systemMessage?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: { [key: string]: string };
|
||||
capabilities?: ModelCapability;
|
||||
}
|
||||
|
||||
export type EmbeddingsProviderName =
|
||||
|
|
@ -739,7 +774,9 @@ export type EmbeddingsProviderName =
|
|||
| "openai"
|
||||
| "cohere"
|
||||
| "free-trial"
|
||||
| "gemini";
|
||||
| "gemini"
|
||||
| "continue-proxy"
|
||||
| "deepinfra";
|
||||
|
||||
export interface EmbedOptions {
|
||||
apiBase?: string;
|
||||
|
|
@ -758,6 +795,7 @@ export interface EmbeddingsProviderDescription extends EmbedOptions {
|
|||
|
||||
export interface EmbeddingsProvider {
|
||||
id: string;
|
||||
providerName: EmbeddingsProviderName;
|
||||
maxChunkSize: number;
|
||||
embed(chunks: string[]): Promise<number[][]>;
|
||||
}
|
||||
|
|
@ -767,7 +805,8 @@ export type RerankerName =
|
|||
| "voyage"
|
||||
| "llm"
|
||||
| "free-trial"
|
||||
| "huggingface-tei";
|
||||
| "huggingface-tei"
|
||||
| "continue-proxy";
|
||||
|
||||
export interface RerankerDescription {
|
||||
name: RerankerName;
|
||||
|
|
@ -846,10 +885,14 @@ interface QuickActionConfig {
|
|||
sendToChat: boolean;
|
||||
}
|
||||
|
||||
export type DefaultContextProvider = ContextProviderWithParams & {
|
||||
query?: string;
|
||||
};
|
||||
|
||||
interface ExperimentalConfig {
|
||||
contextMenuPrompts?: ContextMenuConfig;
|
||||
modelRoles?: ModelRoles;
|
||||
defaultContext?: "activeFile"[];
|
||||
defaultContext?: DefaultContextProvider[];
|
||||
promptPath?: string;
|
||||
|
||||
/**
|
||||
|
|
@ -857,6 +900,11 @@ interface ExperimentalConfig {
|
|||
* function and class declarations.
|
||||
*/
|
||||
quickActions?: QuickActionConfig[];
|
||||
|
||||
/**
|
||||
* Automatically read LLM chat responses aloud using system TTS models
|
||||
*/
|
||||
readResponseTTS?: boolean;
|
||||
}
|
||||
|
||||
interface AnalyticsConfig {
|
||||
|
|
@ -886,6 +934,7 @@ export interface SerializedContinueConfig {
|
|||
reranker?: RerankerDescription;
|
||||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
}
|
||||
|
||||
export type ConfigMergeType = "merge" | "overwrite";
|
||||
|
|
|
|||
83
core/indexing/CodeSnippetsIndex.test.ts
Normal file
83
core/indexing/CodeSnippetsIndex.test.ts
Normal 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,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -7,6 +7,7 @@ import type {
|
|||
IndexingProgressUpdate,
|
||||
} from "../index.js";
|
||||
import { getBasename, getLastNPathParts } from "../util/index.js";
|
||||
import { migrate } from "../util/paths.js";
|
||||
import {
|
||||
TSQueryType,
|
||||
getParserForFile,
|
||||
|
|
@ -43,6 +44,55 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
snippetId INTEGER NOT NULL,
|
||||
FOREIGN KEY (snippetId) REFERENCES code_snippets (id)
|
||||
)`);
|
||||
|
||||
migrate("delete_duplicate_code_snippets", async () => {
|
||||
// Delete duplicate entries in code_snippets
|
||||
await db.exec(`
|
||||
DELETE FROM code_snippets
|
||||
WHERE id NOT IN (
|
||||
SELECT MIN(id)
|
||||
FROM code_snippets
|
||||
GROUP BY path, cacheKey, content, title, startLine, endLine
|
||||
)
|
||||
`);
|
||||
|
||||
// Add unique constraint if it doesn't exist
|
||||
await db.exec(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_code_snippets_unique
|
||||
ON code_snippets (path, cacheKey, content, title, startLine, endLine)
|
||||
`);
|
||||
|
||||
// Delete code_snippets associated with duplicate code_snippets_tags entries
|
||||
await db.exec(`
|
||||
DELETE FROM code_snippets
|
||||
WHERE id IN (
|
||||
SELECT snippetId
|
||||
FROM code_snippets_tags
|
||||
WHERE (snippetId, tag) IN (
|
||||
SELECT snippetId, tag
|
||||
FROM code_snippets_tags
|
||||
GROUP BY snippetId, tag
|
||||
HAVING COUNT(*) > 1
|
||||
)
|
||||
)
|
||||
`);
|
||||
|
||||
// Delete duplicate entries
|
||||
await db.exec(`
|
||||
DELETE FROM code_snippets_tags
|
||||
WHERE id NOT IN (
|
||||
SELECT MIN(id)
|
||||
FROM code_snippets_tags
|
||||
GROUP BY snippetId, tag
|
||||
)
|
||||
`);
|
||||
|
||||
// Add unique constraint if it doesn't exist
|
||||
await db.exec(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_snippetId_tag
|
||||
ON code_snippets_tags (snippetId, tag)
|
||||
`);
|
||||
});
|
||||
}
|
||||
|
||||
async getSnippetsInFile(
|
||||
|
|
@ -50,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(
|
||||
|
|
@ -82,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];
|
||||
|
||||
|
|
@ -93,12 +148,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
);
|
||||
} catch (e) {
|
||||
// If can't parse, assume malformatted code
|
||||
console.error(`Error parsing ${compute.path}:`, e);
|
||||
}
|
||||
|
||||
// Add snippets to sqlite
|
||||
for (const snippet of snippets) {
|
||||
const { lastID } = await db.run(
|
||||
"INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
"REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
[
|
||||
compute.path,
|
||||
compute.cacheKey,
|
||||
|
|
@ -110,7 +166,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
);
|
||||
|
||||
await db.run(
|
||||
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
|
||||
"REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
|
||||
[lastID, tagString],
|
||||
);
|
||||
}
|
||||
|
|
@ -123,47 +179,93 @@ 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 snippetsWithPath = await db.all(
|
||||
"SELECT * FROM code_snippets WHERE cacheKey = ?",
|
||||
[results.addTag[i].cacheKey],
|
||||
);
|
||||
const addTag = results.addTag[i];
|
||||
let snippets: (ChunkWithoutID & { title: string })[] = [];
|
||||
try {
|
||||
snippets = await this.getSnippetsInFile(
|
||||
addTag.path,
|
||||
await this.ide.readFile(addTag.path),
|
||||
);
|
||||
} catch (e) {
|
||||
// If can't parse, assume malformatted code
|
||||
console.error(`Error parsing ${addTag.path}:`, e);
|
||||
}
|
||||
|
||||
for (const snippet of snippetsWithPath) {
|
||||
for (const snippet of snippets) {
|
||||
const { lastID } = await db.run(
|
||||
"REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
[
|
||||
addTag.path,
|
||||
addTag.cacheKey,
|
||||
snippet.content,
|
||||
snippet.title,
|
||||
snippet.startLine,
|
||||
snippet.endLine,
|
||||
],
|
||||
);
|
||||
await db.run(
|
||||
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
|
||||
[snippet.id, tagString],
|
||||
"REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
|
||||
[lastID, tagString],
|
||||
);
|
||||
}
|
||||
|
||||
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 (!Array.isArray(snippets)) {
|
||||
snippets = [snippets];
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
212
core/indexing/CodebaseIndexer.test.ts
Normal file
212
core/indexing/CodebaseIndexer.test.ts
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
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 { testConfigHandler, testIde } from "../test/util/fixtures.js";
|
||||
import {
|
||||
addToTestDir,
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
TEST_DIR,
|
||||
} 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();
|
||||
|
||||
const TEST_TS = `\
|
||||
function main() {
|
||||
console.log("Hello, world!");
|
||||
}
|
||||
|
||||
class Foo {
|
||||
constructor(public bar: string) {}
|
||||
}
|
||||
`;
|
||||
|
||||
const TEST_PY = `\
|
||||
def main():
|
||||
print("Hello, world!")
|
||||
|
||||
class Foo:
|
||||
def __init__(self, bar: str):
|
||||
self.bar = bar
|
||||
`;
|
||||
|
||||
const TEST_RS = `\
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
|
||||
struct Foo {
|
||||
bar: String,
|
||||
}
|
||||
`;
|
||||
|
||||
// A subclass of CodebaseIndexer that adds a new CodebaseIndex
|
||||
class TestCodebaseIndexer extends CodebaseIndexer {
|
||||
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
|
||||
return [new TestCodebaseIndex()];
|
||||
}
|
||||
}
|
||||
|
||||
// These are more like integration tests, whereas we should separately test
|
||||
// the individual CodebaseIndex classes
|
||||
describe("CodebaseIndexer", () => {
|
||||
const pauseToken = new PauseToken(false);
|
||||
const continueServerClient = new ContinueServerClient(undefined, undefined);
|
||||
const codebaseIndexer = new TestCodebaseIndexer(
|
||||
testConfigHandler,
|
||||
testIde,
|
||||
pauseToken,
|
||||
continueServerClient,
|
||||
);
|
||||
const testIndex = new TestCodebaseIndex();
|
||||
|
||||
beforeAll(async () => {
|
||||
tearDownTestDir();
|
||||
setUpTestDir();
|
||||
|
||||
execSync('git config --global user.email "test@example.com"');
|
||||
execSync('git config --global user.name "Test"');
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
async function refreshIndex() {
|
||||
const abortController = new AbortController();
|
||||
const abortSignal = abortController.signal;
|
||||
|
||||
const updates = [];
|
||||
for await (const update of codebaseIndexer.refresh(
|
||||
[TEST_DIR],
|
||||
abortSignal,
|
||||
)) {
|
||||
updates.push(update);
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
|
||||
async function getAllIndexedFiles() {
|
||||
const files = await testIndex.getIndexedFilesForTags(
|
||||
await testIde.getTags(testIndex.artifactId),
|
||||
);
|
||||
return files;
|
||||
}
|
||||
|
||||
async function getIndexPlan() {
|
||||
const workspaceFiles = await walkDir(TEST_DIR, testIde);
|
||||
const [tag] = await testIde.getTags(testIndex.artifactId);
|
||||
const stats = await testIde.getLastModified(workspaceFiles);
|
||||
|
||||
const [results, lastUpdated, markComplete] =
|
||||
await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
{ ...stats },
|
||||
(filepath) => testIde.readFile(filepath),
|
||||
undefined,
|
||||
);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function expectPlan(
|
||||
compute: number,
|
||||
addTag: number,
|
||||
removeTag: number,
|
||||
del: number,
|
||||
) {
|
||||
const plan = await getIndexPlan();
|
||||
console.log("PLAN: ", plan);
|
||||
expect(plan.compute).toHaveLength(compute);
|
||||
expect(plan.addTag).toHaveLength(addTag);
|
||||
expect(plan.removeTag).toHaveLength(removeTag);
|
||||
expect(plan.del).toHaveLength(del);
|
||||
return plan;
|
||||
}
|
||||
|
||||
test("should index test folder without problem", async () => {
|
||||
addToTestDir([
|
||||
["test.ts", TEST_TS],
|
||||
["py/main.py", TEST_PY],
|
||||
]);
|
||||
|
||||
await expectPlan(2, 0, 0, 0);
|
||||
|
||||
const updates = await refreshIndex();
|
||||
expect(updates.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("should have created index folder with all necessary files", async () => {
|
||||
expect(fs.existsSync(getIndexSqlitePath())).toBe(true);
|
||||
});
|
||||
|
||||
test("should have indexed all of the files", async () => {
|
||||
const indexed = await getAllIndexedFiles();
|
||||
expect(indexed.length).toBe(2);
|
||||
expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
|
||||
expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
|
||||
});
|
||||
|
||||
test("should successfully re-index after adding a file", async () => {
|
||||
addToTestDir([["main.rs", TEST_RS]]);
|
||||
|
||||
await expectPlan(1, 0, 0, 0);
|
||||
|
||||
const updates = await refreshIndex();
|
||||
expect(updates.length).toBeGreaterThan(0);
|
||||
|
||||
// Check that the new file was indexed
|
||||
const files = await getAllIndexedFiles();
|
||||
expect(files.length).toBe(3);
|
||||
expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
|
||||
});
|
||||
|
||||
test("should successfully re-index after deleting a file", async () => {
|
||||
fs.rmSync(path.join(TEST_DIR, "main.rs"));
|
||||
|
||||
await expectPlan(0, 0, 0, 1);
|
||||
|
||||
const updates = await refreshIndex();
|
||||
expect(updates.length).toBeGreaterThan(0);
|
||||
|
||||
// Check that the deleted file was removed from the index
|
||||
const files = await getAllIndexedFiles();
|
||||
expect(files.length).toBe(2);
|
||||
expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
|
||||
});
|
||||
|
||||
test("shouldn't index any files when nothing changed", async () => {
|
||||
await expectPlan(0, 0, 0, 0);
|
||||
const updates = await refreshIndex();
|
||||
expect(updates.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("should create git repo for testing", async () => {
|
||||
execSync(
|
||||
`cd ${TEST_DIR} && git init && git checkout -b main && git add -A && git commit -m "First commit"`,
|
||||
);
|
||||
});
|
||||
|
||||
test.skip("should only re-index the changed files when changing branches", async () => {
|
||||
execSync(`cd ${TEST_DIR} && git checkout -b test2`);
|
||||
// Rewriting the file
|
||||
addToTestDir([["test.ts", "// This is different"]]);
|
||||
|
||||
// Should re-compute test.ts, but just re-tag the .py file
|
||||
await expectPlan(1, 1, 0, 0);
|
||||
|
||||
execSync(`cd ${TEST_DIR} && git add -A && git commit -m "Change .ts file"`);
|
||||
});
|
||||
|
||||
test.skip("shouldn't re-index anything when changing back to original branch", async () => {
|
||||
execSync(`cd ${TEST_DIR} && git checkout main`);
|
||||
await expectPlan(0, 0, 0, 0);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,13 +1,20 @@
|
|||
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 { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
|
||||
import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js";
|
||||
import { LanceDbIndex } from "./LanceDbIndex.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 "./FullTextSearchCodebaseIndex.js";
|
||||
import { LanceDbIndex } from "./LanceDbIndex.js";
|
||||
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
|
||||
import { CodebaseIndex, IndexResultType } from "./types.js";
|
||||
import { walkDir } from "./walkDir.js";
|
||||
import {
|
||||
CodebaseIndex,
|
||||
IndexResultType,
|
||||
RefreshIndexResults,
|
||||
} from "./types.js";
|
||||
import { walkDirAsync } from "./walkDir.js";
|
||||
|
||||
export class PauseToken {
|
||||
constructor(private _paused: boolean) {}
|
||||
|
|
@ -22,25 +29,63 @@ 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 = 500;
|
||||
|
||||
// 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,
|
||||
private readonly ide: IDE,
|
||||
protected readonly ide: IDE,
|
||||
private readonly pauseToken: PauseToken,
|
||||
private readonly continueServerClient: IContinueServerClient,
|
||||
) {}
|
||||
|
||||
private async getIndexesToBuild(): Promise<CodebaseIndex[]> {
|
||||
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();
|
||||
|
||||
const indexes = [
|
||||
new ChunkCodebaseIndex(
|
||||
this.ide.readFile.bind(this.ide),
|
||||
pathSep,
|
||||
this.continueServerClient,
|
||||
config.embeddingsProvider.maxChunkSize,
|
||||
), // Chunking must come first
|
||||
new LanceDbIndex(
|
||||
config.embeddingsProvider,
|
||||
this.ide.readFile.bind(this.ide),
|
||||
pathSep,
|
||||
this.continueServerClient,
|
||||
),
|
||||
new FullTextSearchCodebaseIndex(),
|
||||
|
|
@ -50,6 +95,53 @@ export class CodebaseIndexer {
|
|||
return indexes;
|
||||
}
|
||||
|
||||
public async refreshFile(file: string): Promise<void> {
|
||||
if (this.pauseToken.paused) {
|
||||
// NOTE: by returning here, there is a chance that while paused a file is modified and
|
||||
// then after unpausing the file is not reindexed
|
||||
return;
|
||||
}
|
||||
const workspaceDir = await this.getWorkspaceDir(file);
|
||||
if (!workspaceDir) {
|
||||
return;
|
||||
}
|
||||
const branch = await this.ide.getBranch(workspaceDir);
|
||||
const repoName = await this.ide.getRepoName(workspaceDir);
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
const stats = await this.ide.getLastModified([file]);
|
||||
for (const index of indexesToBuild) {
|
||||
const tag = {
|
||||
directory: workspaceDir,
|
||||
branch,
|
||||
artifactId: index.artifactId,
|
||||
};
|
||||
const [results, lastUpdated, markComplete] =
|
||||
await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
{ ...stats },
|
||||
(filepath) => this.ide.readFile(filepath),
|
||||
repoName,
|
||||
);
|
||||
// since this is only a single file update / save we do not want to actualy remove anything, we just want to recompute for our single file
|
||||
results.removeTag = [];
|
||||
results.addTag = [];
|
||||
results.del = [];
|
||||
|
||||
// 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,
|
||||
markComplete,
|
||||
repoName,
|
||||
)) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async *refresh(
|
||||
workspaceDirs: string[],
|
||||
abortSignal: AbortSignal,
|
||||
|
|
@ -81,12 +173,7 @@ export class CodebaseIndexer {
|
|||
};
|
||||
}
|
||||
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
let completedDirs = 0;
|
||||
const totalRelativeExpectedTime = indexesToBuild.reduce(
|
||||
(sum, index) => sum + index.relativeExpectedTime,
|
||||
0,
|
||||
);
|
||||
|
||||
// Wait until Git Extension has loaded to report progress
|
||||
// so we don't appear stuck at 0% while waiting
|
||||
|
|
@ -97,113 +184,244 @@ export class CodebaseIndexer {
|
|||
desc: "Starting indexing...",
|
||||
status: "loading",
|
||||
};
|
||||
const beginTime = Date.now();
|
||||
|
||||
for (const directory of workspaceDirs) {
|
||||
const files = await walkDir(directory, this.ide);
|
||||
const stats = await this.ide.getLastModified(files);
|
||||
const dirBasename = await this.basename(directory);
|
||||
yield {
|
||||
progress,
|
||||
desc: `Discovering files in ${dirBasename}...`,
|
||||
status: "indexing",
|
||||
};
|
||||
const workspaceFiles = [];
|
||||
for await (const p of walkDirAsync(directory, this.ide)) {
|
||||
workspaceFiles.push(p);
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: "Indexing cancelled",
|
||||
status: "disabled",
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (this.pauseToken.paused) {
|
||||
yield* this.yieldUpdateAndPause();
|
||||
}
|
||||
}
|
||||
|
||||
const branch = await this.ide.getBranch(directory);
|
||||
const repoName = await this.ide.getRepoName(directory);
|
||||
let completedRelativeExpectedTime = 0;
|
||||
let nextLogThreshold = 0;
|
||||
|
||||
for (const codebaseIndex of indexesToBuild) {
|
||||
// TODO: IndexTag type should use repoName rather than directory
|
||||
const tag: IndexTag = {
|
||||
try {
|
||||
for await (const updateDesc of this.indexFiles(
|
||||
directory,
|
||||
workspaceFiles,
|
||||
branch,
|
||||
artifactId: codebaseIndex.artifactId,
|
||||
};
|
||||
const [results, lastUpdated, markComplete] = await getComputeDeleteAddRemove(
|
||||
repoName,
|
||||
)) {
|
||||
// Handle pausing in this loop because it's the only one really taking time
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: "Indexing cancelled",
|
||||
status: "disabled",
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (this.pauseToken.paused) {
|
||||
yield* this.yieldUpdateAndPause();
|
||||
}
|
||||
yield updateDesc;
|
||||
if (updateDesc.progress >= nextLogThreshold) {
|
||||
// log progress every 2.5%
|
||||
nextLogThreshold += 0.025;
|
||||
this.logProgress(
|
||||
beginTime,
|
||||
Math.floor(workspaceFiles.length * updateDesc.progress),
|
||||
updateDesc.progress,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
yield this.handleErrorAndGetProgressUpdate(err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
yield {
|
||||
progress: 100,
|
||||
desc: "Indexing Complete",
|
||||
status: "done",
|
||||
};
|
||||
}
|
||||
|
||||
private handleErrorAndGetProgressUpdate(
|
||||
err: unknown,
|
||||
): IndexingProgressUpdate {
|
||||
console.log("error when indexing: ", err);
|
||||
if (err instanceof Error) {
|
||||
return this.errorToProgressUpdate(err);
|
||||
}
|
||||
return {
|
||||
progress: 0,
|
||||
desc: `Indexing failed: ${err}`,
|
||||
status: "failed",
|
||||
debugInfo: extractMinimalStackTraceInfo((err as any)?.stack),
|
||||
};
|
||||
}
|
||||
|
||||
private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
private logProgress(
|
||||
beginTime: number,
|
||||
completedFileCount: number,
|
||||
progress: number,
|
||||
) {
|
||||
const timeTaken = Date.now() - beginTime;
|
||||
const seconds = Math.round(timeTaken / 1000);
|
||||
const progressPercentage = (progress * 100).toFixed(1);
|
||||
const filesPerSec = (completedFileCount / seconds).toFixed(2);
|
||||
console.debug(
|
||||
`Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
|
||||
);
|
||||
}
|
||||
|
||||
private async *yieldUpdateAndPause(): AsyncGenerator<IndexingProgressUpdate> {
|
||||
yield {
|
||||
progress: 0,
|
||||
desc: "Indexing Paused",
|
||||
status: "paused",
|
||||
};
|
||||
while (this.pauseToken.paused) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 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,
|
||||
): Generator<RefreshIndexResults> {
|
||||
let curPos = 0;
|
||||
while (
|
||||
curPos < results.compute.length ||
|
||||
curPos < results.del.length ||
|
||||
curPos < results.addTag.length ||
|
||||
curPos < results.removeTag.length
|
||||
) {
|
||||
yield {
|
||||
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 += this.filesPerBatch;
|
||||
}
|
||||
}
|
||||
|
||||
private async *indexFiles(
|
||||
workspaceDir: string,
|
||||
workspaceFiles: string[],
|
||||
branch: string,
|
||||
repoName: string | undefined,
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const stats = await this.ide.getLastModified(workspaceFiles);
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
let completedIndexCount = 0;
|
||||
let progress = 0;
|
||||
for (const codebaseIndex of indexesToBuild) {
|
||||
const tag: IndexTag = {
|
||||
directory: workspaceDir,
|
||||
branch,
|
||||
artifactId: codebaseIndex.artifactId,
|
||||
};
|
||||
yield {
|
||||
progress: progress,
|
||||
desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
|
||||
status: "indexing",
|
||||
};
|
||||
const [results, lastUpdated, markComplete] =
|
||||
await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
{ ...stats },
|
||||
(filepath) => this.ide.readFile(filepath),
|
||||
repoName,
|
||||
);
|
||||
const totalOps =
|
||||
results.compute.length +
|
||||
results.del.length +
|
||||
results.addTag.length +
|
||||
results.removeTag.length;
|
||||
let completedOps = 0;
|
||||
|
||||
try {
|
||||
for await (let {
|
||||
progress: indexProgress,
|
||||
desc,
|
||||
} of codebaseIndex.update(tag, results, markComplete, repoName)) {
|
||||
// Handle pausing in this loop because it's the only one really taking time
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: "Indexing cancelled",
|
||||
status: "disabled",
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.pauseToken.paused) {
|
||||
yield {
|
||||
progress,
|
||||
desc: "Paused",
|
||||
status: "paused",
|
||||
};
|
||||
while (this.pauseToken.paused) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
progress =
|
||||
(completedDirs +
|
||||
(completedRelativeExpectedTime +
|
||||
Math.min(1.0, indexProgress) *
|
||||
codebaseIndex.relativeExpectedTime) /
|
||||
totalRelativeExpectedTime) /
|
||||
workspaceDirs.length;
|
||||
// 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: progress,
|
||||
desc,
|
||||
status: "indexing",
|
||||
};
|
||||
}
|
||||
|
||||
lastUpdated.forEach((lastUpdated, path) => {
|
||||
markComplete([lastUpdated], IndexResultType.UpdateLastUpdated);
|
||||
});
|
||||
|
||||
completedRelativeExpectedTime += codebaseIndex.relativeExpectedTime;
|
||||
yield {
|
||||
progress:
|
||||
(completedDirs +
|
||||
completedRelativeExpectedTime / totalRelativeExpectedTime) /
|
||||
workspaceDirs.length,
|
||||
desc: "Completed indexing " + codebaseIndex.artifactId,
|
||||
status: "indexing",
|
||||
};
|
||||
} catch (e: any) {
|
||||
let errMsg = `${e}`;
|
||||
|
||||
const errorRegex =
|
||||
/Invalid argument error: Values length (\d+) is less than the length \((\d+)\) multiplied by the value size \(\d+\)/;
|
||||
const match = e.message.match(errorRegex);
|
||||
|
||||
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.`;
|
||||
}
|
||||
|
||||
yield {
|
||||
progress: 0,
|
||||
desc: errMsg,
|
||||
status: "failed",
|
||||
};
|
||||
|
||||
console.warn(
|
||||
`Error updating the ${codebaseIndex.artifactId} index: ${e}`,
|
||||
);
|
||||
return;
|
||||
completedOps +=
|
||||
subResult.compute.length +
|
||||
subResult.del.length +
|
||||
subResult.addTag.length +
|
||||
subResult.removeTag.length;
|
||||
progress =
|
||||
(completedIndexCount + completedOps / totalOps) *
|
||||
(1 / indexesToBuild.length);
|
||||
}
|
||||
}
|
||||
|
||||
completedDirs++;
|
||||
progress = completedDirs / workspaceDirs.length;
|
||||
yield {
|
||||
progress,
|
||||
desc: "Indexing Complete",
|
||||
status: "done",
|
||||
};
|
||||
await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
|
||||
completedIndexCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async getWorkspaceDir(filepath: string): Promise<string | undefined> {
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
if (filepath.startsWith(workspaceDir)) {
|
||||
return workspaceDir;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async basename(filepath: string): Promise<string> {
|
||||
const pathSep = await this.ide.pathSep();
|
||||
const path = filepath.split(pathSep);
|
||||
return path[path.length - 1];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue