diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index bad9f55f0..f9a4b0151 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -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. ] diff --git a/.github/workflows/README.md b/.github/workflows/README.md index f22d06955..ff1b7bd22 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -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 diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml new file mode 100644 index 000000000..d909a279a --- /dev/null +++ b/.github/workflows/dev_pr.yaml @@ -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 diff --git a/.github/workflows/jetbrains-build.yaml b/.github/workflows/jetbrains-build.yaml deleted file mode 100644 index 16d07163c..000000000 --- a/.github/workflows/jetbrains-build.yaml +++ /dev/null @@ -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<> $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 diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 3df1ae29f..e4400f20b 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -2,14 +2,19 @@ # Running the publishPlugin task requires all following secrets to be provided: PUBLISH_TOKEN, PRIVATE_KEY, PRIVATE_KEY_PASSWORD, CERTIFICATE_CHAIN. # See https://plugins.jetbrains.com/docs/intellij/plugin-signing.html for more information. -name: Release -# on: -# release: -# types: [prereleased, released] +name: JetBrains Release + +on: + release: + types: [prereleased] defaults: run: - working-directory: ./extensions/intellij + working-directory: extensions/intellij + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true jobs: check_release_name: @@ -18,19 +23,20 @@ jobs: should_run: ${{ steps.check.outputs.should_run }} steps: - id: check + working-directory: . run: | - if [[ "${{ github.event.release.name }}" == *-jetbrains ]]; then + if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then echo "should_run=true" >> $GITHUB_OUTPUT else echo "should_run=false" >> $GITHUB_OUTPUT fi # Prepare and publish the plugin to JetBrains Marketplace repository - release: + build: needs: check_release_name if: needs.check_release_name.outputs.should_run == 'true' - name: Publish Plugin - runs-on: ubuntu-latest + name: Build Plugin + runs-on: macos-latest permissions: contents: write pull-requests: write @@ -41,14 +47,26 @@ jobs: with: ref: ${{ github.event.release.tag_name }} - # Set up Java environment for the next steps + - name: Import Apple certificate + uses: apple-actions/import-codesign-certs@v3 + with: + keychain: ${{ github.run_id }} + keychain-password: ${{ github.run_id }} + p12-file-base64: ${{ secrets.APPLE_CERT_DATA }} + p12-password: ${{ secrets.APPLE_CERT_PASSWORD }} + + # Validate wrapper + - name: Gradle Wrapper Validation + uses: gradle/actions/wrapper-validation@v3 + + # # Set up Java environment for the next steps - name: Setup Java uses: actions/setup-java@v4 with: distribution: zulu java-version: 17 - # Setup Gradle + # # Setup Gradle - name: Setup Gradle uses: gradle/actions/setup-gradle@v3 with: @@ -59,16 +77,21 @@ jobs: id: properties shell: bash run: | - CHANGELOG="$(cat << 'EOM' | sed -e 's/^[[:space:]]*$//g' -e '/./,$!d' - ${{ github.event.release.body }} - EOM - )" + PROPERTIES="$(./gradlew properties --console=plain -q)" + VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" + # CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" + CHANGELOG="" + + echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT echo "changelog<> $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 diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 3591d3e23..8e57aede7 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -1,14 +1,27 @@ name: Publish Extension on: - create: - tags: - - "v0.8.*-vscode" - branches: - - main + release: + types: [released] jobs: + check_release_name: + runs-on: ubuntu-latest + outputs: + should_run: ${{ steps.check.outputs.should_run }} + steps: + - id: check + working-directory: . + run: | + if [[ "${{ github.event.release.tag_name }}" == v0.8.*-vscode ]]; then + echo "should_run=true" >> $GITHUB_OUTPUT + else + echo "should_run=false" >> $GITHUB_OUTPUT + fi + build: + needs: check_release_name + if: needs.check_release_name.outputs.should_run == 'true' strategy: matrix: include: @@ -97,10 +110,12 @@ jobs: cd gui npm ci + # npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json - name: Install Core Dependencies run: | cd core npm ci + npm i vectordb - name: Run core tests run: | diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 6fca2c0ad..3958730ec 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -1,14 +1,27 @@ name: Publish Preview Extension on: - create: - tags: - - "v0.9.*-vscode" - branches: - - dev + release: + types: [prereleased] jobs: + check_release_name: + runs-on: ubuntu-latest + outputs: + should_run: ${{ steps.check.outputs.should_run }} + steps: + - id: check + working-directory: . + run: | + if [[ "${{ github.event.release.tag_name }}" == v0.9.*-vscode ]]; then + echo "should_run=true" >> $GITHUB_OUTPUT + else + echo "should_run=false" >> $GITHUB_OUTPUT + fi + build: + needs: check_release_name + if: needs.check_release_name.outputs.should_run == 'true' strategy: matrix: include: @@ -92,10 +105,19 @@ jobs: cd gui npm ci + # npm ci doesn't end up capturing the @lancedb/... dep because it's not in the package-lock.json - name: Install Core Dependencies run: | cd core npm ci + npm i vectordb + + # - name: Run core tests + # run: | + # cd core + # npm run test + # env: + # OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} # 2.5. Pre package - name: Set var for environment info @@ -107,14 +129,6 @@ jobs: cd extensions/vscode npm run prepackage -- --target ${{ env.target }} - # 2.75 Run core tests - - name: Run core tests - run: | - cd core - npm run test - env: - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - # 3. Re-install esbuild (for cases that we force installed for another arch in prepackage.js) - name: Re-install esbuild run: | diff --git a/.github/workflows/ts-check.yaml b/.github/workflows/ts-check.yaml index 193988990..f73016fa5 100644 --- a/.github/workflows/ts-check.yaml +++ b/.github/workflows/ts-check.yaml @@ -5,7 +5,6 @@ on: branches: - main - preview - - dev jobs: tsc-check: diff --git a/.gitignore b/.gitignore index bf28524cd..3fa43ae1a 100644 --- a/.gitignore +++ b/.gitignore @@ -165,7 +165,5 @@ Icon? .continue -# Sandbox env default file -extensions/vscode/manual-testing-sandbox/example.ts .prompts/ \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index 54d282cc8..896793040 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -17,10 +17,7 @@ "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode" ], "pauseForSourceMap": false, - "outFiles": [ - "${workspaceFolder}/extensions/vscode/out/extension.js", - "/Users/natesesti/.continue/config.ts" - ], + "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], "preLaunchTask": "vscode-extension:build", "env": { // "CONTROL_PLANE_ENV": "local" diff --git a/.vscode/settings.json b/.vscode/settings.json index 060bc5e6c..f56d10f61 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -15,6 +15,7 @@ }, "search.exclude": { "**/binary": true, + "binary/": false, "**/core/vendor/**": true, "**/gui/dist": true } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 49dbba82e..2e595561f 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -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": [] } ] } diff --git a/CHANGELOG.md b/CHANGELOG.md index 010e9d1e3..268bbe613 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2192b2b8d..0a998802a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -152,7 +152,7 @@ Pre-requisite: You should use the Intellij IDE, which can be downloaded [here](h ##### Debugging -Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The Intellij extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file. +Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The JetBrains extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file. For the sake of rapid development, it is also possible to configure this communication to happen over local TCP sockets: diff --git a/binary/README.md b/binary/README.md index beff54b4b..741cc425f 100644 --- a/binary/README.md +++ b/binary/README.md @@ -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 +``` diff --git a/binary/build.js b/binary/build.js index d2f01ee35..016afe9bd 100644 --- a/binary/build.js +++ b/binary/build.js @@ -162,6 +162,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { "../core/vendor/tree-sitter.wasm", "../core/llm/llamaTokenizerWorkerPool.mjs", "../core/llm/llamaTokenizer.mjs", + "../core/llm/tiktokenWorkerPool.mjs", ]; for (const f of filesToCopy) { fs.copyFileSync( @@ -237,9 +238,20 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { }.tar.gz`; execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`); execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); - fs.copyFileSync( - `${targetDir}/build/Release/node_sqlite3.node`, - `${targetDir}/node_sqlite3.node`, + + // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + fs.writeFileSync( + `${targetDir}/package.json`, + JSON.stringify( + { + name: "binary", + version: "1.0.0", + author: "Continue Dev, Inc", + license: "Apache-2.0", + }, + undefined, + 2, + ), ); // Copy to build directory for testing @@ -247,7 +259,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { const [platform, arch] = target.split("-"); if (platform === currentPlatform && arch === currentArch) { fs.copyFileSync( - `${targetDir}/node_sqlite3.node`, + `${targetDir}/build/Release/node_sqlite3.node`, `build/node_sqlite3.node`, ); } @@ -257,10 +269,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { } fs.unlinkSync(`${targetDir}/build.tar.gz`); - fs.rmSync(`${targetDir}/build`, { - recursive: true, - force: true, - }); // Download and unzip prebuilt esbuild binary for the target console.log(`[info] Downloading esbuild for ${target}...`); @@ -299,9 +307,18 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { `${targetDir}/continue-binary${exe}`, `${targetDir}/esbuild${exe}`, `${targetDir}/index.node`, // @lancedb - `${targetDir}/node_sqlite3.node`, + "package.json", // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + `${targetDir}/build/Release/node_sqlite3.node`, ); } + + // Note that this doesn't verify they actually made it into the binary, just that they were in the expected folder before it was built + pathsToVerify.push("out/index.js"); + pathsToVerify.push("out/llamaTokenizerWorkerPool.mjs"); + pathsToVerify.push("out/tiktokenWorkerPool.mjs"); + pathsToVerify.push("out/xhr-sync-worker.js"); + pathsToVerify.push("out/tree-sitter.wasm"); + validateFilesPresent(pathsToVerify); console.log("[info] Done!"); diff --git a/binary/package-lock.json b/binary/package-lock.json index 9378d2eef..dfcd3371a 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -49,6 +49,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.10", "@continuedev/llm-info": "^1.0.1", + "@crawlee/playwright": "^3.11.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -57,11 +58,11 @@ "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", "axios": "^1.6.7", - "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", "dbinfoz": "^0.1.4", "dotenv": "^16.4.5", + "extract-zip": "^2.0.1", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", @@ -79,7 +80,9 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", + "playwright": "^1.46.1", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", "replicate": "^0.26.0", diff --git a/binary/pkgJson/darwin-arm64/package.json b/binary/pkgJson/darwin-arm64/package.json index cc41ae801..ce6f2cace 100644 --- a/binary/pkgJson/darwin-arm64/package.json +++ b/binary/pkgJson/darwin-arm64/package.json @@ -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" diff --git a/binary/pkgJson/darwin-x64/package.json b/binary/pkgJson/darwin-x64/package.json index 8ccb256e1..178ef6471 100644 --- a/binary/pkgJson/darwin-x64/package.json +++ b/binary/pkgJson/darwin-x64/package.json @@ -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" diff --git a/binary/pkgJson/linux-arm64/package.json b/binary/pkgJson/linux-arm64/package.json index 9fe88da50..4a3b2a42f 100644 --- a/binary/pkgJson/linux-arm64/package.json +++ b/binary/pkgJson/linux-arm64/package.json @@ -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" diff --git a/binary/pkgJson/linux-x64/package.json b/binary/pkgJson/linux-x64/package.json index 1c875baa0..f62ecede7 100644 --- a/binary/pkgJson/linux-x64/package.json +++ b/binary/pkgJson/linux-x64/package.json @@ -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" diff --git a/binary/pkgJson/win32-arm64/package.json b/binary/pkgJson/win32-arm64/package.json index 3eeb12234..478cf7eb9 100644 --- a/binary/pkgJson/win32-arm64/package.json +++ b/binary/pkgJson/win32-arm64/package.json @@ -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" diff --git a/binary/pkgJson/win32-x64/package.json b/binary/pkgJson/win32-x64/package.json index 2e495524b..c466fc942 100644 --- a/binary/pkgJson/win32-x64/package.json +++ b/binary/pkgJson/win32-x64/package.json @@ -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" diff --git a/binary/src/IpcMessenger.ts b/binary/src/IpcMessenger.ts index 66acb1448..341372d8e 100644 --- a/binary/src/IpcMessenger.ts +++ b/binary/src/IpcMessenger.ts @@ -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); diff --git a/binary/src/logging.ts b/binary/src/logging.ts index cba34855c..b6dbfba2c 100644 --- a/binary/src/logging.ts +++ b/binary/src/logging.ts @@ -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..."); } diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 1c67b146c..8ba241323 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -8,7 +8,7 @@ "plugins": ["@typescript-eslint", "import"], "rules": { "quotes": ["warn", "double", {}], - "@typescript-eslint/naming-convention": "warn", + "@typescript-eslint/naming-convention": "off", "@typescript-eslint/semi": "warn", "curly": "warn", "eqeqeq": "warn", diff --git a/core/.gitignore b/core/.gitignore index ad1c54334..7d8f1fa53 100644 --- a/core/.gitignore +++ b/core/.gitignore @@ -4,4 +4,5 @@ target npm-debug.log* .env .continue-test -testDir \ No newline at end of file +testDir +coverage \ No newline at end of file diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index 4e25c9fef..2c68be1bf 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -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 diff --git a/core/autocomplete/brackets.ts b/core/autocomplete/brackets.ts index 63afdfd10..3734df2be 100644 --- a/core/autocomplete/brackets.ts +++ b/core/autocomplete/brackets.ts @@ -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); } diff --git a/core/test/streamTransforms/stopAtStopTokens.test.ts b/core/autocomplete/charStream.test.ts similarity index 98% rename from core/test/streamTransforms/stopAtStopTokens.test.ts rename to core/autocomplete/charStream.test.ts index cdb507dd7..7ab8923fc 100644 --- a/core/test/streamTransforms/stopAtStopTokens.test.ts +++ b/core/autocomplete/charStream.test.ts @@ -1,4 +1,4 @@ -import { stopAtStopTokens } from "../../autocomplete/charStream.js"; +import { stopAtStopTokens } from "./charStream"; describe("stopAtStopTokens", () => { async function* createMockStream(chunks: string[]): AsyncGenerator { diff --git a/core/autocomplete/charStream.ts b/core/autocomplete/charStream.ts index 0ce49e418..79fc33a0d 100644 --- a/core/autocomplete/charStream.ts +++ b/core/autocomplete/charStream.ts @@ -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} 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} An async generator that yields characters. + */ export async function* onlyWhitespaceAfterEndOfLine( stream: AsyncGenerator, endOfLine: string[], fullStop: () => void, ): AsyncGenerator { 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} stream - The input character stream. + * @yields {string} Characters from the stream. + */ export async function* noFirstCharNewline(stream: AsyncGenerator) { let first = true; for await (const char of stream) { @@ -40,6 +58,20 @@ export async function* noFirstCharNewline(stream: AsyncGenerator) { } } +/** + * Asynchronously yields characters from the input stream, stopping if a stop token is encountered. + * + * @param {AsyncGenerator} 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} 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, stopTokens: string[], diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index c67ce1f0a..39d2d1e73 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -37,7 +37,7 @@ import { import { isOnlyPunctuationAndWhitespace } from "./filter.js"; import { AutocompleteLanguageInfo } from "./languages.js"; import { - avoidPathLine, + avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, skipPrefixes, stopAtLines, @@ -478,9 +478,9 @@ export class CompletionProvider { const lines = fullPrefix.split("\n"); fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ lang.singleLineComment - } ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${ - lines[lines.length - 1] - }`; + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; } const fullSuffix = getRangeInString(fileContents, { @@ -581,7 +581,10 @@ export class CompletionProvider { prefix = `${formattedSnippets}\n\n${prefix}`; } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n${prefix}`; + prefix = `${lang.singleLineComment} ${getLastNPathParts( + filepath, + 2, + )}\n${prefix}`; } prompt = compiledTemplate({ @@ -689,7 +692,10 @@ export class CompletionProvider { let lineGenerator = streamLines(charGenerator); lineGenerator = stopAtLines(lineGenerator, fullStop); lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment); + lineGenerator = avoidPathLineAndEmptyComments( + lineGenerator, + lang.singleLineComment, + ); lineGenerator = skipPrefixes(lineGenerator); lineGenerator = noTopLevelKeywordsMidline( lineGenerator, diff --git a/core/autocomplete/languages.ts b/core/autocomplete/languages.ts index 19ab65f71..f5b4cffb0 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/languages.ts @@ -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: [], }; diff --git a/core/autocomplete/lineStream.test.ts b/core/autocomplete/lineStream.test.ts new file mode 100644 index 000000000..df8cd1263 --- /dev/null +++ b/core/autocomplete/lineStream.test.ts @@ -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); + }); + }); +}); diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 674f0d46e..e7d3493bd 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -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 = [""]; +export const LINES_TO_STOP_AT = ["# End of file.", ""]; +export const LINES_TO_REMOVE_BEFORE_START = [ + "", + "[CODE]", + "", +]; + +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: ' 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 { 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.", " 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 = [""]; +/** + * 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 = [""]; - +/** + * 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 = [ - "", - "[CODE]", - "", -]; - -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} 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, ): AsyncGenerator { 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; } } diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts index 635f52012..422b377bd 100644 --- a/core/autocomplete/retrieval.ts +++ b/core/autocomplete/retrieval.ts @@ -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, diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templates.ts index 53aa034a9..030e0a306 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templates.ts @@ -33,8 +33,8 @@ const stableCodeFimTemplate: AutocompleteTemplate = { "", "", "", - "<|endoftext|>", "", + "<|endoftext|>", "", "", ], @@ -70,7 +70,9 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`) .join("\n\n"); return [ - `${otherFiles}\n\n+++++ ${relativePaths[relativePaths.length - 1]}\n${prefix}`, + `${otherFiles}\n\n+++++ ${ + relativePaths[relativePaths.length - 1] + }\n${prefix}`, suffix, ]; }, @@ -132,8 +134,8 @@ const starcoder2FimTemplate: AutocompleteTemplate = { "", "", "", - "<|endoftext|>", "", + "<|endoftext|>", ], }, }; @@ -172,8 +174,10 @@ const codegeexFimTemplate: AutocompleteTemplate = { ...snippets.map((snippet) => snippet.filepath), filepath, ]); - const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1]}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; - if (snippets.length == 0) { + const baseTemplate = `###PATH:${ + relativePaths[relativePaths.length - 1] + }\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; + if (snippets.length === 0) { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } const references = `###REFERENCE:\n${snippets diff --git a/core/commands/slash/comment.ts b/core/commands/slash/comment.ts index 929763bf3..e3b601c04 100644 --- a/core/commands/slash/comment.ts +++ b/core/commands/slash/comment.ts @@ -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", diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index a0fbfdd26..a3c3ed91c 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -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 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) + diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index ed5fa4dec..a7738a041 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import { IDE, SlashCommand } from "../.."; import * as fs from "fs/promises"; import * as path from "path"; diff --git a/core/test/config/ConfigHandler.skip.ts b/core/config/ConfigHandler.test.ts similarity index 83% rename from core/test/config/ConfigHandler.skip.ts rename to core/config/ConfigHandler.test.ts index ef35789cb..ef4e1814d 100644 --- a/core/test/config/ConfigHandler.skip.ts +++ b/core/config/ConfigHandler.test.ts @@ -1,11 +1,11 @@ import fs from "node:fs"; import path from "node:path"; -import { defaultConfig } from "../../config/default"; -import { getConfigTsPath } from "../../util/paths"; -import { testConfigHandler } from "../fixtures"; -import { TEST_DIR } from "../testUtils/testDir"; +import { defaultConfig } from "./default"; +import { getConfigTsPath } from "../util/paths"; +import { testConfigHandler } from "../test/util/fixtures"; +import { TEST_DIR } from "../test/util/testDir"; -describe("Test the ConfigHandler and E2E config loading", () => { +describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { const profiles = testConfigHandler.listProfiles(); expect(profiles.length).toBe(1); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index dff0b065b..a95da2db1 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -51,12 +51,12 @@ class ProfileLifecycleManager { } // Clear saved config and reload - reloadConfig(): Promise { + async reloadConfig(): Promise { this.savedConfig = undefined; this.savedBrowserConfig = undefined; this.pendingConfigPromise = undefined; - return this.profileLoader.doLoadConfig(); + return await this.profileLoader.doLoadConfig(); } async loadConfig( diff --git a/core/config/load.ts b/core/config/load.ts index a9b2ba94f..2bb836d73 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -355,9 +355,11 @@ async function intermediateToFinalConfig( // These context providers are always included, regardless of what, if anything, // the user has configured in config.json + + const codebaseContextParams = ((config.contextProviders || []).filter(isContextProviderWithParams).find(cp => cp.name === "codebase") as ContextProviderWithParams | undefined)?.params || {}; const DEFAULT_CONTEXT_PROVIDERS = [ new FileContextProvider({}), - new CodebaseContextProvider({}), + new CodebaseContextProvider(codebaseContextParams), ]; const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 16f72d40e..2ff3f9294 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -10,6 +10,7 @@ import { import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js"; import { Telemetry } from "../../util/posthog.js"; +import { TTS } from "../../util/tts.js"; import { loadFullConfigNode } from "../load.js"; export default async function doLoadConfig( @@ -48,9 +49,12 @@ export default async function doLoadConfig( await Telemetry.setup( newConfig.allowAnonymousTelemetry ?? true, await ide.getUniqueId(), - ideInfo.extensionVersion, + ideInfo, ); + // TODO: pass config to pre-load non-system TTS models + await TTS.setup(); + if (newConfig.analytics) { await TeamAnalytics.setup( newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 92d558aaf..f1bfc898d 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,8 +4,8 @@ import * as YAML from "yaml"; import type { IDE, SlashCommand } from ".."; import { walkDir } from "../indexing/walkDir"; import { stripImages } from "../llm/images"; -import { getBasename } from "../util/index"; import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; +import { getBasename } from "../util/index"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; diff --git a/core/context/providers/PostgresContextProvider.ts b/core/context/providers/PostgresContextProvider.ts index 494a3bc33..55c00ae3c 100644 --- a/core/context/providers/PostgresContextProvider.ts +++ b/core/context/providers/PostgresContextProvider.ts @@ -37,7 +37,7 @@ class PostgresContextProvider extends BaseContextProvider { let tablesInfoQuery = ` SELECT table_schema, table_name FROM information_schema.tables`; - if (schema != null) { + if (schema !== null) { tablesInfoQuery += ` WHERE table_schema = '${schema}'`; } const { rows: tablesInfo } = await pool.query(tablesInfoQuery); diff --git a/core/context/rerankers/tei.ts b/core/context/rerankers/tei.ts index 667181ae3..61f38b98b 100644 --- a/core/context/rerankers/tei.ts +++ b/core/context/rerankers/tei.ts @@ -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, diff --git a/core/context/retrieval/fullTextSearch.ts b/core/context/retrieval/fullTextSearch.ts index 3e22db302..9c52bd6b6 100644 --- a/core/context/retrieval/fullTextSearch.ts +++ b/core/context/retrieval/fullTextSearch.ts @@ -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, diff --git a/core/continueServer/stubs/headers.ts b/core/continueServer/stubs/headers.ts index e6a864230..ca1e0df9d 100644 --- a/core/continueServer/stubs/headers.ts +++ b/core/continueServer/stubs/headers.ts @@ -6,7 +6,7 @@ export async function getHeaders() { key: constants.c, timestamp: getTimestamp(), v: "1", - extensionVersion: Telemetry.extensionVersion ?? "0.0.0", + extensionVersion: Telemetry.ideInfo?.extensionVersion ?? "0.0.0", os: Telemetry.os ?? "Unknown", uniqueId: Telemetry.uniqueId ?? "None", }; diff --git a/core/control-plane/analytics/LogStashAnalyticsProvider.ts b/core/control-plane/analytics/LogStashAnalyticsProvider.ts index 59d72432a..aa35af43e 100644 --- a/core/control-plane/analytics/LogStashAnalyticsProvider.ts +++ b/core/control-plane/analytics/LogStashAnalyticsProvider.ts @@ -30,7 +30,8 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider { async setup(config: Analytics, uniqueId: string): Promise { 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; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 53e62d247..bee6061b2 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -74,7 +74,7 @@ export class ControlPlaneClient { } try { - const resp = await this.request(`/workspaces`, { + const resp = await this.request("/workspaces", { method: "GET", }); return (await resp.json()) as any; diff --git a/core/core.ts b/core/core.ts index 6718cdf7d..bf61042b7 100644 --- a/core/core.ts +++ b/core/core.ts @@ -26,7 +26,9 @@ import historyManager from "./util/history"; import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { TTS } from "./util/tts"; import { streamDiffLines } from "./util/verticalEdit"; +import DocsCrawler from "./indexing/docs/DocsCrawler"; export class Core { // implements IMessenger @@ -167,12 +169,19 @@ export class Core { (..._) => Promise.resolve([]), ); + try { + DocsCrawler.verifyOrInstallChromium(); + } catch (err) { + console.debug(`Failed to install Chromium: ${err}`); + } + const on = this.messenger.on.bind(this.messenger); this.messenger.onError((err) => { console.error(err); Telemetry.capture("core_messenger_error", { message: err.message, + stack: err.stack, }); this.messenger.request("errorPopup", { message: err.message }); }); @@ -359,6 +368,13 @@ export class Core { abortedMessageIds: Set, msg: Message, ) { + const config = await configHandler.loadConfig(); + + // Stop TTS on new StreamChat + if(config.experimental?.readResponseTTS) { + TTS.kill(); + } + const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( msg.data.messages, @@ -383,6 +399,10 @@ export class Core { next = await gen.next(); } + if(config.experimental?.readResponseTTS && "completion" in next.value) { + TTS.read(next.value?.completion); + } + return { done: true, content: next.value }; } @@ -457,6 +477,13 @@ export class Core { } }); + // Provide messenger to TTS so it can set GUI active / inactive state + TTS.messenger = this.messenger; + + on("tts/kill", async () => { + TTS.kill(); + }); + async function* runNodeJsSlashCommand( configHandler: ConfigHandler, abortedMessageIds: Set, @@ -638,8 +665,13 @@ export class Core { const rows = await DevDataSqliteDb.getTokensPerModel(); return rows; }); - on("index/forceReIndex", async (msg) => { - const dirs = msg.data ? [msg.data] : await this.ide.getWorkspaceDirs(); + on("index/forceReIndex", async ({ data }) => { + if (data?.shouldClearIndexes) { + const codebaseIndexer = await this.codebaseIndexerPromise; + await codebaseIndexer.clearIndexes(); + } + + const dirs = data?.dir ? [data.dir] : await this.ide.getWorkspaceDirs(); await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { @@ -690,6 +722,7 @@ export class Core { "indexing_error", { error: update.desc, + stack: update.debugInfo, }, false, ); diff --git a/core/test/streamDiff.test.ts b/core/diff/streamDiff.test.ts similarity index 100% rename from core/test/streamDiff.test.ts rename to core/diff/streamDiff.test.ts diff --git a/core/index.d.ts b/core/index.d.ts index d3ff2a4b8..9730e2111 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -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; @@ -319,6 +322,7 @@ export interface LLMOptions { uniqueId?: string; systemMessage?: string; contextLength?: number; + maxStopWords?: number; completionOptions?: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; @@ -340,19 +344,23 @@ export interface LLMOptions { apiVersion?: string; apiType?: string; - // GCP Options + // AWS options + profile?: string; + modelArn?: string; + + // AWS and GCP Options region?: string; + + // GCP Options projectId?: string; capabilities?: ModelCapability; - // WatsonX options + // IBM watsonx options watsonxUrl?: string; - watsonxApiKey?: string; - watsonxZenApiKeyBase64?: string; // Required if using watsonx software with ZenApiKey auth - watsonxUsername?: string; - watsonxPassword?: string; + watsonxCreds?: string; watsonxProjectId?: string; watsonxStopToken?: string; + watsonxApiVersion?: string; } type RequireAtLeastOne = Pick< T, @@ -586,6 +594,7 @@ type ModelProvider = | "ollama" | "huggingface-tgi" | "huggingface-inference-api" + | "kindo" | "llama.cpp" | "replicate" | "text-gen-webui" @@ -594,6 +603,7 @@ type ModelProvider = | "gemini" | "mistral" | "bedrock" + | "bedrockimport" | "sagemaker" | "deepinfra" | "flowise" @@ -606,7 +616,8 @@ type ModelProvider = | "azure" | "openai-aiohttp" | "msty" - | "watsonx"; + | "watsonx" + | "openrouter"; export type ModelName = | "AUTODETECT" @@ -745,6 +756,7 @@ export interface ModelDescription { apiKey?: string; apiBase?: string; contextLength?: number; + maxStopWords?: number; template?: TemplateType; completionOptions?: BaseCompletionOptions; systemMessage?: string; @@ -871,10 +883,14 @@ interface QuickActionConfig { sendToChat: boolean; } +export type DefaultContextProvider = ContextProviderWithParams & { + query?: string; +}; + interface ExperimentalConfig { contextMenuPrompts?: ContextMenuConfig; modelRoles?: ModelRoles; - defaultContext?: "activeFile"[]; + defaultContext?: DefaultContextProvider[]; promptPath?: string; /** @@ -882,6 +898,11 @@ interface ExperimentalConfig { * function and class declarations. */ quickActions?: QuickActionConfig[]; + + /** + * Automatically read LLM chat responses aloud using system TTS models + */ + readResponseTTS?: boolean; } interface AnalyticsConfig { diff --git a/core/indexing/CodeSnippetsIndex.test.ts b/core/indexing/CodeSnippetsIndex.test.ts new file mode 100644 index 000000000..a80ffe7bd --- /dev/null +++ b/core/indexing/CodeSnippetsIndex.test.ts @@ -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, + ); + }); +}); diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 8fc1ccb95..00b949c72 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -100,26 +100,30 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { contents: string, ): Promise<(ChunkWithoutID & { title: string })[]> { const parser = await getParserForFile(filepath); + if (!parser) { return []; } + const ast = parser.parse(contents); const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets); const matches = query?.matches(ast.rootNode); - return ( - matches?.flatMap((match) => { - const node = match.captures[0].node; - const title = match.captures[1].node.text; - const results = { - title, - content: node.text, - startLine: node.startPosition.row, - endLine: node.endPosition.row, - }; - return results; - }) ?? [] - ); + if (!matches) { + return []; + } + + return matches.flatMap((match) => { + const node = match.captures[0].node; + const title = match.captures[1].node.text; + const results = { + title, + content: node.text, + startLine: node.startPosition.row, + endLine: node.endPosition.row, + }; + return results; + }); } async *update( @@ -132,6 +136,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { await CodeSnippetsCodebaseIndex._createTables(db); const tagString = tagToString(tag); + // Compute for (let i = 0; i < results.compute.length; i++) { const compute = results.compute[i]; @@ -174,18 +179,29 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { markComplete([compute], IndexResultType.Compute); } + // Delete for (let i = 0; i < results.del.length; i++) { const del = results.del[i]; - const deleted = await db.run( - "DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?", + + const snippets = await db.all( + "SELECT id FROM code_snippets WHERE path = ? AND cacheKey = ?", [del.path, del.cacheKey], ); - await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [ - deleted.lastID, - ]); + + if (snippets) { + const snippetIds = snippets.map((row) => row.id).join(","); + + await db.run(`DELETE FROM code_snippets WHERE id IN (${snippetIds})`); + + await db.run( + `DELETE FROM code_snippets_tags WHERE snippetId IN (${snippetIds})`, + ); + } + markComplete([del], IndexResultType.Delete); } + // Add tag for (let i = 0; i < results.addTag.length; i++) { const addTag = results.addTag[i]; let snippets: (ChunkWithoutID & { title: string })[] = []; @@ -220,19 +236,33 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { markComplete([results.addTag[i]], IndexResultType.AddTag); } + // Remove tag for (let i = 0; i < results.removeTag.length; i++) { - const item = results.removeTag[i]; - await db.run( - ` - DELETE FROM code_snippets_tags - WHERE tag = ? - AND snippetId IN ( - SELECT id FROM code_snippets - WHERE cacheKey = ? AND path = ? - ) - `, - [tagString, item.cacheKey, item.path], + const removeTag = results.removeTag[i]; + + let snippets = await db.get( + `SELECT id FROM code_snippets + WHERE cacheKey = ? AND path = ?`, + [removeTag.cacheKey, removeTag.path], ); + + if (snippets) { + if (!Array.isArray(snippets)) { + snippets = [snippets]; + } + + const snippetIds = snippets.map((row: any) => row.id).join(","); + + await db.run( + ` + DELETE FROM code_snippets_tags + WHERE tag = ? + AND snippetId IN (${snippetIds}) + `, + [tagString], + ); + } + markComplete([results.removeTag[i]], IndexResultType.RemoveTag); } } diff --git a/core/test/indexing/CodebaseIndexer.skip.ts b/core/indexing/CodebaseIndexer.test.ts similarity index 89% rename from core/test/indexing/CodebaseIndexer.skip.ts rename to core/indexing/CodebaseIndexer.test.ts index 6d7d73c8d..f05acfc16 100644 --- a/core/test/indexing/CodebaseIndexer.skip.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -2,20 +2,20 @@ import { jest } from "@jest/globals"; import { execSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -import { ContinueServerClient } from "../../continueServer/stubs/client.js"; -import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js"; -import { getComputeDeleteAddRemove } from "../../indexing/refreshIndex.js"; -import { TestCodebaseIndex } from "../../indexing/TestCodebaseIndex.js"; -import { CodebaseIndex } from "../../indexing/types.js"; -import { walkDir } from "../../indexing/walkDir.js"; -import { getIndexSqlitePath } from "../../util/paths.js"; -import { testConfigHandler, testIde } from "../fixtures.js"; +import { ContinueServerClient } from "../continueServer/stubs/client.js"; +import { testConfigHandler, testIde } from "../test/util/fixtures.js"; import { addToTestDir, setUpTestDir, tearDownTestDir, TEST_DIR, -} from "../testUtils/testDir.js"; +} from "../test/util/testDir.js"; +import { getIndexSqlitePath } from "../util/paths.js"; +import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; +import { getComputeDeleteAddRemove } from "./refreshIndex.js"; +import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; +import { CodebaseIndex } from "./types.js"; +import { walkDir } from "./walkDir.js"; jest.useFakeTimers(); @@ -71,6 +71,9 @@ describe("CodebaseIndexer", () => { beforeAll(async () => { tearDownTestDir(); setUpTestDir(); + + execSync('git config --global user.email "test@example.com"'); + execSync('git config --global user.name "Test"'); }); afterAll(async () => { diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 984704aa2..b377d5a2f 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,9 +1,12 @@ +import * as fs from "fs/promises"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { IContinueServerClient } from "../continueServer/interface.js"; -import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js"; +import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js"; +import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; +import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; -import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js"; +import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; import { LanceDbIndex } from "./LanceDbIndex.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { @@ -26,6 +29,24 @@ export class PauseToken { } export class CodebaseIndexer { + /** + * We batch for two reasons: + * - To limit memory usage for indexes that perform computations locally, e.g. FTS + * - To make as few requests as possible to the embeddings providers + */ + filesPerBatch = 1000; + + // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on, + // e.g. a `SQLITE_BUSY` error. + errorsRegexesToClearIndexesOn = [ + /Invalid argument error: Values length (d+) is less than the length ((d+)) multiplied by the value size (d+)/, + /SQLITE_CONSTRAINT/, + /SQLITE_ERROR/, + /SQLITE_CORRUPT/, + /SQLITE_IOERR/, + /SQLITE_FULL/, + ]; + constructor( private readonly configHandler: ConfigHandler, protected readonly ide: IDE, @@ -33,6 +54,23 @@ export class CodebaseIndexer { private readonly continueServerClient: IContinueServerClient, ) {} + async clearIndexes() { + const sqliteFilepath = getIndexSqlitePath(); + const lanceDbFolder = getLanceDbPath(); + + try { + await fs.unlink(sqliteFilepath); + } catch (error) { + console.error(`Error deleting ${sqliteFilepath} folder: ${error}`); + } + + try { + await fs.rm(lanceDbFolder, { recursive: true, force: true }); + } catch (error) { + console.error(`Error deleting ${lanceDbFolder}: ${error}`); + } + } + protected async getIndexesToBuild(): Promise { const config = await this.configHandler.loadConfig(); const pathSep = await this.ide.pathSep(); @@ -88,6 +126,12 @@ export class CodebaseIndexer { results.removeTag = []; results.addTag = []; results.del = []; + + // Don't update if nothing to update. Some of the indices might do unnecessary setup work + if (results.compute.length === 0) { + continue; + } + for await (const _ of index.update( tag, results, @@ -203,7 +247,6 @@ export class CodebaseIndexer { yield this.handleErrorAndGetProgressUpdate(err); return; } - completedDirs += 1; } yield { progress: 100, @@ -223,24 +266,31 @@ export class CodebaseIndexer { progress: 0, desc: `Indexing failed: ${err}`, status: "failed", + debugInfo: extractMinimalStackTraceInfo((err as any)?.stack), }; } private errorToProgressUpdate(err: Error): IndexingProgressUpdate { - const errorRegex = - /Invalid argument error: Values length (\d+) is less than the length \((\d+)\) multiplied by the value size \(\d+\)/; - const match = err.message.match(errorRegex); - let errMsg: string; - if (match) { - const [_, valuesLength, expectedLength] = match; - errMsg = `Generated embedding had length ${valuesLength} but was expected to be ${expectedLength}. This may be solved by deleting ~/.continue/index and refreshing the window to re-index.`; - } else { - errMsg = `${err}`; + let errMsg: string = `${err}`; + let shouldClearIndexes = false; + + // Check if any of the error regexes match + for (const regexStr of this.errorsRegexesToClearIndexesOn) { + const regex = new RegExp(regexStr); + const match = err.message.match(regex); + + if (match !== null) { + shouldClearIndexes = true; + break; + } } + return { progress: 0, desc: errMsg, status: "failed", + shouldClearIndexes, + debugInfo: extractMinimalStackTraceInfo(err.stack), }; } @@ -269,20 +319,14 @@ export class CodebaseIndexer { } } - private getBatchSize(workspaceSize: number): number { - return 100; - } - /* - * enables the indexing operation to be completed in small batches, this is important in large + * Enables the indexing operation to be completed in batches, this is important in large * repositories where indexing can quickly use up all the memory available */ private *batchRefreshIndexResults( results: RefreshIndexResults, - workspaceSize: number, ): Generator { let curPos = 0; - const batchSize = this.getBatchSize(workspaceSize); while ( curPos < results.compute.length || curPos < results.del.length || @@ -290,12 +334,12 @@ export class CodebaseIndexer { curPos < results.removeTag.length ) { yield { - compute: results.compute.slice(curPos, curPos + batchSize), - del: results.del.slice(curPos, curPos + batchSize), - addTag: results.addTag.slice(curPos, curPos + batchSize), - removeTag: results.removeTag.slice(curPos, curPos + batchSize), + compute: results.compute.slice(curPos, curPos + this.filesPerBatch), + del: results.del.slice(curPos, curPos + this.filesPerBatch), + addTag: results.addTag.slice(curPos, curPos + this.filesPerBatch), + removeTag: results.removeTag.slice(curPos, curPos + this.filesPerBatch), }; - curPos += batchSize; + curPos += this.filesPerBatch; } } @@ -333,31 +377,33 @@ export class CodebaseIndexer { results.addTag.length + results.removeTag.length; let completedOps = 0; - for (const subResult of this.batchRefreshIndexResults( - results, - workspaceFiles.length, - )) { - for await (const { desc } of codebaseIndex.update( - tag, - subResult, - markComplete, - repoName, - )) { - yield { - progress: progress, - desc, - status: "indexing", - }; + + // Don't update if nothing to update. Some of the indices might do unnecessary setup work + if (totalOps > 0) { + for (const subResult of this.batchRefreshIndexResults(results)) { + for await (const { desc } of codebaseIndex.update( + tag, + subResult, + markComplete, + repoName, + )) { + yield { + progress: progress, + desc, + status: "indexing", + }; + } + completedOps += + subResult.compute.length + + subResult.del.length + + subResult.addTag.length + + subResult.removeTag.length; + progress = + (completedIndexCount + completedOps / totalOps) * + (1 / indexesToBuild.length); } - completedOps += - subResult.compute.length + - subResult.del.length + - subResult.addTag.length + - subResult.removeTag.length; - progress = - (completedIndexCount + completedOps / totalOps) * - (1 / indexesToBuild.length); } + await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated); completedIndexCount += 1; } diff --git a/core/indexing/FullTextSearchCodebaseIndex.test.ts b/core/indexing/FullTextSearchCodebaseIndex.test.ts new file mode 100644 index 000000000..af59d0b3c --- /dev/null +++ b/core/indexing/FullTextSearchCodebaseIndex.test.ts @@ -0,0 +1,67 @@ +import { jest } from "@jest/globals"; +import { + insertMockChunks, + mockPathAndCacheKey, + updateIndexAndAwaitGenerator, +} from "../test/util/indexing"; +import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { IndexResultType } from "./types"; + +describe("FullTextSearchCodebaseIndex", () => { + let index: FullTextSearchCodebaseIndex; + let db: DatabaseConnection; + + async function getFts() { + return await db.all("SELECT * FROM fts"); + } + + async function getFtsMetadata() { + return await db.all("SELECT * FROM fts_metadata"); + } + + beforeEach(async () => { + db = await SqliteDb.get(); + index = new FullTextSearchCodebaseIndex(); + }); + + it.skip("should update the index and maintain expected database state", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + await insertMockChunks(); + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + expect((await getFts()).length).toBe(1); + expect((await getFtsMetadata()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // RemoveTag test - currently, we don't do anything other than mark complete + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // AddTag test - currently, we don't do anything other than mark complete + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + expect((await getFts()).length).toBe(0); + expect((await getFtsMetadata()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearchCodebaseIndex.ts similarity index 87% rename from core/indexing/FullTextSearch.ts rename to core/indexing/FullTextSearchCodebaseIndex.ts index c640eae20..7a571bc13 100644 --- a/core/indexing/FullTextSearch.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -1,23 +1,19 @@ -import { - BranchAndDir, - Chunk, - IndexTag, - IndexingProgressUpdate, -} from "../index.js"; -import { getBasename } from "../util/index.js"; -import { RETRIEVAL_PARAMS } from "../util/parameters.js"; -import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; +import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; +import { getBasename } from "../util/index"; +import { RETRIEVAL_PARAMS } from "../util/parameters"; +import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, RefreshIndexResults, type CodebaseIndex, -} from "./types.js"; +} from "./types"; export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; - artifactId = "sqliteFts"; + static artifactId = "sqliteFts"; + artifactId: string = ChunkCodebaseIndex.artifactId; private async _createTables(db: DatabaseConnection) { await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( @@ -90,11 +86,12 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { - const { lastID } = await db.run( - "DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", - [item.path, item.cacheKey], - ); - await db.run("DELETE FROM fts WHERE rowid = ?", [lastID]); + await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [ + item.path, + item.cacheKey, + ]); + + await db.run("DELETE FROM fts WHERE path = ?", [item.path]); markComplete([item], IndexResultType.Delete); } diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts new file mode 100644 index 000000000..0c636df6a --- /dev/null +++ b/core/indexing/LanceDbIndex.test.ts @@ -0,0 +1,115 @@ +import { jest } from "@jest/globals"; +import lance from "vectordb"; +import { testConfigHandler, testIde } from "../test/util/fixtures"; +import { + mockPathAndCacheKey, + mockTag, + testContinueServerClient, + updateIndexAndAwaitGenerator, +} from "../test/util/indexing"; +import { getLanceDbPath } from "../util/paths"; +import { LanceDbIndex } from "./LanceDbIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { IndexResultType } from "./types"; + +jest.useFakeTimers(); + +describe("ChunkCodebaseIndex", () => { + let index: LanceDbIndex; + let sqliteDb: DatabaseConnection; + let lanceDb: lance.Connection; + + async function getAllSqliteLanceDbCache() { + return await sqliteDb.all("SELECT * FROM lance_db_cache"); + } + + beforeAll(async () => { + const pathSep = await testIde.pathSep(); + const mockConfig = await testConfigHandler.loadConfig(); + + index = new LanceDbIndex( + mockConfig.embeddingsProvider, + testIde.readFile.bind(testIde), + pathSep, + testContinueServerClient, + ); + + sqliteDb = await SqliteDb.get(); + lanceDb = await lance.connect(getLanceDbPath()); + }); + + /** + * Some notes on quirks of this test: + * - Currently, it appears that there is a race condition in LanceDB that + * requires us to re-open the table connection each time we want to read + * from it. Attempting to follow these docs did not resolve the issue: + * https://lancedb.github.io/lancedb/guides/tables/#consistency + * + * - We cannot open either the 'dev' or 'main' tag tables ubtil after we + * can assume they've been created through `updateIndexAndAwaitGenerator` + */ + it.skip("should update the index and maintain expected database state", async () => { + const mainTag = mockTag; + const mainTagTableName = index.tableNameForTag(mainTag); + + const devTag = { ...mockTag, branch: "dev" }; + const devTagTableName = index.tableNameForTag(devTag); + + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + // Compute test - inserts into both LanceDB and Sqlite + await updateIndexAndAwaitGenerator( + index, + "compute", + mockMarkComplete, + mainTag, + ); + let mainTagTable = await lanceDb.openTable(mainTagTableName); + expect(await mainTagTable.countRows()).toBe(1); + expect((await getAllSqliteLanceDbCache()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // AddTag test - only inserts into Lance DB + await updateIndexAndAwaitGenerator( + index, + "addTag", + mockMarkComplete, + devTag, + ); + let devTagTable = await lanceDb.openTable(devTagTableName); + expect(await devTagTable.countRows()).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // RemoveTag - only removes from Lance DB + await updateIndexAndAwaitGenerator( + index, + "removeTag", + mockMarkComplete, + devTag, + ); + devTagTable = await lanceDb.openTable(devTagTableName); + expect(await devTagTable.countRows()).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // Delete test - removes from LanceDB and Sqlite + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete, mainTag); + mainTagTable = await lanceDb.openTable(mainTagTableName); + expect(await mainTagTable.countRows()).toBe(0); + expect((await getAllSqliteLanceDbCache()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 198232a95..7c4787529 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -1,7 +1,7 @@ // NOTE: vectordb requirement must be listed in extensions/vscode to avoid error import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; -import { Table } from "vectordb"; +import lance, { Table } from "vectordb"; import { IContinueServerClient } from "../continueServer/interface.js"; import { BranchAndDir, @@ -31,6 +31,10 @@ interface LanceDbRow { [key: string]: any; } +type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] }; + +type ChunkMap = Map; + export class LanceDbIndex implements CodebaseIndex { relativeExpectedTime: number = 13; get artifactId(): string { @@ -44,7 +48,7 @@ export class LanceDbIndex implements CodebaseIndex { private readonly continueServerClient?: IContinueServerClient, ) {} - private tableNameForTag(tag: IndexTag) { + tableNameForTag(tag: IndexTag) { return tagToString(tag).replace(/[^\w-_.]/g, ""); } @@ -85,77 +89,112 @@ export class LanceDbIndex implements CodebaseIndex { ); } - private async packToRows(item: PathAndCacheKey): Promise { - const content = await this.readFile(item.path); - if (!shouldChunk(this.pathSep, item.path, content)) { - return []; + private async computeRows(items: PathAndCacheKey[]): Promise { + const chunkMap = await this.collectChunks(items); + const allChunks = Array.from(chunkMap.values()).flatMap( + ({ chunks }) => chunks, + ); + const embeddings = await this.getEmbeddings(allChunks); + + // Remove undefined embeddings and their corresponding chunks + for (let i = embeddings.length - 1; i >= 0; i--) { + if (embeddings[i] === undefined) { + const chunk = allChunks[i]; + const chunks = chunkMap.get(chunk.filepath)?.chunks; + + if (chunks) { + const index = chunks.findIndex((c) => c === chunk); + if (index !== -1) { + chunks.splice(index, 1); + } + } + + embeddings.splice(i, 1); + } } + + return this.createLanceDbRows(chunkMap, embeddings); + } + + private async collectChunks(items: PathAndCacheKey[]): Promise { + const chunkMap: ChunkMap = new Map(); + + for (const item of items) { + try { + const content = await this.readFile(item.path); + + if (!shouldChunk(this.pathSep, item.path, content)) { + continue; + } + + const chunks = await this.getChunks(item, content); + chunkMap.set(item.path, { item, chunks }); + } catch (err) { + console.log(`LanceDBIndex, skipping ${item.path}: ${err}`); + } + } + + return chunkMap; + } + + private async getChunks( + item: PathAndCacheKey, + content: string, + ): Promise { const chunks: Chunk[] = []; + const chunkParams = { filepath: item.path, contents: content, maxChunkSize: this.embeddingsProvider.maxChunkSize, digest: item.cacheKey, }; + for await (const chunk of chunkDocument(chunkParams)) { if (chunk.content.length === 0) { - // File did not chunk properly, let's skip it. throw new Error("did not chunk properly"); } + chunks.push(chunk); } - const embeddings = await this.chunkListToEmbedding(chunks); - if (chunks.length !== embeddings.length) { - throw new Error( - `Unexpected lengths: chunks and embeddings do not match for ${item.path}`, - ); - } - const results = []; - for (let i = 0; i < chunks.length; i++) { - results.push({ - path: item.path, - cachekey: item.cacheKey, - uuid: uuidv4(), - vector: embeddings[i], - startLine: chunks[i].startLine, - endLine: chunks[i].endLine, - contents: chunks[i].content, - }); - } - return results; + + return chunks; } - private async chunkListToEmbedding(chunks: Chunk[]): Promise { - let embeddings: number[][]; + private async getEmbeddings(chunks: Chunk[]): Promise { try { - embeddings = await this.embeddingsProvider.embed( - chunks.map((c) => c.content), - ); + return await this.embeddingsProvider.embed(chunks.map((c) => c.content)); } catch (err) { throw new Error( - `Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}: ${err}`, + `Failed to generate embeddings for ${chunks.length} chunks with provider: ${this.embeddingsProvider.id}: ${err}`, { cause: err }, ); } - if (embeddings.some((emb) => emb === undefined)) { - throw new Error( - `Empty embedding returned for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}`, - ); - } - return embeddings; } - private async computeRows(items: PathAndCacheKey[]): Promise { - const rowChunkPromises = items.map(this.packToRows.bind(this)); - const rowChunkLists = []; - for (let i = 0; i < items.length; i++) { - try { - rowChunkLists.push(await rowChunkPromises[i]); - } catch (err) { - console.log(`LanceDBIndex, skipping ${items[i].path}: ${err}`); + private createLanceDbRows( + chunkMap: ChunkMap, + embeddings: number[][], + ): LanceDbRow[] { + const results: LanceDbRow[] = []; + let embeddingIndex = 0; + + for (const [path, { item, chunks }] of chunkMap) { + for (const chunk of chunks) { + results.push({ + path, + cachekey: item.cacheKey, + uuid: uuidv4(), + vector: embeddings[embeddingIndex], + startLine: chunk.startLine, + endLine: chunk.endLine, + contents: chunk.content, + }); + embeddingIndex++; } } - return rowChunkLists.flat(); + + return results; } async *update( @@ -164,40 +203,39 @@ export class LanceDbIndex implements CodebaseIndex { markComplete: MarkCompleteCallback, repoName: string | undefined, ): AsyncGenerator { - const lancedb = await import("vectordb"); - const tableName = this.tableNameForTag(tag); - const db = await lancedb.connect(getLanceDbPath()); + const sqliteDb = await SqliteDb.get(); + await this.createSqliteCacheTable(sqliteDb); - const sqlite = await SqliteDb.get(); - await this.createSqliteCacheTable(sqlite); + const lanceTableName = this.tableNameForTag(tag); + const lanceDb = await lance.connect(getLanceDbPath()); + const existingLanceTables = await lanceDb.tableNames(); + + let lanceTable: Table | undefined = undefined; + let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName); // Compute - let table: Table | undefined = undefined; - const existingTables = await db.tableNames(); - let needToCreateTable = !existingTables.includes(tableName); - const addComputedLanceDbRows = async ( - pathAndCacheKey: PathAndCacheKey, + pathAndCacheKeys: PathAndCacheKey[], computedRows: LanceDbRow[], ) => { // Create table if needed, add computed rows - if (table) { + if (lanceTable) { if (computedRows.length > 0) { - await table.add(computedRows); + await lanceTable.add(computedRows); } - } else if (existingTables.includes(tableName)) { - table = await db.openTable(tableName); - needToCreateTable = false; + } else if (existingLanceTables.includes(lanceTableName)) { + lanceTable = await lanceDb.openTable(lanceTableName); + needToCreateLanceTable = false; if (computedRows.length > 0) { - await table.add(computedRows); + await lanceTable.add(computedRows); } } else if (computedRows.length > 0) { - table = await db.createTable(tableName, computedRows); - needToCreateTable = false; + lanceTable = await lanceDb.createTable(lanceTableName, computedRows); + needToCreateLanceTable = false; } // Mark item complete - await markComplete([pathAndCacheKey], IndexResultType.Compute); + await markComplete(pathAndCacheKeys, IndexResultType.Compute); }; // Check remote cache @@ -233,7 +271,7 @@ export class LanceDbIndex implements CodebaseIndex { }; rows.push(row); - await sqlite.run( + await sqliteDb.run( "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", row.uuid, row.cachekey, @@ -246,7 +284,7 @@ export class LanceDbIndex implements CodebaseIndex { ); } - await addComputedLanceDbRows({ cacheKey, path }, rows); + await addComputedLanceDbRows([{ cacheKey, path }], rows); } // Remove items that don't need to be recomputed @@ -267,21 +305,13 @@ export class LanceDbIndex implements CodebaseIndex { }; const dbRows = await this.computeRows(results.compute); - await this.insertRows(sqlite, dbRows); - await Promise.all( - results.compute.map((item) => { - addComputedLanceDbRows( - item, - dbRows.filter((row) => row.path === item.path), - ); - }), - ); - await markComplete(results.compute, IndexResultType.Compute); + await this.insertRows(sqliteDb, dbRows); + await addComputedLanceDbRows(results.compute, dbRows); let accumulatedProgress = 0; // Add tag - retrieve the computed info from lance sqlite cache for (const { path, cacheKey } of results.addTag) { - const stmt = await sqlite.prepare( + const stmt = await sqliteDb.prepare( "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", cacheKey, path, @@ -289,25 +319,28 @@ export class LanceDbIndex implements CodebaseIndex { ); const cachedItems = await stmt.all(); - const lanceRows: LanceDbRow[] = cachedItems.map((item) => { - return { + const lanceRows: LanceDbRow[] = cachedItems.map( + ({ uuid, vector, startLine, endLine, contents }) => ({ path, + uuid, + startLine, + endLine, + contents, cachekey: cacheKey, - uuid: item.uuid, - vector: JSON.parse(item.vector), - }; - }); + vector: JSON.parse(vector), + }), + ); if (lanceRows.length > 0) { - if (needToCreateTable) { - table = await db.createTable(tableName, lanceRows); - needToCreateTable = false; - } else if (!table) { - table = await db.openTable(tableName); - needToCreateTable = false; - await table.add(lanceRows); + if (needToCreateLanceTable) { + lanceTable = await lanceDb.createTable(lanceTableName, lanceRows); + needToCreateLanceTable = false; + } else if (!lanceTable) { + lanceTable = await lanceDb.openTable(lanceTableName); + needToCreateLanceTable = false; + await lanceTable.add(lanceRows); } else { - await table?.add(lanceRows); + await lanceTable?.add(lanceRows); } } @@ -321,11 +354,18 @@ export class LanceDbIndex implements CodebaseIndex { } // Delete or remove tag - remove from lance table) - if (!needToCreateTable) { + if (!needToCreateLanceTable) { const toDel = [...results.removeTag, ...results.del]; + + if (!lanceTable) { + lanceTable = await lanceDb.openTable(lanceTableName); + } + for (const { path, cacheKey } of toDel) { // This is where the aforementioned lowercase conversion problem shows - await table?.delete(`cachekey = '${cacheKey}' AND path = '${path}'`); + await lanceTable.delete( + `cachekey = '${cacheKey}' AND path = '${path}'`, + ); accumulatedProgress += 1 / toDel.length / 3; yield { @@ -335,11 +375,12 @@ export class LanceDbIndex implements CodebaseIndex { }; } } + await markComplete(results.removeTag, IndexResultType.RemoveTag); // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { - await sqlite.run( + await sqliteDb.run( "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", cacheKey, path, @@ -354,6 +395,7 @@ export class LanceDbIndex implements CodebaseIndex { } await markComplete(results.del, IndexResultType.Delete); + yield { progress: 1, desc: "Completed Calculating Embeddings", @@ -375,8 +417,7 @@ export class LanceDbIndex implements CodebaseIndex { return []; } - const table = await db.openTable(tableName); - let query = table.search(vector); + let query = db.search(vector); if (directory) { // seems like lancedb is only post-filtering, so have to return a bunch of results and slice after query = query.where(`path LIKE '${directory}%'`).limit(300); @@ -393,12 +434,8 @@ export class LanceDbIndex implements CodebaseIndex { tags: BranchAndDir[], filterDirectory: string | undefined, ): Promise { - const lancedb = await import("vectordb"); - if (!lancedb.connect) { - throw new Error("LanceDB failed to load a native module"); - } const [vector] = await this.embeddingsProvider.embed([query]); - const db = await lancedb.connect(getLanceDbPath()); + const db = await lance.connect(getLanceDbPath()); let allResults = []; for (const tag of tags) { @@ -481,9 +518,10 @@ export class LanceDbIndex implements CodebaseIndex { { cause: err }, ), ); + } else { + resolve(); } }); - resolve(); }); }); } diff --git a/core/indexing/README.md b/core/indexing/README.md index b0f8d408a..2a7375f00 100644 --- a/core/indexing/README.md +++ b/core/indexing/README.md @@ -23,8 +23,8 @@ All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./ `CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file `FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5 `ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex` -`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite +`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. -## Known problems: +## Known problems - `FullTextSearchCodebaseIndex` doesn't differentiate between tags (branch, repo), so results may come from any branch/repo. LanceDB does this by creating separate tables for each tag (see `tableNameForTag`). The chunk index does this with a second table diff --git a/core/indexing/TestCodebaseIndex.ts b/core/indexing/TestCodebaseIndex.ts index 234bcbc3e..7031fd992 100644 --- a/core/indexing/TestCodebaseIndex.ts +++ b/core/indexing/TestCodebaseIndex.ts @@ -35,14 +35,14 @@ export class TestCodebaseIndex implements CodebaseIndex { for (const item of [...results.compute, ...results.addTag]) { await db.run( - `INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)`, + "INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)", [item.path, tag.branch, tag.directory], ); } for (const item of [...results.del, ...results.removeTag]) { await db.run( - `DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?`, + "DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?", [item.path, tag.branch, tag.directory], ); } diff --git a/core/indexing/chunk/ChunkCodebaseIndex.test.ts b/core/indexing/chunk/ChunkCodebaseIndex.test.ts new file mode 100644 index 000000000..7453e8a78 --- /dev/null +++ b/core/indexing/chunk/ChunkCodebaseIndex.test.ts @@ -0,0 +1,83 @@ +import { jest } from "@jest/globals"; +import { testIde } from "../../test/util/fixtures"; +import { + mockFileContents, + mockFilename, + mockPathAndCacheKey, + testContinueServerClient, + updateIndexAndAwaitGenerator, +} from "../../test/util/indexing"; +import { addToTestDir } from "../../test/util/testDir"; +import { DatabaseConnection, SqliteDb } from "../refreshIndex"; +import { IndexResultType } from "../types"; +import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex"; + +jest.useFakeTimers(); + +describe("ChunkCodebaseIndex", () => { + let index: ChunkCodebaseIndex; + let db: DatabaseConnection; + + async function getAllChunks() { + return await db.all("SELECT * FROM chunks"); + } + + async function getAllChunkTags() { + return await db.all("SELECT * FROM chunk_tags"); + } + + beforeAll(async () => { + const pathSep = await testIde.pathSep(); + + index = new ChunkCodebaseIndex( + testIde.readFile.bind(testIde), + pathSep, + testContinueServerClient, + 1000, + ); + + addToTestDir([[mockFilename, mockFileContents]]); + + db = await SqliteDb.get(); + }); + + it.skip("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + expect((await getAllChunks()).length).toBe(1); + expect((await getAllChunkTags()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // RemoveTag test + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + expect((await getAllChunkTags()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // AddTag test + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + expect((await getAllChunkTags()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + expect((await getAllChunks()).length).toBe(0); + expect((await getAllChunkTags()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 008f90c62..cdf91f359 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -1,8 +1,8 @@ +import * as path from "path"; import { RunResult } from "sqlite3"; import { IContinueServerClient } from "../../continueServer/interface.js"; import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js"; import { getBasename } from "../../util/index.js"; -import { getLanguageForFile } from "../../util/treeSitter.js"; import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js"; import { IndexResultType, @@ -61,8 +61,11 @@ export class ChunkCodebaseIndex implements CodebaseIndex { let accumulatedProgress = 0; if (results.compute.length > 0) { + const filepath = results.compute[0].path; + const folderName = path.basename(path.dirname(filepath)); + yield { - desc: `Chunking ${results.compute.length} ${this.formatListPlurality("file", results.compute.length)}`, + desc: `Chunking files in ${folderName}`, status: "indexing", progress: accumulatedProgress, }; @@ -114,14 +117,21 @@ export class ChunkCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { - const deleted = await db.run("DELETE FROM chunks WHERE cacheKey = ?", [ - item.cacheKey, - ]); + const chunkToDelete = await db.get( + "SELECT id FROM chunks WHERE cacheKey = ?", + [item.cacheKey], + ); - // Delete from chunk_tags - await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [ - deleted.lastID, - ]); + if (chunkToDelete) { + await db.run("DELETE FROM chunks WHERE id = ?", [chunkToDelete.id]); + + // Delete from chunk_tags + await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [ + chunkToDelete.id, + ]); + } else { + console.debug("Chunk to delete wasn't found in the table: ", item.path); + } await markComplete([item], IndexResultType.Delete); accumulatedProgress += 1 / results.del.length / 4; @@ -133,7 +143,6 @@ export class ChunkCodebaseIndex implements CodebaseIndex { } } - private async createTables(db: DatabaseConnection) { await db.exec(`CREATE TABLE IF NOT EXISTS chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -172,11 +181,17 @@ export class ChunkCodebaseIndex implements CodebaseIndex { } private async computeChunks(paths: PathAndCacheKey[]): Promise { - const chunkLists = await Promise.all(paths.map(p => this.packToChunks(p))); + const chunkLists = await Promise.all( + paths.map((p) => this.packToChunks(p)), + ); return chunkLists.flat(); } - private async insertChunks(db: DatabaseConnection, tagString: string, chunks: Chunk[]) { + private async insertChunks( + db: DatabaseConnection, + tagString: string, + chunks: Chunk[], + ) { await new Promise((resolve, reject) => { db.db.serialize(() => { db.db.exec("BEGIN", (err: Error | null) => { @@ -184,31 +199,50 @@ export class ChunkCodebaseIndex implements CodebaseIndex { reject(new Error("error creating transaction", { cause: err })); } }); - const chunksSQL = "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)"; - chunks.map(c => { - db.db.run(chunksSQL, [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content], (result: RunResult, err: Error) => { - if (err) { - reject(new Error("error inserting into chunks table", { cause: err })); - } - }); - const chunkTagsSQL = "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)"; - db.db.run(chunkTagsSQL, [ tagString ], (result: RunResult, err: Error) => { - if (err) { - reject(new Error("error inserting into chunk_tags table", { cause: err })); - } - }); + const chunksSQL = + "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)"; + chunks.map((c) => { + db.db.run( + chunksSQL, + [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content], + (result: RunResult, err: Error) => { + if (err) { + reject( + new Error("error inserting into chunks table", { + cause: err, + }), + ); + } + }, + ); + const chunkTagsSQL = + "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)"; + db.db.run( + chunkTagsSQL, + [tagString], + (result: RunResult, err: Error) => { + if (err) { + reject( + new Error("error inserting into chunk_tags table", { + cause: err, + }), + ); + } + }, + ); }); db.db.exec("COMMIT", (err: Error | null) => { if (err) { - reject(new Error("error while committing insert chunks transaction", { cause: err })); + reject( + new Error("error while committing insert chunks transaction", { + cause: err, + }), + ); + } else { + resolve(); } }); - resolve(); }); }); } - - private formatListPlurality(word: string, length: number): string { - return length <= 1 ? word : `${word}s`; - } } diff --git a/core/test/indexing/chunk/chunk.test.ts b/core/indexing/chunk/chunk.test.ts similarity index 94% rename from core/test/indexing/chunk/chunk.test.ts rename to core/indexing/chunk/chunk.test.ts index e45c11c79..a9559ca27 100644 --- a/core/test/indexing/chunk/chunk.test.ts +++ b/core/indexing/chunk/chunk.test.ts @@ -1,5 +1,5 @@ import path from "path"; -import { shouldChunk } from "../../../indexing/chunk/chunk"; +import { shouldChunk } from "./chunk"; describe("shouldChunk", () => { test("should chunk a typescript file", () => { diff --git a/core/test/indexing/chunk/code.test.ts b/core/indexing/chunk/code.test.ts similarity index 85% rename from core/test/indexing/chunk/code.test.ts rename to core/indexing/chunk/code.test.ts index 00615d124..c852ecafd 100644 --- a/core/test/indexing/chunk/code.test.ts +++ b/core/indexing/chunk/code.test.ts @@ -1,5 +1,5 @@ -import { ChunkWithoutID } from "../../../index.js"; -import { codeChunker } from "../../../indexing/chunk/code.js"; +import { ChunkWithoutID } from "../.."; +import { codeChunker } from "./code"; async function genToArr(generator: AsyncGenerator): Promise { const result: T[] = []; @@ -29,7 +29,7 @@ describe.skip("codeChunker", () => { test("should capture small class and function from large python file", async () => { const extraLine = "# This is a comment"; const myClass = "class MyClass:\n def __init__(self):\n pass"; - const myFunction = 'def my_function():\n return "Hello, World!"'; + const myFunction = "def my_function():\n return \"Hello, World!\""; const file = Array(100).fill(extraLine).join("\n") + @@ -66,7 +66,7 @@ describe.skip("codeChunker", () => { chunks[0].startsWith("class MyClass:\n def method1():\n ..."), ).toBe(true); // The extra spaces seem to be a bug with tree-sitter-python - expect(chunks).toContain('def method1():\n return "Hello, 1!"'); - expect(chunks).toContain('def method20():\n return "Hello, 20!"'); + expect(chunks).toContain("def method1():\n return \"Hello, 1!\""); + expect(chunks).toContain("def method20():\n return \"Hello, 20!\""); }); }); diff --git a/core/indexing/docs/DocsCrawler.test.ts b/core/indexing/docs/DocsCrawler.test.ts new file mode 100644 index 000000000..b3c4b2593 --- /dev/null +++ b/core/indexing/docs/DocsCrawler.test.ts @@ -0,0 +1,130 @@ +import DocsCrawler, { type PageData } from "./DocsCrawler"; +import preIndexedDocs from "./preIndexedDocs"; + +// Temporary workaround until we have better caching of Chromium +// download between test runs +const TIMEOUT = 1_000_000; + +// Skipped until we have a better way to cache Chromium installs +// between tests and in CI +describe.skip("crawl", () => { + describe("GitHub repositories", () => { + const repoUrl = + "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; + + let crawlResults: PageData[]; + + beforeAll(async () => { + const docsCrawler = new DocsCrawler(new URL(repoUrl)); + + crawlResults = []; + + for await (const page of docsCrawler.crawl()) { + crawlResults.push(page); + } + }, TIMEOUT); + + test("finds expected markdown files", async () => { + expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( + true, + ); + + expect( + crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), + ).toBe(true); + }); + + test("html includes the correct content", async () => { + const doc = crawlResults.find((page) => + page.path.endsWith("docs-depth-1.md"), + ); + + expect(doc?.content.includes("Test body")).toBe(true); + expect(doc?.content.includes("Test H2 Header")).toBe(true); + }); + + test("ignores non-markdown files, e.g. `test.js` at the root", async () => { + expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( + false, + ); + }); + }); + + describe.only("Non-Github repository sites", () => { + it( + "succeeds in crawling a list of common sites", + async () => { + const TEST_SITES = [ + "https://docs.nestjs.com/", + "https://docs.nestjs.com/", + "https://go.dev/doc/", + "https://clickhouse.com/docs", + "https://www.tensorflow.org/api_docs", + "https://www.rust-lang.org/learn", + "https://docs.anthropic.com/en/docs", + ]; + + const NUM_PAGES_TO_CRAWL = 10; + + for (const site of TEST_SITES) { + const crawlResults: PageData[] = []; + const docsCrawler = new DocsCrawler( + new URL(site), + NUM_PAGES_TO_CRAWL, + ); + + for await (const page of docsCrawler.crawl()) { + crawlResults.push(page); + } + + // `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee + // an exact number of pages to crawl since it runs in parallel + expect(crawlResults.length).toBeGreaterThanOrEqual( + NUM_PAGES_TO_CRAWL, + ); + } + }, + TIMEOUT, + ); + }); + + describe("Pre-indexed Docs", () => { + const results: { [url: string]: boolean } = {}; + let totalTests = 0; + let passedTests = 0; + + Object.keys(preIndexedDocs).forEach((url) => { + test( + `Crawl test for ${url}`, + async () => { + totalTests++; + let pageFound = false; + + try { + const docsCrawler = new DocsCrawler(new URL(url), 1); + + for await (const page of docsCrawler.crawl()) { + if (page.url === url) { + pageFound = true; + break; + } + } + } catch (error) { + console.error(`Error crawling ${url}:`, error); + } + + results[url] = pageFound; + if (pageFound) { + passedTests++; + console.log(`✅ ${url}`); + } else { + console.log(`❌ ${url}`); + } + + expect(pageFound).toBe(true); + }, + TIMEOUT, + ); + }); + }); +}); diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts new file mode 100644 index 000000000..afd3ea440 --- /dev/null +++ b/core/indexing/docs/DocsCrawler.ts @@ -0,0 +1,248 @@ +import { Octokit } from "@octokit/rest"; +import * as fs from "fs"; +import { URL } from "node:url"; +import { Page } from "puppeteer"; +import { getChromiumPath, getContinueUtilsPath } from "../../util/paths"; +// @ts-ignore +// @prettier-ignore +import PCR from "puppeteer-chromium-resolver"; + +export type PageData = { + url: string; + path: string; + content: string; +}; + +export default class DocsCrawler { + LINK_GROUP_SIZE = 2; // Controls parallelization of crawler + GITHUB_HOST = "github.com"; + static MAX_REQUESTS_PER_CRAWL = 1000; + markdownRegex = new RegExp(/\.(md|mdx)$/); + octokit = new Octokit({ + auth: undefined, + }); + + static PCR_CONFIG = { + downloadPath: getContinueUtilsPath(), + }; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number = DocsCrawler.MAX_REQUESTS_PER_CRAWL, + ) {} + + static verifyOrInstallChromium() { + if (!fs.existsSync(getChromiumPath())) { + PCR(DocsCrawler.PCR_CONFIG); + } + } + + async *crawl(): AsyncGenerator { + if (this.startUrl.host === this.GITHUB_HOST) { + yield* this.crawlGithubRepo(); + } else { + yield* this.crawlSite(); + } + } + + private async getGithubRepoDefaultBranch( + owner: string, + repo: string, + ): Promise { + const repoInfo = await this.octokit.repos.get({ + owner, + repo, + }); + + return repoInfo.data.default_branch; + } + + private async getGitHubRepoPaths( + owner: string, + repo: string, + branch: string, + ) { + const tree = await this.octokit.request( + "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", + { + owner, + repo, + tree_sha: branch, + headers: { + "X-GitHub-Api-Version": "2022-11-28", + }, + recursive: "true", + }, + ); + + const paths = tree.data.tree + .filter( + (file: any) => + file.type === "blob" && this.markdownRegex.test(file.path ?? ""), + ) + .map((file: any) => file.path); + + return paths; + } + + private async getGithubRepoFileContent( + path: string, + owner: string, + repo: string, + ) { + try { + const response = await this.octokit.repos.getContent({ + owner, + repo, + path, + headers: { + Accept: "application/vnd.github.raw+json", + }, + }); + + return response.data as unknown as string; + } catch (error) { + console.debug("Error fetching file contents:", error); + return null; + } + } + + private async *crawlGithubRepo() { + console.debug(`Crawling GitHub repo: ${this.startUrl.toString()}`); + + const urlStr = this.startUrl.toString(); + const [_, owner, repo] = this.startUrl.pathname.split("/"); + const branch = await this.getGithubRepoDefaultBranch(owner, repo); + const paths = await this.getGitHubRepoPaths(owner, repo, branch); + + for await (const path of paths) { + const content = await this.getGithubRepoFileContent(path, owner, repo); + + yield { + path, + url: urlStr, + content: content ?? "", + }; + } + } + + private stripHashFromUrl(urlStr: string) { + try { + let url = new URL(urlStr); + url.hash = ""; + return url; + } catch (err) { + return null; + } + } + + private isValidHostAndPath(newUrl: URL, curUrl: URL) { + return ( + newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host + ); + } + + private async getLinksFromPage(page: Page, curUrl: URL) { + const links = await page.$$eval("a", (links) => links.map((a) => a.href)); + + // This additional step is due to issues getting the URL module to work + // in an $$eval command + const cleanedLinks = links + .map(this.stripHashFromUrl) + .filter( + (newUrl) => + newUrl !== null && + this.isValidHostAndPath(newUrl, curUrl) && + newUrl !== curUrl, + ) + .map((newUrl) => (newUrl as URL).href); + + const dedupedLinks = Array.from(new Set(cleanedLinks)); + + return dedupedLinks; + } + + private async getLinkGroupsFromPage(page: Page, curUrl: URL) { + const links = await this.getLinksFromPage(page, curUrl); + + const groups = links.reduce((acc, link, i) => { + const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); + + if (!acc[groupIndex]) { + acc.push([]); + } + + acc[groupIndex].push(link); + + return acc; + }, [] as string[][]); + + return groups; + } + + private async *crawlSitePages( + page: Page, + curUrl: URL, + visitedLinks: Set = new Set(), + curRequestCount: number = 0, + ): AsyncGenerator { + if (curRequestCount >= this.maxRequestsPerCrawl) { + console.warn("Max requests per crawl reached. Stopping crawler."); + return; + } + + if (visitedLinks.has(curUrl.toString())) { + return; + } + + console.debug(`Crawling page: ${curUrl.toString()}`); + + await page.goto(curUrl.toString()); + + const htmlContent = await page.content(); + const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); + const requestCount = curRequestCount + 1; + + visitedLinks.add(curUrl.toString()); + + yield { + path: curUrl.pathname, + url: curUrl.toString(), + content: htmlContent, + }; + + for (const linkGroup of linkGroups) { + for (const link of linkGroup) { + yield* this.crawlSitePages( + page, + new URL(link), + visitedLinks, + requestCount, + ); + } + } + } + + private async *crawlSite(): AsyncGenerator { + console.debug(`Crawling site repo: ${this.startUrl}`); + + const stats = await PCR(DocsCrawler.PCR_CONFIG); + + const browser = await stats.puppeteer.launch({ + args: [ + "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", + ], + executablePath: stats.executablePath, + }); + + const page = await browser.newPage(); + + try { + yield* this.crawlSitePages(page, this.startUrl); + } catch (e) { + console.debug("Error getting links: ", e); + } finally { + await browser.close(); + } + } +} diff --git a/core/test/indexing/DocsService.skip.ts b/core/indexing/docs/DocsService.test.ts similarity index 87% rename from core/test/indexing/DocsService.skip.ts rename to core/indexing/docs/DocsService.test.ts index da688dbe1..f1fb6295b 100644 --- a/core/test/indexing/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -1,16 +1,14 @@ /** * @jest-environment jsdom */ -import * as fs from "fs"; -import * as path from "path"; import { ConfigHandler } from "../../config/ConfigHandler.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { SiteIndexingConfig } from "../../index.js"; -import DocsService from "../../indexing/docs/DocsService.js"; -import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js"; -import FreeTrialEmbeddingsProvider from "../../indexing/embeddings/FreeTrialEmbeddingsProvider.js"; +import DocsService from "./DocsService.js"; +import preIndexedDocs from "./preIndexedDocs.js"; +import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js"; import FileSystemIde from "../../util/filesystem.js"; -import { editConfigJson, getConfigJsonPath } from "../../util/paths.js"; +import { editConfigJson } from "../../util/paths.js"; describe.skip("DocsService Integration Tests", () => { let ide: FileSystemIde; @@ -23,13 +21,6 @@ describe.skip("DocsService Integration Tests", () => { faviconUrl: "https://github.com/favicon.ico", }; - async function clearConfigDir() { - const configFolder = path.dirname(getConfigJsonPath()); - if (fs.existsSync(configFolder)) { - fs.rmSync(configFolder, { recursive: true, force: true }); - } - } - /** * We need to reload config explicitly to handle the scenario where the * config file update listeners are not called before we attempt to @@ -43,8 +34,6 @@ describe.skip("DocsService Integration Tests", () => { } beforeEach(async () => { - await clearConfigDir(); - ide = new FileSystemIde(process.cwd()); configHandler = new ConfigHandler( @@ -75,10 +64,6 @@ describe.skip("DocsService Integration Tests", () => { await docsService.isInitialized; }); - afterAll(async () => { - await clearConfigDir(); - }); - test("Indexing, retrieval, and deletion of a new documentation site", async () => { const generator = docsService.indexAndAdd(mockSiteConfig); while (!(await generator.next()).done) {} diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 1e8a8245c..fcfc893e5 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -1,8 +1,8 @@ import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; import lancedb, { Connection } from "vectordb"; -import { ConfigHandler } from "../../config/ConfigHandler.js"; -import DocsContextProvider from "../../context/providers/DocsContextProvider.js"; +import { ConfigHandler } from "../../config/ConfigHandler"; +import DocsContextProvider from "../../context/providers/DocsContextProvider"; import { Chunk, ContinueConfig, @@ -10,27 +10,27 @@ import { IDE, IndexingProgressUpdate, SiteIndexingConfig, -} from "../../index.js"; -import { FromCoreProtocol, ToCoreProtocol } from "../../protocol/index.js"; -import { GlobalContext } from "../../util/GlobalContext.js"; -import { IMessenger } from "../../util/messenger.js"; +} from "../.."; +import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; +import { GlobalContext } from "../../util/GlobalContext"; +import { IMessenger } from "../../util/messenger"; import { editConfigJson, getDocsSqlitePath, getLanceDbPath, -} from "../../util/paths.js"; -import { Telemetry } from "../../util/posthog.js"; -import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js"; -import { Article, chunkArticle, pageToArticle } from "./article.js"; -import { crawlPage } from "./crawl.js"; -import { runLanceMigrations, runSqliteMigrations } from "./migrations.js"; +} from "../../util/paths"; +import { Telemetry } from "../../util/posthog"; +import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; +import { Article, chunkArticle, pageToArticle } from "./article"; +import DocsCrawler from "./DocsCrawler"; +import { runLanceMigrations, runSqliteMigrations } from "./migrations"; import { downloadFromS3, getS3Filename, S3Buckets, SiteIndexingResults, -} from "./preIndexed.js"; -import preIndexedDocs from "./preIndexedDocs.js"; +} from "./preIndexed"; +import preIndexedDocs from "./preIndexedDocs"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -112,8 +112,8 @@ export default class DocsService { } /* - * Currently, we generate and host embeddings for pre-indexed docs using transformers.js. - * However, we don't ship transformers.js with the JetBrains extension. + * Currently, we generate and host embeddings for pre-indexed docs using transformers. + * However, we don't ship transformers with the JetBrains extension. * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. */ async canUsePreindexedDocs() { @@ -202,11 +202,10 @@ export default class DocsService { let processedPages = 0; let maxKnownPages = 1; + const docsCrawler = new DocsCrawler(new URL(startUrl)); + // Crawl pages and retrieve info as articles - for await (const page of crawlPage( - new URL(startUrl), - siteIndexingConfig.maxDepth, - )) { + for await (const page of docsCrawler.crawl()) { processedPages++; const article = pageToArticle(page); @@ -279,6 +278,8 @@ export default class DocsService { status: "failed", }; + this.docsIndexingQueue.delete(startUrl); + return; } @@ -291,8 +292,8 @@ export default class DocsService { status: "indexing", }; - // Clear old index if re-indexing. - if (reIndex) { + // Delete indexed docs if re-indexing + if (reIndex && await this.has(startUrl.toString())) { console.log("Deleting old embeddings"); await this.delete(startUrl); } @@ -521,8 +522,9 @@ export default class DocsService { private async getLanceTableNameFromEmbeddingsProvider( isPreIndexedDoc: boolean, ) { - const embeddingsProvider = - await this.getEmbeddingsProvider(isPreIndexedDoc); + const embeddingsProvider = await this.getEmbeddingsProvider( + isPreIndexedDoc, + ); const embeddingsProviderId = this.removeInvalidLanceTableNameChars( embeddingsProvider.id, ); @@ -722,12 +724,13 @@ export default class DocsService { await this.isJetBrainsAndPreIndexedDocsProvider(); if (isJetBrainsAndPreIndexedDocsProvider) { - this.ide.errorPopup( - "The 'transformers.js' embeddings provider currently cannot be used to index " + - "documentation in JetBrains. To enable documentation indexing, you can use " + - "any of the other providers described in the docs: " + - "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", - ); + // A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider + // this.ide.errorPopup( + // "The 'transformers.js' embeddings provider currently cannot be used to index " + + // "documentation in JetBrains. To enable documentation indexing, you can use " + + // "any of the other providers described in the docs: " + + // "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", + // ); this.globalContext.update( "curEmbeddingsProviderId", diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index e972652bf..c86bdb838 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -1,8 +1,8 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; -import { Chunk } from "../../index.js"; -import { cleanFragment, cleanHeader } from "../chunk/markdown.js"; -import { PageData } from "./crawl.js"; +import { Chunk } from "../../"; +import { cleanFragment, cleanHeader } from "../chunk/markdown"; +import { type PageData } from "./DocsCrawler"; export type ArticleComponent = { title: string; @@ -148,7 +148,7 @@ export function stringToArticle( export function pageToArticle(page: PageData): Article | undefined { try { - return stringToArticle(page.url, page.html, page.path); + return stringToArticle(page.url, page.content, page.path); } catch (err) { console.error("Error converting URL to article components", err); return undefined; diff --git a/core/indexing/docs/crawl.ts b/core/indexing/docs/crawl.ts deleted file mode 100644 index 838a92241..000000000 --- a/core/indexing/docs/crawl.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { Octokit } from "@octokit/rest"; -import cheerio from "cheerio"; -import fetch from "node-fetch"; -import { URL } from "node:url"; - -const IGNORE_PATHS_ENDING_IN = [ - "favicon.ico", - "robots.txt", - ".rst.txt", - "genindex", - "py-modindex", - "search.html", - "search", - "genindex.html", - "changelog", - "changelog.html", -]; - -const markdownRegex = new RegExp(/\.(md|mdx)$/); - -async function getDefaultBranch(owner: string, repo: string): Promise { - const octokit = new Octokit({ auth: undefined }); - - const repoInfo = await octokit.repos.get({ - owner, - repo, - }); - - return repoInfo.data.default_branch; -} - -async function crawlGithubRepo(baseUrl: URL) { - const octokit = new Octokit({ - auth: undefined, - }); - - const [_, owner, repo] = baseUrl.pathname.split("/"); - - const branch = await getDefaultBranch(owner, repo); - console.log("Github repo detected. Crawling", branch, "branch"); - - const tree = await octokit.request( - "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", - { - owner, - repo, - tree_sha: branch, - headers: { - "X-GitHub-Api-Version": "2022-11-28", - }, - recursive: "true", - }, - ); - - const paths = tree.data.tree - .filter( - (file: any) => - file.type === "blob" && markdownRegex.test(file.path ?? ""), - ) - .map((file: any) => baseUrl.pathname + "/tree/main/" + file.path); - - return paths; -} - -async function getLinksFromUrl(url: string, path: string) { - const baseUrl = new URL(url); - const location = new URL(path, url); - let response; - - try { - response = await fetch(location.toString()); - } catch (error: unknown) { - if (error instanceof Error && error.message.includes("maximum redirect")) { - console.error("Maximum redirect reached for: ", location.toString()); - return { - html: "", - links: [], - }; - } - console.error(error); - return { - html: "", - links: [], - }; - } - - const html = await response.text(); - let links: string[] = []; - - if (url.includes("github.com")) { - return { - html, - links, - }; - } - - const $ = cheerio.load(html); - - $("a").each((_, element) => { - const href = $(element).attr("href"); - if (!href) { - return; - } - - const parsedUrl = new URL(href, url); - if ( - parsedUrl.hostname === baseUrl.hostname - // parsedUrl.pathname.startsWith(baseUrl.pathname) - ) { - links.push(parsedUrl.pathname); - } - }); - - links = [...new Set(links)].filter((link) => { - return ( - !link.includes("#") && - !IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending)) - ); - }); - - return { - html, - links, - }; -} - -function splitUrl(url: URL) { - const baseUrl = `${url.protocol}//${url.hostname}${ - url.port ? ":" + url.port : "" - }`; - const basePath = url.pathname; - return { - baseUrl, - basePath, - }; -} - -export type PageData = { - url: string; - path: string; - html: string; -}; - -export async function* crawlPage( - url: URL, - maxDepth: number = 3, -): AsyncGenerator { - console.log( - `Starting crawl from: ${url.toString()} - Max Depth: ${maxDepth}`, - ); - - const { baseUrl, basePath } = splitUrl(url); - let paths: { path: string; depth: number }[] = [{ path: basePath, depth: 0 }]; - - if (url.hostname === "github.com") { - const githubLinks = await crawlGithubRepo(url); - const githubLinkObjects = githubLinks.map((link) => ({ - path: link, - depth: 0, - })); - paths = [...paths, ...githubLinkObjects]; - } - - let index = 0; - while (index < paths.length) { - const batch = paths.slice(index, index + 50); - - try { - const promises = batch.map(({ path, depth }) => - getLinksFromUrl(baseUrl, path).then((links) => ({ - links, - path, - depth, - })), - ); // Adjust for depth tracking - - const results = await Promise.all(promises); - for (const { - links: { html, links: linksArray }, - path, - depth, - } of results) { - if (html !== "" && depth <= maxDepth) { - // Check depth - yield { - url: url.toString(), - path, - html, - }; - } - - // Ensure we only add links if within depth limit - if (depth < maxDepth) { - for (let link of linksArray) { - if (!paths.some((p) => p.path === link)) { - paths.push({ path: link, depth: depth + 1 }); // Increment depth for new paths - } - } - } - } - } catch (e) { - if (e instanceof TypeError) { - console.warn("Error while crawling page: ", e); // Likely an invalid url, continue with process - } else { - console.error("Error while crawling page: ", e); - } - } - - index += batch.length; // Proceed to next batch - } - console.log("Crawl completed"); -} diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 1cb34ba6f..9da86ef85 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -1,5 +1,4 @@ -/* eslint-disable @typescript-eslint/naming-convention */ -import { SiteIndexingConfig } from "../../index.js"; +import { SiteIndexingConfig } from "../../"; const preIndexedDocs: Record< SiteIndexingConfig["startUrl"], diff --git a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts index 1bb7af75a..d3c22f3f0 100644 --- a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts +++ b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts @@ -37,9 +37,7 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider { requests, }), headers: { - // eslint-disable-next-line @typescript-eslint/naming-convention "x-goog-api-key": this.options.apiKey, - // eslint-disable-next-line @typescript-eslint/naming-convention "Content-Type": "application/json", }, }), diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index f39dee4fa..acf3d81e8 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -19,13 +19,10 @@ export const allEmbeddingsProviders: Record< EmbeddingsProviderConstructor > = { ollama: OllamaEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "transformers.js": TransformersJsEmbeddingsProvider, openai: OpenAIEmbeddingsProvider, cohere: CohereEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "free-trial": FreeTrialEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, gemini: GeminiEmbeddingsProvider, "continue-proxy": ContinueProxyEmbeddingsProvider, diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 643b61c32..16526e7fb 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -65,6 +65,8 @@ export const DEFAULT_IGNORE_FILETYPES = [ "*.continueignore", "config.json", "*.csv", + "*.uasset", + "*.pdb", // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt ]; diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 26ca80cb6..6800a9e8a 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -1,5 +1,6 @@ import crypto from "node:crypto"; import * as fs from "node:fs"; +import plimit from "p-limit"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; import { IndexTag, IndexingProgressUpdate } from "../index.js"; @@ -112,11 +113,6 @@ async function getSavedItemsForTag( return rows; } -interface PathAndOptionalCacheKey { - path: string; - cacheKey?: string; -} - enum AddRemoveResultType { Add = "add", Remove = "remove", @@ -143,7 +139,6 @@ async function getAddRemoveForTag( const saved = await getSavedItemsForTag(tag); - const add: PathAndCacheKey[] = []; const updateNewVersion: PathAndCacheKey[] = []; const updateOldVersion: PathAndCacheKey[] = []; const remove: PathAndCacheKey[] = []; @@ -178,15 +173,16 @@ async function getAddRemoveForTag( } } - // Any leftover in current files need to be added - add.push( - ...(await Promise.all( - Object.keys(files).map(async (path) => { - const fileContents = await readFile(path); - return { path, cacheKey: calculateHash(fileContents) }; - }), - )), - ); + // limit to only 10 concurrent file reads to avoid issues such as + // "too many file handles". A large number here does not improve + // throughput due to the nature of disk or network i/o -- huge + // amounts of readers generally does not improve performance + const limit = plimit(10); + const promises = Object.keys(files).map(async (path) => { + const fileContents = await limit(() => readFile(path)); + return { path, cacheKey: calculateHash(fileContents) }; + }); + const add: PathAndCacheKey[] = await Promise.all(promises); // Create the markComplete callback function const db = await SqliteDb.get(); @@ -230,7 +226,7 @@ async function getAddRemoveForTag( break; case AddRemoveResultType.Add: await db.run( - "INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)", + "REPLACE INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)", path, cacheKey, newLastUpdatedTimestamp, @@ -395,7 +391,7 @@ export async function getComputeDeleteAddRemove( lastUpdated, async (items, resultType) => { // Update tag catalog - markComplete(items, resultType); + await markComplete(items, resultType); // Update the global cache const results: any = { diff --git a/core/test/walkDir.test.ts b/core/indexing/walkDir.test.ts similarity index 94% rename from core/test/walkDir.test.ts rename to core/indexing/walkDir.test.ts index 87f643f4e..7fa5ed00c 100644 --- a/core/test/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -1,12 +1,12 @@ import path from "path"; -import { walkDir, WalkerOptions } from "../indexing/walkDir.js"; -import FileSystemIde from "../util/filesystem.js"; +import { walkDir, WalkerOptions } from "../indexing/walkDir"; +import FileSystemIde from "../util/filesystem"; import { - addToTestDir, + TEST_DIR, setUpTestDir, tearDownTestDir, - TEST_DIR, -} from "./testUtils/testDir.js"; + addToTestDir, +} from "../test/util/testDir"; const ide = new FileSystemIde(TEST_DIR); @@ -191,6 +191,22 @@ describe("walkDir", () => { await expectPaths(["a.txt"], ["ignored_dir/b.txt", "ignored_dir/c/d.py"]); }); + test("gitignore in sub directory should only apply to subdirectory", async () => { + const files = [ + [".gitignore", "abc"], + "a.txt", + "abc", + "xyz/", + ["xyz/.gitignore", "xyz"], + "xyz/b.txt", + "xyz/c/", + "xyz/c/d.py", + "xyz/xyz", + ]; + addToTestDir(files); + await expectPaths(["a.txt", "xyz/b.txt", "xyz/c/d.py"], ["abc", "xyz/xyz"]); + }); + test("should handle complex patterns in .gitignore", async () => { const files = [ [".gitignore", "*.what\n!important.what\ntemp/\n/root_only.txt"], diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 014753daf..eeeb064d0 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -29,7 +29,12 @@ type WalkableEntry = { // helper struct used for the DFS walk type WalkContext = { walkableEntry: WalkableEntry; + ignoreContexts: IgnoreContext[]; +}; + +type IgnoreContext = { ignore: Ignore; + dirname: string; }; class DFSWalker { @@ -51,30 +56,22 @@ class DFSWalker { this.options.returnRelativePaths ? "" : this.path, this.ide, ); - const root: WalkContext = { - walkableEntry: { - relPath: "", - absPath: this.path, - type: 2 as FileType.Directory, - entry: ["", 2 as FileType.Directory], - }, - ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), - }; + const root = this.newRootWalkContext(); const stack = [root]; for (let cur = stack.pop(); cur; cur = stack.pop()) { const walkableEntries = await this.listDirForWalking(cur.walkableEntry); - const ignore = await this.getIgnoreToApplyInDir( - cur.ignore, + const ignoreContexts = await this.getIgnoreToApplyInDir( + cur, walkableEntries, ); for (const w of walkableEntries) { - if (!this.shouldInclude(w, ignore)) { + if (!this.shouldInclude(w, ignoreContexts)) { continue; } if (this.entryIsDirectory(w.entry)) { stack.push({ walkableEntry: w, - ignore: ignore, + ignoreContexts: ignoreContexts, }); if (this.options.onlyDirs) { // when onlyDirs is enabled the walker will only return directory names @@ -87,6 +84,23 @@ class DFSWalker { } } + private newRootWalkContext(): WalkContext { + return { + walkableEntry: { + relPath: "", + absPath: this.path, + type: 2 as FileType.Directory, + entry: ["", 2 as FileType.Directory], + }, + ignoreContexts: [ + { + ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), + dirname: "", + }, + ], + }; + } + private async listDirForWalking( walkableEntry: WalkableEntry, ): Promise { @@ -102,15 +116,22 @@ class DFSWalker { } private async getIgnoreToApplyInDir( - parentIgnore: Ignore, - walkableEntries: WalkableEntry[], - ): Promise { - const ignoreFilesInDir = await this.loadIgnoreFiles(walkableEntries); + curDir: WalkContext, + entriesInDir: WalkableEntry[], + ): Promise { + const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir); if (ignoreFilesInDir.length === 0) { - return parentIgnore; + return curDir.ignoreContexts; } const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat(); - return ignore().add(parentIgnore).add(patterns); + const newIgnoreContext = { + ignore: ignore().add(patterns), + dirname: curDir.walkableEntry.relPath, + }; + return [ + ...curDir.ignoreContexts, + newIgnoreContext + ]; } private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { @@ -126,7 +147,7 @@ class DFSWalker { return this.ignoreFileNames.has(p); } - private shouldInclude(walkableEntry: WalkableEntry, ignore: Ignore) { + private shouldInclude(walkableEntry: WalkableEntry, ignoreContexts: IgnoreContext[]) { if (this.entryIsSymlink(walkableEntry.entry)) { // If called from the root, a symlink either links to a real file in this repository, // and therefore will be walked OR it linksto something outside of the repository and @@ -141,7 +162,17 @@ class DFSWalker { return false; } } - return !ignore.ignores(relPath); + for (const ig of ignoreContexts) { + // remove the directory name and path seperator from the match path, unless this an ignore file + // in the root directory + const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; + // The ignore library expects a path relative to the ignore file location + const matchPath = relPath.substring(prefixLength); + if (ig.ignore.ignores(matchPath)) { + return false; + } + } + return true; } private entryIsDirectory(entry: Entry) { diff --git a/core/jest.global-setup.ts b/core/jest.global-setup.ts index cf374a702..ee9cddde4 100644 --- a/core/jest.global-setup.ts +++ b/core/jest.global-setup.ts @@ -1,9 +1,5 @@ -import fs from "fs"; import path from "path"; export default async function () { process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test"); - if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) { - fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true }); - } } diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts index d4b86824a..a4c024332 100644 --- a/core/jest.setup-after-env.ts +++ b/core/jest.setup-after-env.ts @@ -1,7 +1,7 @@ // https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055 -import { TextEncoder, TextDecoder } from "util"; -import fetch, { Request, Response } from "node-fetch"; import { jest } from "@jest/globals"; +import fetch, { Request, Response } from "node-fetch"; +import { TextDecoder, TextEncoder } from "util"; if (process.env.DEBUG === "jest") { jest.setTimeout(5 * 60 * 1000); @@ -14,3 +14,18 @@ globalThis.Request = Request; globalThis.Response = Response; globalThis.TextEncoder = TextEncoder; globalThis.TextDecoder = TextDecoder; + +// Trying to delete this when for some reason SQLite is still in use causes tests to fail +// globalThis.beforeAll(() => { +// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` +// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { +// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); +// } +// }); + +// globalThis.afterAll(() => { +// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` +// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { +// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); +// } +// }); diff --git a/core/llm/asyncEncoder.test.ts b/core/llm/asyncEncoder.test.ts new file mode 100644 index 000000000..9ed5eb80a --- /dev/null +++ b/core/llm/asyncEncoder.test.ts @@ -0,0 +1,45 @@ +import { LlamaAsyncEncoder, GPTAsyncEncoder } from "./asyncEncoder"; + +describe("llama encoder", () => { + var tokenizer: LlamaAsyncEncoder; + + beforeAll(() => { + tokenizer = new LlamaAsyncEncoder(); + }); + + afterAll(() => { + tokenizer.close(); + }); + + test("hello world", async () => { + const input = "the quick brown fox jumped over the lazy dog"; + const output = await tokenizer.encode(input); + expect(output).toEqual([ + 1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203, + ]); + const decoded = await tokenizer.decode(output); + expect(decoded).toBe(input); + }); +}); + +describe("tiktoken encoder", () => { + var tokenizer: GPTAsyncEncoder; + + beforeAll(() => { + tokenizer = new GPTAsyncEncoder(); + }); + + afterAll(() => { + tokenizer.close(); + }); + + test("hello world", async () => { + const input = "the quick brown fox jumped over the lazy dog"; + const output = await tokenizer.encode(input); + expect(output).toEqual([ + 1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679, + ]); + const decoded = await tokenizer.decode(output); + expect(decoded).toBe(input); + }); +}); diff --git a/core/llm/asyncEncoder.ts b/core/llm/asyncEncoder.ts index ed6425df2..5fd39eed6 100644 --- a/core/llm/asyncEncoder.ts +++ b/core/llm/asyncEncoder.ts @@ -1,7 +1,5 @@ -import llamaTokenizer from "./llamaTokenizer.js"; -import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; +import path from "path"; import workerpool from "workerpool"; -import * as path from "path"; export interface AsyncEncoder { encode(text: string): Promise; @@ -13,7 +11,9 @@ export class LlamaAsyncEncoder implements AsyncEncoder { private workerPool: workerpool.Pool; constructor() { - this.workerPool = workerpool.pool(workerCodeFilePath("llamaTokenizerWorkerPool.mjs")); + this.workerPool = workerpool.pool( + workerCodeFilePath("llamaTokenizerWorkerPool.mjs"), + ); } async encode(text: string): Promise { @@ -35,7 +35,9 @@ export class GPTAsyncEncoder implements AsyncEncoder { private workerPool: workerpool.Pool; constructor() { - this.workerPool = workerpool.pool(workerCodeFilePath("tiktokenWorkerPool.mjs")); + this.workerPool = workerpool.pool( + workerCodeFilePath("tiktokenWorkerPool.mjs"), + ); } async encode(text: string): Promise { @@ -58,4 +60,4 @@ function workerCodeFilePath(workerFileName: string): string { return path.join(__dirname, "llm", workerFileName); } return path.join(__dirname, workerFileName); -} \ No newline at end of file +} diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index e1d184b80..1696bd674 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -80,7 +80,7 @@ function modelSupportsImages( title: string | undefined, capabilities: ModelCapability | undefined ): boolean { - if (capabilities?.uploadImage !== undefined) return capabilities.uploadImage + if (capabilities?.uploadImage !== undefined) {return capabilities.uploadImage;} if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) { return false; } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 5d042e3ca..06cd4a3bb 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -24,18 +24,37 @@ class LlamaEncoding implements Encoding { } } +class NonWorkerAsyncEncoder implements AsyncEncoder { + constructor(private readonly encoding: Encoding) {} + + async close(): Promise {} + + async encode(text: string): Promise { + return this.encoding.encode(text); + } + + async decode(tokens: number[]): Promise { + return this.encoding.decode(tokens); + } +} + let gptEncoding: Encoding | null = null; const gptAsyncEncoder = new GPTAsyncEncoder(); const llamaEncoding = new LlamaEncoding(); const llamaAsyncEncoder = new LlamaAsyncEncoder(); function asyncEncoderForModel(modelName: string): AsyncEncoder { + // Temporary due to issues packaging the worker files + if (process.env.IS_BINARY) { + const encoding = encodingForModel(modelName); + return new NonWorkerAsyncEncoder(encoding); + } + const modelType = autodetectTemplateType(modelName); if (!modelType || modelType === "none") { return gptAsyncEncoder; } - // Temporary due to issues packaging the worker files - return process.env.IS_BINARY ? gptAsyncEncoder : llamaAsyncEncoder; + return llamaAsyncEncoder; } function encodingForModel(modelName: string): Encoding { diff --git a/core/test/baseLLM.test.ts b/core/llm/index.test.ts similarity index 97% rename from core/test/baseLLM.test.ts rename to core/llm/index.test.ts index b49c9ac39..926b61209 100644 --- a/core/test/baseLLM.test.ts +++ b/core/llm/index.test.ts @@ -1,5 +1,5 @@ -import { ChatMessage, LLMOptions, ModelProvider } from "../index.js"; -import { BaseLLM } from "../llm/index.js"; +import { ChatMessage, LLMOptions, ModelProvider } from ".."; +import { BaseLLM } from "."; class DummyLLM extends BaseLLM { static providerName: ModelProvider = "openai"; diff --git a/core/llm/index.ts b/core/llm/index.ts index ca3c032a6..a6c30ed5a 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -91,6 +91,7 @@ export abstract class BaseLLM implements ILLM { title?: string; systemMessage?: string; contextLength: number; + maxStopWords?: number | undefined; completionOptions: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; @@ -110,15 +111,12 @@ export abstract class BaseLLM implements ILLM { accountId?: string; aiGatewaySlug?: string; - // For WatsonX only. - + // For IBM watsonx only. watsonxUrl?: string; - watsonxApiKey?: string; - watsonxZenApiKeyBase64?: string = "YOUR_WATSONX_ZENAPIKEY"; // Required if using watsonx software with ZenApiKey auth - watsonxUsername?: string; - watsonxPassword?: string; + watsonxCreds?: string; watsonxProjectId?: string; watsonxStopToken?: string; + watsonxApiVersion?: string; private _llmOptions: LLMOptions; @@ -143,6 +141,7 @@ export abstract class BaseLLM implements ILLM { this.systemMessage = options.systemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; + this.maxStopWords = options.maxStopWords ?? this.maxStopWords; this.completionOptions = { ...options.completionOptions, model: options.model || "gpt-4", @@ -171,13 +170,13 @@ export abstract class BaseLLM implements ILLM { this.apiKey = options.apiKey; this.aiGatewaySlug = options.aiGatewaySlug; this.apiBase = options.apiBase; + // for watsonx only this.watsonxUrl = options.watsonxUrl; - this.watsonxApiKey = options.watsonxApiKey; + this.watsonxCreds = options.watsonxCreds; this.watsonxProjectId = options.watsonxProjectId; - this.watsonxUsername = options.watsonxUsername; - this.watsonxPassword = options.watsonxPassword; this.watsonxStopToken = options.watsonxStopToken; + this.watsonxApiVersion = options.watsonxApiVersion; if (this.apiBase && !this.apiBase.endsWith("/")) { this.apiBase = `${this.apiBase}/`; diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 226671c52..415ec0f10 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,19 +14,24 @@ import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; class Bedrock extends BaseLLM { - private static PROFILE_NAME: string = "bedrock"; static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { region: "us-east-1", model: "anthropic.claude-3-sonnet-20240229-v1:0", - contextLength: 200_000, + contextLength: 200_000 }; + profile?: string | undefined; constructor(options: LLMOptions) { super(options); if (!options.apiBase) { this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; } + if (options.profile) { + this.profile = options.profile; + } else { + this.profile = "bedrock"; + } } protected async *_streamComplete( @@ -124,11 +129,11 @@ class Bedrock extends BaseLLM { private async _getCredentials() { try { return await fromIni({ - profile: Bedrock.PROFILE_NAME, + profile: this.profile, })(); } catch (e) { console.warn( - `AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`, + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, ); return await fromIni()(); } diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts new file mode 100644 index 000000000..f53d4b15e --- /dev/null +++ b/core/llm/llms/BedrockImport.ts @@ -0,0 +1,96 @@ +import { + BedrockRuntimeClient, + InvokeModelWithResponseStreamCommand, +} from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import { + CompletionOptions, + LLMOptions, + ModelProvider, +} from "../../index.js"; +import { BaseLLM } from "../index.js"; + +class BedrockImport extends BaseLLM { + static providerName: ModelProvider = "bedrockimport"; + static defaultOptions: Partial = { + region: "us-east-1" + }; + // the BedRock imported custom model ARN + modelArn?: string | undefined; + profile?: string | undefined; + + constructor(options: LLMOptions) { + super(options); + if (!options.apiBase) { + this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; + } + if (options.modelArn) { + this.modelArn = options.modelArn; + } + if (options.profile) { + this.profile = options.profile; + } else { + this.profile = "bedrock"; + } + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions, + ): AsyncGenerator { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.region, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + + const input = this._generateInvokeModelCommandInput(prompt, options); + const command = new InvokeModelWithResponseStreamCommand(input); + const response = await client.send(command); + + if (response.body) { + for await (const item of response.body) { + const chunk = JSON.parse(new TextDecoder().decode(item.chunk?.bytes)); + if (chunk.outputs[0].text) { + yield chunk.outputs[0].text; + } + } + } + } + + private _generateInvokeModelCommandInput( + prompt: string, + options: CompletionOptions, + ): any { + const payload = { + prompt: prompt + }; + + return { + body: JSON.stringify(payload), + modelId: this.modelArn, + accept: "application/json", + contentType: "application/json" + }; + } + + private async _getCredentials() { + try { + return await + fromIni({ + profile: this.profile + })(); + } catch (e) { + console.warn( + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} + +export default BedrockImport; diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index e8342b546..105a2e20c 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -13,7 +13,7 @@ class Deepseek extends OpenAI { }, useLegacyCompletionsEndpoint: false, }; - protected maxStopWords: number | undefined = 16; + maxStopWords: number | undefined = 16; supportsFim(): boolean { return true; diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index e4c1674e6..10632b90f 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -2,7 +2,6 @@ import { TRIAL_FIM_MODEL } from "../../config/onboarding.js"; import { getHeaders } from "../../continueServer/stubs/headers.js"; import { constants } from "../../deploy/constants.js"; import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; -import { Telemetry } from "../../util/posthog.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -29,18 +28,19 @@ class FreeTrial extends BaseLLM { } private async _countTokens(prompt: string, model: string, isPrompt: boolean) { - if (!Telemetry.client) { - throw new Error( - 'In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set "allowAnonymousTelemetry": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.', - ); - } - const event = isPrompt - ? "free_trial_prompt_tokens" - : "free_trial_completion_tokens"; - Telemetry.capture(event, { - tokens: this.countTokens(prompt), - model, - }); + // Removed to reduce PostHog bill + // if (!Telemetry.client) { + // throw new Error( + // "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.", + // ); + // } + // const event = isPrompt + // ? "free_trial_prompt_tokens" + // : "free_trial_completion_tokens"; + // Telemetry.capture(event, { + // tokens: this.countTokens(prompt), + // model, + // }); } private _convertArgs(options: CompletionOptions): any { diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts index 27c51e1e3..7115bcc32 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -6,7 +6,7 @@ class Groq extends OpenAI { static defaultOptions: Partial = { apiBase: "https://api.groq.com/openai/v1/", }; - protected maxStopWords: number | undefined = 4; + maxStopWords: number | undefined = 4; private static modelConversion: { [key: string]: string } = { "llama2-70b": "llama2-70b-4096", diff --git a/core/llm/llms/Kindo.ts b/core/llm/llms/Kindo.ts new file mode 100644 index 000000000..855e386de --- /dev/null +++ b/core/llm/llms/Kindo.ts @@ -0,0 +1,16 @@ +import { LLMOptions, ModelProvider } from "../.."; +import OpenAI from "./OpenAI"; + +class Kindo extends OpenAI { + static providerName: ModelProvider = "kindo"; + static defaultOptions: Partial = { + apiBase: "https://llm.kindo.ai/v1", + requestOptions: { + headers: { + "kindo-token-transaction-type": "CONTINUE" + } + } + }; +} + +export default Kindo; \ No newline at end of file diff --git a/core/llm/llms/Mistral.ts b/core/llm/llms/Mistral.ts index 95208bb8c..992e650c7 100644 --- a/core/llm/llms/Mistral.ts +++ b/core/llm/llms/Mistral.ts @@ -20,6 +20,10 @@ class Mistral extends OpenAI { ) { this.apiBase = options.apiBase ?? "https://codestral.mistral.ai/v1/"; } + + if (!this.apiBase?.endsWith("/")) { + this.apiBase += "/"; + } } private static modelConversion: { [key: string]: string } = { diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index fe5ab7f55..f830b7f0f 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -50,7 +50,8 @@ class Ollama extends BaseLLM { let value = parts[2]; switch (key) { case "num_ctx": - this.contextLength = Number.parseInt(value); + this.contextLength = + options.contextLength ?? Number.parseInt(value); break; case "stop": if (!this.completionOptions.stop) { @@ -60,7 +61,7 @@ class Ollama extends BaseLLM { this.completionOptions.stop.push(JSON.parse(value)); } catch (e) { console.warn( - 'Error parsing stop parameter value "{value}: ${e}', + "Error parsing stop parameter value \"{value}: ${e}", ); } break; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index cea8ec524..4a7477102 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -42,7 +42,7 @@ const CHAT_ONLY_MODELS = [ class OpenAI extends BaseLLM { public useLegacyCompletionsEndpoint: boolean | undefined = undefined; - protected maxStopWords: number | undefined = undefined; + maxStopWords: number | undefined = undefined; constructor(options: LLMOptions) { super(options); @@ -104,13 +104,13 @@ class OpenAI extends BaseLLM { this.maxStopWords !== undefined ? options.stop?.slice(0, this.maxStopWords) : url.host === "api.deepseek.com" - ? options.stop?.slice(0, 16) - : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" - ? options.stop?.slice(0, 4) - : options.stop, + ? options.stop?.slice(0, 16) + : url.port === "1337" || + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" + ? options.stop?.slice(0, 4) + : options.stop, }; return finalOptions; diff --git a/core/llm/llms/OpenRouter.ts b/core/llm/llms/OpenRouter.ts new file mode 100644 index 000000000..d01a19ec5 --- /dev/null +++ b/core/llm/llms/OpenRouter.ts @@ -0,0 +1,17 @@ +import { LLMOptions, ModelProvider } from "../../index.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; +import OpenAI from "./OpenAI.js"; + +class OpenRouter extends OpenAI { + static providerName: ModelProvider = "openrouter"; + static defaultOptions: Partial = { + apiBase: "https://openrouter.ai/api/v1/", + model: "gpt-4o-mini", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; +} + +export default OpenRouter; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index 6a5890e67..a59de352c 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -55,7 +55,7 @@ class SageMaker extends BaseLLM { let position; while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); - const data = JSON.parse(line.replace(/^data:/, '')); + const data = JSON.parse(line.replace(/^data:/, "")); if ("choices" in data) { yield data.choices[0].delta.content; } @@ -94,7 +94,7 @@ class SageMaker extends BaseLLM { let position; while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); - const data = JSON.parse(line.replace(/^data:/, '')); + const data = JSON.parse(line.replace(/^data:/, "")); if ("choices" in data) { yield { role: "assistant", content: data.choices[0].delta.content }; } @@ -143,7 +143,7 @@ class MessageAPIToolkit implements SageMakerModelToolkit { let prompt = jinja.compile(this.sagemaker.completionOptions.chat_template).render( { messages: messages, add_generation_prompt: true }, { autoEscape: false } - ) + ); const payload = { inputs: prompt, parameters: this.sagemaker.completionOptions, diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 747a10c6a..68dfef47c 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -6,6 +6,7 @@ import { } from "../../index.js"; import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; +import { streamResponse } from "../stream.js"; const watsonxConfig = { accessToken: { expiration: 0, @@ -13,17 +14,20 @@ const watsonxConfig = { }, }; class WatsonX extends BaseLLM { - protected maxStopWords: number | undefined = undefined; + maxStopWords: number | undefined = undefined; constructor(options: LLMOptions) { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { - if (this.watsonxUrl != null && this.watsonxUrl.includes("cloud.ibm.com")) { + + if ( + this.watsonxUrl?.includes("cloud.ibm.com") + ) { // watsonx SaaS const wxToken = await ( await fetch( - `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxApiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, + `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxCreds}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, { method: "POST", headers: { @@ -40,17 +44,16 @@ class WatsonX extends BaseLLM { } else { // watsonx Software if ( - this.watsonxZenApiKeyBase64 && - this.watsonxZenApiKeyBase64 !== "YOUR_WATSONX_ZENAPIKEY" + !this.watsonxCreds?.includes(":") ) { - // Using ZenApiKey auth - return { - token: this.watsonxZenApiKeyBase64, - expiration: -1, - }; + // Using ZenApiKey auth + return { + token: this.watsonxCreds ?? "", + expiration: -1, + }; } else { // Using username/password auth - + const userPass = this.watsonxCreds?.split(":"); const wxToken = await ( await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, { method: "POST", @@ -59,8 +62,8 @@ class WatsonX extends BaseLLM { Accept: "application/json", }, body: JSON.stringify({ - username: this.watsonxUsername, - password: this.watsonxPassword, + username: userPass[0], + password: userPass[1], }), }) ).json(); @@ -125,7 +128,9 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"} ${watsonxConfig.accessToken.token}`, + Authorization: `${ + watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxConfig.accessToken.token}`, }; } @@ -169,21 +174,27 @@ class WatsonX extends BaseLLM { watsonxConfig.accessToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60} mins)`, + `Reusing token (expires in ${ + (watsonxConfig.accessToken.expiration - now) / 60 + } mins)`, ); } if (watsonxConfig.accessToken.token === undefined) { - throw new Error(`Something went wrong. Check your credentials, please.`); + throw new Error("Something went wrong. Check your credentials, please."); } - const stopToken = this.watsonxStopToken ?? (options.model.includes("granite") ? "<|im_end|>" : undefined); - var streamResponse = await fetch( - `${this.watsonxUrl}/ml/v1/text/generation_stream?version=2023-05-29`, + const stopToken = + this.watsonxStopToken ?? + (options.model?.includes("granite") ? "<|im_end|>" : undefined); + var response = await this.fetch( + `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`, { method: "POST", headers: { "Content-Type": "application/json", - Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"} ${watsonxConfig.accessToken.token}`, + Authorization: `${ + watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxConfig.accessToken.token}`, }, body: JSON.stringify({ input: messages[messages.length - 1].content, @@ -196,30 +207,22 @@ class WatsonX extends BaseLLM { repetition_penalty: 1, }, model_id: options.model, - project_id: this.watsonxProjectId, + project_id: this.watsonxProjectId }), }, ); - if (!streamResponse.ok || streamResponse.body === null) { + if (!response.ok || response.body === null) { throw new Error( "Something went wrong. No response received, check your connection", ); } else { - const reader = streamResponse.body.getReader(); - while (true) { - const chunk = await reader.read(); - if (chunk.done) { - break; - } - - // Decode the stream - const textResponseMsg = new TextDecoder().decode(chunk.value); - const lines = textResponseMsg.split(/\r?\n/); + for await (const value of streamResponse(response)) { + const lines = value.split("\n"); let generatedChunk = ""; let generatedTextIndex = undefined; - lines.forEach((el) => { + lines.forEach((el: string) => { // console.log(`${el}`); if (el.startsWith("id:")) { generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index cd084207e..84c23c9bb 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -11,6 +11,7 @@ import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Azure from "./Azure"; import Bedrock from "./Bedrock"; +import BedrockImport from "./BedrockImport"; import Cloudflare from "./Cloudflare"; import Cohere from "./Cohere"; import DeepInfra from "./DeepInfra"; @@ -22,6 +23,7 @@ import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; import HuggingFaceTGI from "./HuggingFaceTGI"; +import Kindo from "./Kindo"; import LMStudio from "./LMStudio"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; @@ -29,6 +31,7 @@ import Mistral from "./Mistral"; import Msty from "./Msty"; import Ollama from "./Ollama"; import OpenAI from "./OpenAI"; +import OpenRouter from "./OpenRouter"; import Replicate from "./Replicate"; import SageMaker from "./SageMaker"; import TextGenWebUI from "./TextGenWebUI"; @@ -48,11 +51,13 @@ const LLMs = [ Together, HuggingFaceTGI, HuggingFaceInferenceAPI, + Kindo, LlamaCpp, OpenAI, LMStudio, Mistral, Bedrock, + BedrockImport, SageMaker, DeepInfra, Flowise, @@ -64,6 +69,7 @@ const LLMs = [ Msty, Azure, WatsonX, + OpenRouter, ]; export async function llmFromDescription( diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index fd288a48e..00a05ac72 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -74,7 +74,7 @@ const osModelsEditPrompt: PromptTemplate = (history, otherData) => { !firstCharOfFirstLine; const suffixTag = isSuffix ? "" : ""; const suffixExplanation = isSuffix - ? ' When you get to "", end your response.' + ? " When you get to \"\", end your response." : ""; // If neither prefilling nor /v1/completions are supported, we have to use a chat prompt without putting words in the model's mouth diff --git a/core/package-lock.json b/core/package-lock.json index 28570648f..133599374 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -22,14 +22,16 @@ "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", + "fingerprint-generator": "^2.1.54", "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "header-generator": "^2.1.54", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "ignore": "^5.3.1", @@ -44,8 +46,11 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", + "puppeteer": "^22.4.0", + "puppeteer-chromium-resolver": "^23.0.0", "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", @@ -1225,7 +1230,6 @@ "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", - "dev": true, "dependencies": { "@babel/highlight": "^7.24.7", "picocolors": "^1.0.0" @@ -1609,7 +1613,6 @@ "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", - "dev": true, "engines": { "node": ">=6.9.0" } @@ -1656,7 +1659,6 @@ "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", - "dev": true, "dependencies": { "@babel/helper-validator-identifier": "^7.24.7", "chalk": "^2.4.2", @@ -1671,7 +1673,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, "dependencies": { "color-convert": "^1.9.0" }, @@ -1683,7 +1684,6 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -1697,7 +1697,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, "dependencies": { "color-name": "1.1.3" } @@ -1705,14 +1704,12 @@ "node_modules/@babel/highlight/node_modules/color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" }, "node_modules/@babel/highlight/node_modules/escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, "engines": { "node": ">=0.8.0" } @@ -1721,7 +1718,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, "engines": { "node": ">=4" } @@ -1730,7 +1726,6 @@ "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, "dependencies": { "has-flag": "^3.0.0" }, @@ -3740,6 +3735,18 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@lancedb/vectordb-darwin-arm64": { + "version": "0.4.20", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.20.tgz", + "integrity": "sha512-ffP2K4sA5mQTgePyARw1y8dPN996FmpvyAYoWO+TSItaXlhcXvc+KVa5udNMCZMDYeEnEv2Xpj6k4PwW3oBz+A==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, "node_modules/@lancedb/vectordb-darwin-x64": { "version": "0.4.20", "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.20.tgz", @@ -3752,6 +3759,42 @@ "darwin" ] }, + "node_modules/@lancedb/vectordb-linux-arm64-gnu": { + "version": "0.4.20", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.20.tgz", + "integrity": "sha512-FpNOjOsz3nJVm6EBGyNgbOW2aFhsWZ/igeY45Z8hbZaaK2YBwrg/DASoNlUzgv6IR8cUaGJ2irNVJfsKR2cG6g==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-linux-x64-gnu": { + "version": "0.4.20", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.20.tgz", + "integrity": "sha512-pOqWjrRZQSrLTlQPkjidRii7NZDw8Xu9pN6ouVu2JAK8n81FXaPtFCyAI+Y3v9GpnYDN0rvD4eQ36aHAVPsa2g==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-win32-x64-msvc": { + "version": "0.4.20", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.20.tgz", + "integrity": "sha512-5J5SsYSJ7jRCmU/sgwVHdrGz43B/7R2T9OEoFTKyVAtqTZdu75rkytXyn9SyEayXVhlUOaw76N0ASm0hAoDS/A==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@mozilla/readability": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.5.0.tgz", @@ -4018,6 +4061,27 @@ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==" }, + "node_modules/@puppeteer/browsers": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.3.0.tgz", + "integrity": "sha512-ioXoq9gPxkss4MYhD+SFaU9p1IHFUX0ILAWFPyjGaBdjLsYAlZw6j1iLA0N/m12uVHLFDfSYNF7EQccjinIMDA==", + "dependencies": { + "debug": "^4.3.5", + "extract-zip": "^2.0.1", + "progress": "^2.0.3", + "proxy-agent": "^6.4.0", + "semver": "^7.6.3", + "tar-fs": "^3.0.6", + "unbzip2-stream": "^1.4.3", + "yargs": "^17.7.2" + }, + "bin": { + "browsers": "lib/cjs/main-cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -4630,6 +4694,11 @@ "node": ">= 6" } }, + "node_modules/@tootallnate/quickjs-emscripten": { + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz", + "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==" + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -4955,6 +5024,15 @@ "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", "dev": true }, + "node_modules/@types/yauzl": { + "version": "2.10.3", + "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz", + "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==", + "optional": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "7.10.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.10.0.tgz", @@ -5228,6 +5306,14 @@ "eslint-config-nodebb": "0.1.1" } }, + "node_modules/adm-zip": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.15.tgz", + "integrity": "sha512-jYPWSeOA8EFoZnucrKCNihqBjoEGQSU4HKgHYQgKNEQ0pQF9a/DYuo/+fAxY76k4qe75LUlLWpAM1QWcBMTOKw==", + "engines": { + "node": ">=12.0" + } + }, "node_modules/agent-base": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", @@ -5364,8 +5450,7 @@ "node_modules/aproba": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", - "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", - "optional": true + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" }, "node_modules/are-we-there-yet": { "version": "3.0.1", @@ -5546,6 +5631,17 @@ "node": ">=0.8" } }, + "node_modules/ast-types": { + "version": "0.13.4", + "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", + "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", + "dependencies": { + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/async-mutex": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz", @@ -5830,6 +5926,14 @@ } ] }, + "node_modules/basic-ftp": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", + "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", @@ -5930,7 +6034,6 @@ "version": "4.23.0", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz", "integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==", - "dev": true, "funding": [ { "type": "opencollective", @@ -6003,6 +6106,14 @@ "ieee754": "^1.2.1" } }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "engines": { + "node": "*" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -6095,7 +6206,6 @@ "version": "1.0.30001620", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001620.tgz", "integrity": "sha512-WJvYsOjd1/BYUY6SNGUosK9DUidBPDTnOARHp3fSmFO1ekdxaY6nKRttEVrfMmYi80ctS0kz1wiWmm14fVc3ew==", - "dev": true, "funding": [ { "type": "opencollective", @@ -6155,42 +6265,6 @@ "node": ">=10" } }, - "node_modules/cheerio": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.12.tgz", - "integrity": "sha512-VqR8m68vM46BNnuZ5NtnGBKIE/DfN0cRIzg9n40EIq9NOv90ayxLBXA8fXC5gquFRGJSTRqBq25Jt2ECLR431Q==", - "dependencies": { - "cheerio-select": "^2.1.0", - "dom-serializer": "^2.0.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "htmlparser2": "^8.0.1", - "parse5": "^7.0.0", - "parse5-htmlparser2-tree-adapter": "^7.0.0" - }, - "engines": { - "node": ">= 6" - }, - "funding": { - "url": "https://github.com/cheeriojs/cheerio?sponsor=1" - } - }, - "node_modules/cheerio-select": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", - "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", - "dependencies": { - "boolbase": "^1.0.0", - "css-select": "^5.1.0", - "css-what": "^6.1.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/fb55" - } - }, "node_modules/chownr": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", @@ -6199,6 +6273,19 @@ "node": ">=10" } }, + "node_modules/chromium-bidi": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.6.3.tgz", + "integrity": "sha512-qXlsCmpCZJAnoTYI83Iu6EdYQpMYdVkCfq08KDh2pmlVqK5t5IA9mGs4/LwCwp4fqisSOMXZxP3HIh8w8aRn0A==", + "dependencies": { + "mitt": "3.0.1", + "urlpattern-polyfill": "10.0.0", + "zod": "3.23.8" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, "node_modules/ci-info": { "version": "3.9.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", @@ -6233,7 +6320,6 @@ "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", @@ -6300,7 +6386,6 @@ "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", - "optional": true, "bin": { "color-support": "bin.js" } @@ -6405,8 +6490,7 @@ "node_modules/console-control-strings": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", - "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", - "optional": true + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" }, "node_modules/convert-source-map": { "version": "2.0.0", @@ -6432,6 +6516,31 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" }, + "node_modules/cosmiconfig": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", + "integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==", + "dependencies": { + "env-paths": "^2.2.1", + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, "node_modules/create-jest": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", @@ -6617,9 +6726,9 @@ } }, "node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz", + "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==", "dependencies": { "ms": "2.1.2" }, @@ -6719,6 +6828,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/degenerator": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", + "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", + "dependencies": { + "ast-types": "^0.13.4", + "escodegen": "^2.1.0", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -6763,6 +6885,11 @@ "node": ">=8" } }, + "node_modules/devtools-protocol": { + "version": "0.0.1312386", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1312386.tgz", + "integrity": "sha512-DPnhUXvmvKT2dFA/j7B+riVLUt9Q6RKJlcppojL5CoRywJJKLDYnRlw0gTFKfgDPHP5E04UoB71SxoJlVZy8FA==" + }, "node_modules/diff-sequences": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", @@ -6858,6 +6985,20 @@ "url": "https://github.com/fb55/domutils?sponsor=1" } }, + "node_modules/dot-prop": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-6.0.1.tgz", + "integrity": "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/dotenv": { "version": "16.4.5", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", @@ -6883,11 +7024,15 @@ "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==" }, + "node_modules/eight-colors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eight-colors/-/eight-colors-1.3.0.tgz", + "integrity": "sha512-hVoK898cR71ADj7L1LZWaECLaSkzzPtqGXIaKv4K6Pzb72QgjLVsQaNI+ELDQQshzFvgp5xTPkaYkPGqw3YR+g==" + }, "node_modules/electron-to-chromium": { "version": "1.4.776", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.776.tgz", - "integrity": "sha512-s694bi3+gUzlliqxjPHpa9NRTlhzTgB34aan+pVKZmOTGy2xoZXl+8E1B8i5p5rtev3PKMK/H4asgNejC+YHNg==", - "dev": true + "integrity": "sha512-s694bi3+gUzlliqxjPHpa9NRTlhzTgB34aan+pVKZmOTGy2xoZXl+8E1B8i5p5rtev3PKMK/H4asgNejC+YHNg==" }, "node_modules/emittery": { "version": "0.13.1", @@ -6904,8 +7049,7 @@ "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "devOptional": true + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, "node_modules/encoding": { "version": "0.1.13", @@ -6979,7 +7123,6 @@ "version": "2.2.1", "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", - "optional": true, "engines": { "node": ">=6" } @@ -6994,7 +7137,6 @@ "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, "dependencies": { "is-arrayish": "^0.2.1" } @@ -7166,7 +7308,6 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", - "dev": true, "engines": { "node": ">=6" } @@ -7186,7 +7327,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", - "dev": true, "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", @@ -7603,6 +7743,39 @@ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" }, + "node_modules/extract-zip": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", + "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==", + "dependencies": { + "debug": "^4.1.1", + "get-stream": "^5.1.0", + "yauzl": "^2.10.0" + }, + "bin": { + "extract-zip": "cli.js" + }, + "engines": { + "node": ">= 10.17.0" + }, + "optionalDependencies": { + "@types/yauzl": "^2.9.1" + } + }, + "node_modules/extract-zip/node_modules/get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", @@ -7703,6 +7876,14 @@ "bser": "2.1.1" } }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "dependencies": { + "pend": "~1.2.0" + } + }, "node_modules/fetch-blob": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", @@ -7779,6 +7960,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/fingerprint-generator": { + "version": "2.1.54", + "resolved": "https://registry.npmjs.org/fingerprint-generator/-/fingerprint-generator-2.1.54.tgz", + "integrity": "sha512-Hd/t8h+icv9jeDd64hxTyfuP9U0bkq9z9Lna4q/MeIs2e1mTcHuznyJzApqtYdZP3cIY4JEfmDz5yW/QcMz+Ow==", + "dependencies": { + "generative-bayesian-network": "^2.1.54", + "header-generator": "^2.1.54", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/flat-cache": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", @@ -7892,6 +8086,27 @@ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" }, + "node_modules/fs-extra": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", + "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fs-extra/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/fs-minipass": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", @@ -7983,6 +8198,15 @@ "is-property": "^1.0.2" } }, + "node_modules/generative-bayesian-network": { + "version": "2.1.54", + "resolved": "https://registry.npmjs.org/generative-bayesian-network/-/generative-bayesian-network-2.1.54.tgz", + "integrity": "sha512-1RIfmYqZqghwjRQGqUU36tZmJkyz77dztmgUHeAGkG0o9eTwN7fBxOCyQLqxZd9Qg72d19IKdcIvrs53TI2KdA==", + "dependencies": { + "adm-zip": "^0.5.9", + "tslib": "^2.4.0" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -7996,7 +8220,6 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, "engines": { "node": "6.* || 8.* || >= 10.*" } @@ -8056,6 +8279,28 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-uri": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.3.tgz", + "integrity": "sha512-BzUrJBS9EcUb4cFol8r4W3v1cPsSyajLSthNkz5BxbpDcHN5tIrM10E2eNvfnvBn3DaT3DUgx0OpsBKkaOpanw==", + "dependencies": { + "basic-ftp": "^5.0.2", + "data-uri-to-buffer": "^6.0.2", + "debug": "^4.3.4", + "fs-extra": "^11.2.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/get-uri/node_modules/data-uri-to-buffer": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", + "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", + "engines": { + "node": ">= 14" + } + }, "node_modules/getpass": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", @@ -8373,8 +8618,7 @@ "node_modules/has-unicode": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", - "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", - "optional": true + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==" }, "node_modules/hasown": { "version": "2.0.2", @@ -8395,6 +8639,20 @@ "he": "bin/he" } }, + "node_modules/header-generator": { + "version": "2.1.54", + "resolved": "https://registry.npmjs.org/header-generator/-/header-generator-2.1.54.tgz", + "integrity": "sha512-fRitYKX+HwmID0zUeWzsu3wZDa5dTVi7XE/m2kRcP+wZVhVuKHm7zD2jfmxddhVQWgdp0CY4+eTfDOlD5dsBMQ==", + "dependencies": { + "browserslist": "^4.21.1", + "generative-bayesian-network": "^2.1.54", + "ow": "^0.28.1", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/html-encoding-sniffer": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", @@ -8412,24 +8670,6 @@ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, - "node_modules/htmlparser2": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", - "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==", - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "entities": "^4.4.0" - } - }, "node_modules/http-cache-semantics": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", @@ -8622,7 +8862,6 @@ "version": "9.0.5", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz", "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==", - "optional": true, "dependencies": { "jsbn": "1.1.0", "sprintf-js": "^1.1.3" @@ -8649,8 +8888,7 @@ "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==" }, "node_modules/is-bigint": { "version": "1.0.4", @@ -8745,7 +8983,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "devOptional": true, "engines": { "node": ">=8" } @@ -8809,6 +9046,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", + "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", + "engines": { + "node": ">=8" + } + }, "node_modules/is-path-inside": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", @@ -9047,6 +9292,33 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-changed-files/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-changed-files/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-circus": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", @@ -9078,6 +9350,33 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-circus/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-circus/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-cli": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", @@ -9645,6 +9944,33 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-runner/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-runner/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-runtime": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", @@ -9823,8 +10149,7 @@ "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "node_modules/js-yaml": { "version": "4.1.0", @@ -9840,8 +10165,7 @@ "node_modules/jsbn": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz", - "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==", - "optional": true + "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==" }, "node_modules/jsdom": { "version": "24.1.1", @@ -9916,8 +10240,7 @@ "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" }, "node_modules/json-schema": { "version": "0.4.0", @@ -9951,6 +10274,25 @@ "node": ">=6" } }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonfile/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/jsprim": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", @@ -10050,8 +10392,7 @@ "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" }, "node_modules/llm-code-highlighter": { "version": "0.0.14", @@ -10102,6 +10443,11 @@ "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", "dev": true }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==" + }, "node_modules/lodash.memoize": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", @@ -10466,6 +10812,11 @@ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==" + }, "node_modules/mkdirp": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", @@ -10573,6 +10924,14 @@ "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==" }, + "node_modules/netmask": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz", + "integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/node-abi": { "version": "3.62.0", "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.62.0.tgz", @@ -10706,8 +11065,7 @@ "node_modules/node-releases": { "version": "2.0.14", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", - "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", - "dev": true + "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==" }, "node_modules/nopt": { "version": "5.0.0", @@ -11048,7 +11406,64 @@ "node": ">= 0.8.0" } }, + "node_modules/ow": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/ow/-/ow-0.28.2.tgz", + "integrity": "sha512-dD4UpyBh/9m4X2NVjA+73/ZPBRF+uF4zIMFvvQsabMiEK8x41L3rQ8EENOi35kyyoaJwNxEeJcP6Fj1H4U409Q==", + "dependencies": { + "@sindresorhus/is": "^4.2.0", + "callsites": "^3.1.0", + "dot-prop": "^6.0.1", + "lodash.isequal": "^4.5.0", + "vali-date": "^1.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ow/node_modules/@sindresorhus/is": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", + "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, "node_modules/p-limit": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-6.1.0.tgz", + "integrity": "sha512-H0jc0q1vOzlEk0TqAKXKZxdl7kX3OFUzCnNVUnq5Pc3DGo0kpeaMuPqxQn235HibwBEb0/pm9dgKTjXy66fBkg==", + "dependencies": { + "yocto-queue": "^1.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate/node_modules/p-limit": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", @@ -11062,13 +11477,10 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dependencies": { - "p-limit": "^3.0.2" - }, + "node_modules/p-locate/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "engines": { "node": ">=10" }, @@ -11100,6 +11512,49 @@ "node": ">=6" } }, + "node_modules/pac-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.0.2.tgz", + "integrity": "sha512-BFi3vZnO9X5Qt6NRz7ZOaPja3ic0PhlsmCRYLOpN11+mWBCR6XJDqW5RF3j8jm4WGGQZtBA+bTfxYzeKW73eHg==", + "dependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "agent-base": "^7.0.2", + "debug": "^4.3.4", + "get-uri": "^6.0.1", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.5", + "pac-resolver": "^7.0.1", + "socks-proxy-agent": "^8.0.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-proxy-agent/node_modules/socks-proxy-agent": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", + "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "dependencies": { + "agent-base": "^7.1.1", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-resolver": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", + "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", + "dependencies": { + "degenerator": "^5.0.0", + "netmask": "^2.0.2" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/pad-left": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz", @@ -11127,7 +11582,6 @@ "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", @@ -11152,18 +11606,6 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, - "node_modules/parse5-htmlparser2-tree-adapter": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz", - "integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==", - "dependencies": { - "domhandler": "^5.0.2", - "parse5": "^7.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -11201,6 +11643,11 @@ "node": ">=8" } }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==" + }, "node_modules/performance-now": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", @@ -11299,8 +11746,7 @@ "node_modules/picocolors": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", - "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", - "dev": true + "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==" }, "node_modules/picomatch": { "version": "2.3.1", @@ -11573,6 +12019,14 @@ "node": ">= 0.6.0" } }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/promise-inflight": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", @@ -11635,6 +12089,45 @@ "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" }, + "node_modules/proxy-agent": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.4.0.tgz", + "integrity": "sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "^4.3.4", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", + "lru-cache": "^7.14.1", + "pac-proxy-agent": "^7.0.1", + "proxy-from-env": "^1.1.0", + "socks-proxy-agent": "^8.0.2" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/proxy-agent/node_modules/socks-proxy-agent": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", + "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "dependencies": { + "agent-base": "^7.1.1", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/proxy-from-env": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", @@ -11662,6 +12155,131 @@ "node": ">=6" } }, + "node_modules/puppeteer": { + "version": "22.15.0", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-22.15.0.tgz", + "integrity": "sha512-XjCY1SiSEi1T7iSYuxS82ft85kwDJUS7wj1Z0eGVXKdtr5g4xnVcbjwxhq5xBnpK/E7x1VZZoJDxpjAOasHT4Q==", + "hasInstallScript": true, + "dependencies": { + "@puppeteer/browsers": "2.3.0", + "cosmiconfig": "^9.0.0", + "devtools-protocol": "0.0.1312386", + "puppeteer-core": "22.15.0" + }, + "bin": { + "puppeteer": "lib/esm/puppeteer/node/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/puppeteer-chromium-resolver": { + "version": "23.0.0", + "resolved": "https://registry.npmjs.org/puppeteer-chromium-resolver/-/puppeteer-chromium-resolver-23.0.0.tgz", + "integrity": "sha512-PbSXK4ERPwp+eYm+SVY5vMWCxsdeJcddwz4avXvDx7kE9DLE+L86Xg027sypw2oan5yi6557brzVsbajcMmy2g==", + "hasInstallScript": true, + "dependencies": { + "@puppeteer/browsers": "^2.3.1", + "eight-colors": "^1.3.0", + "gauge": "^5.0.2", + "puppeteer-core": "^23.1.0" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/@puppeteer/browsers": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.3.1.tgz", + "integrity": "sha512-uK7o3hHkK+naEobMSJ+2ySYyXtQkBxIH8Gn4MK9ciePjNV+Pf+PgY/W7iPzn2MTjl3stcYB5AlcTmPYw7AXDwA==", + "dependencies": { + "debug": "^4.3.6", + "extract-zip": "^2.0.1", + "progress": "^2.0.3", + "proxy-agent": "^6.4.0", + "semver": "^7.6.3", + "tar-fs": "^3.0.6", + "unbzip2-stream": "^1.4.3", + "yargs": "^17.7.2" + }, + "bin": { + "browsers": "lib/cjs/main-cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/chromium-bidi": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.6.4.tgz", + "integrity": "sha512-8zoq6ogmhQQkAKZVKO2ObFTl4uOkqoX1PlKQX3hZQ5E9cbUotcAb7h4pTNVAGGv8Z36PF3CtdOriEp/Rz82JqQ==", + "dependencies": { + "mitt": "3.0.1", + "urlpattern-polyfill": "10.0.0", + "zod": "3.23.8" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/gauge": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-5.0.2.tgz", + "integrity": "sha512-pMaFftXPtiGIHCJHdcUUx9Rby/rFT/Kkt3fIIGCs+9PMDIljSyRiqraTlxNtBReJRDfUefpa263RQ3vnp5G/LQ==", + "deprecated": "This package is no longer supported.", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.3", + "console-control-strings": "^1.1.0", + "has-unicode": "^2.0.1", + "signal-exit": "^4.0.1", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.5" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/puppeteer-core": { + "version": "23.1.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-23.1.1.tgz", + "integrity": "sha512-OeTqNiYGF9qZtwZU4Yc88DDqFJs4TJ4rnK81jkillh6MwDeQodyisM9xe5lBmPhwiDy92s5J5DQtQLjCKHFQ3g==", + "dependencies": { + "@puppeteer/browsers": "2.3.1", + "chromium-bidi": "0.6.4", + "debug": "^4.3.6", + "devtools-protocol": "0.0.1312386", + "typed-query-selector": "^2.12.0", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/puppeteer-core": { + "version": "22.15.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-22.15.0.tgz", + "integrity": "sha512-cHArnywCiAAVXa3t4GGL2vttNxh7GqXtIYGym99egkNJ3oG//wL9LkvO4WE8W1TJe95t1F1ocu9X4xWaGsOKOA==", + "dependencies": { + "@puppeteer/browsers": "2.3.0", + "chromium-bidi": "0.6.3", + "debug": "^4.3.6", + "devtools-protocol": "0.0.1312386", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/pure-rand": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", @@ -11949,7 +12567,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -12146,9 +12763,9 @@ } }, "node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "bin": { "semver": "bin/semver.js" }, @@ -12343,7 +12960,6 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "optional": true, "engines": { "node": ">= 6.0.0", "npm": ">= 3.0.0" @@ -12379,7 +12995,6 @@ "version": "2.8.3", "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz", "integrity": "sha512-l5x7VUUWbjVFbafGLxPWkYsHIhEvmF85tbIeFZWc8ZPtoMyybuEhL7Jye/ooC4/d48FgOjSJXgsF/AJPYCW8Zw==", - "optional": true, "dependencies": { "ip-address": "^9.0.5", "smart-buffer": "^4.2.0" @@ -12455,8 +13070,7 @@ "node_modules/sprintf-js": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", - "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", - "optional": true + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==" }, "node_modules/sqlite": { "version": "5.1.1", @@ -12610,7 +13224,6 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "devOptional": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -13149,6 +13762,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/typed-query-selector": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.0.tgz", + "integrity": "sha512-SbklCd1F0EiZOyPiW192rrHZzZ5sBijB6xM+cpmrwDqObvdtunOHHIk9fCGsoK5JVIYXoyEp4iEdE3upFH3PAg==" + }, "node_modules/typescript": { "version": "5.4.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", @@ -13197,6 +13815,38 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/unbzip2-stream": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz", + "integrity": "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==", + "dependencies": { + "buffer": "^5.2.1", + "through": "^2.3.8" + } + }, + "node_modules/unbzip2-stream/node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, "node_modules/undici": { "version": "6.18.2", "resolved": "https://registry.npmjs.org/undici/-/undici-6.18.2.tgz", @@ -13285,7 +13935,6 @@ "version": "1.0.16", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.16.tgz", "integrity": "sha512-KVbTxlBYlckhF5wgfyZXTWnMn7MMZjMu9XG8bPlliUOP9ThaF4QnhP8qrjrH7DRzHfSk0oQv1wToW+iA5GajEQ==", - "dev": true, "funding": [ { "type": "opencollective", @@ -13328,6 +13977,11 @@ "requires-port": "^1.0.0" } }, + "node_modules/urlpattern-polyfill": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/urlpattern-polyfill/-/urlpattern-polyfill-10.0.0.tgz", + "integrity": "sha512-H/A06tKD7sS1O1X2SshBVeA5FLycRpjqiBeqGKmBwBDBy28EnRjORxTNe269KSSr5un5qyWi1iL61wLxpd+ZOg==" + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -13359,6 +14013,14 @@ "node": ">=10.12.0" } }, + "node_modules/vali-date": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/vali-date/-/vali-date-1.0.0.tgz", + "integrity": "sha512-sgECfZthyaCKW10N0fm27cg8HYTFK5qMWgypqkXMQ4Wbl/zZKx7xZICgcoxIIE+WFAP/MBL2EFwC/YvLxw3Zeg==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/vectordb": { "version": "0.4.20", "resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.20.tgz", @@ -13529,7 +14191,6 @@ "version": "1.1.5", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", - "optional": true, "dependencies": { "string-width": "^1.0.2 || 2 || 3 || 4" } @@ -13588,7 +14249,6 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -13672,7 +14332,6 @@ "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, "engines": { "node": ">=10" } @@ -13698,7 +14357,6 @@ "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", @@ -13716,17 +14374,25 @@ "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, "engines": { "node": ">=12" } }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.1.1.tgz", + "integrity": "sha512-b4JR1PFR10y1mKjhHY9LaGo6tmrgjit7hxVIeAmyMw3jegXR4dhYqLaQF5zMXZxY7tLpMyJeLjr1C4rLmkVe8g==", "engines": { - "node": ">=10" + "node": ">=12.20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" diff --git a/core/package.json b/core/package.json index 82a8157b7..4b20b5b2c 100644 --- a/core/package.json +++ b/core/package.json @@ -3,7 +3,7 @@ "version": "1.0.13", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand", "build:npm": "tsc -p ./tsconfig.npm.json", "lint": "eslint . --ext ts", "lint:fix": "eslint . --ext ts --fix" @@ -39,8 +39,8 @@ }, "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.620.1", - "@aws-sdk/credential-providers": "^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", "@mozilla/readability": "^0.5.0", @@ -48,11 +48,9 @@ "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", - "jinja-js": "0.1.8", "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", @@ -63,6 +61,7 @@ "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", @@ -73,8 +72,11 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", + "puppeteer": "^22.4.0", + "puppeteer-chromium-resolver": "^23.0.0", "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", @@ -91,9 +93,6 @@ "yaml": "^2.4.2", "zod": "^3.23.8" }, - "puppeteer": { - "chromium_revision": "119.0.6045.105" - }, "engine-strict": true, "engines": { "node": ">=20.11.0" diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 6d96ec685..9cd4d4ec8 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,6 +1,5 @@ -/* eslint-disable @typescript-eslint/naming-convention */ -import type { AutocompleteInput } from "../autocomplete/completionProvider.js"; -import { ProfileDescription } from "../config/ConfigHandler.js"; +import type { AutocompleteInput } from "../autocomplete/completionProvider"; +import { ProfileDescription } from "../config/ConfigHandler"; import type { BrowserSerializedContinueConfig, ChatMessage, @@ -16,7 +15,7 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, -} from "../index.js"; +} from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ done?: boolean; @@ -129,8 +128,12 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined, { model: string; promptTokens: number; generatedTokens: number }[], ]; + "tts/kill": [undefined, void]; "index/setPaused": [boolean, void]; - "index/forceReIndex": [undefined | string, void]; + "index/forceReIndex": [ + undefined | { dir?: string; shouldClearIndexes?: boolean }, + void, + ]; "index/indexingProgressBarInitialized": [undefined, void]; completeOnboarding: [ { diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 2fa70bf73..5e1e74589 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -31,6 +31,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; + setTTSActive: [boolean, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap updateSubmenuItems: [ { provider: string; submenuItems: ContextSubmenuItem[] }, diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 5fe14573a..1e2499ca7 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -30,6 +30,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "autocomplete/cancel", "autocomplete/accept", "command/run", + "tts/kill", "llm/complete", "llm/streamComplete", "llm/streamChat", @@ -57,4 +58,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "refreshSubmenuItems", "isContinueInputFocused", "didChangeAvailableProfiles", + "setTTSActive", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 061f2819d..d3b127fdc 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -13,4 +13,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; + setTTSActive: [boolean, void]; }; diff --git a/core/test/context/providers/index.skip.ts b/core/test/context/providers/index.test.ts similarity index 94% rename from core/test/context/providers/index.skip.ts rename to core/test/context/providers/index.test.ts index a31d10e46..ae16ccb87 100644 --- a/core/test/context/providers/index.skip.ts +++ b/core/test/context/providers/index.test.ts @@ -8,7 +8,7 @@ import { ConfigHandler } from "../../../config/ConfigHandler"; import { contextProviderClassFromName } from "../../../context/providers"; import { ControlPlaneClient } from "../../../control-plane/client"; import FileSystemIde from "../../../util/filesystem"; -import { TEST_DIR } from "../../testUtils/testDir"; +import { TEST_DIR } from "../../util/testDir"; const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ { name: "diff", params: {} }, @@ -46,7 +46,7 @@ async function getContextProviderExtras( }; } -describe("Should successfully run all context providers", () => { +describe.skip("Should successfully run all context providers", () => { const extrasPromise = getContextProviderExtras("Test"); CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => { diff --git a/core/test/context/retrieval/RetrievalPipeline.test.ts b/core/test/context/retrieval/RetrievalPipeline.test.ts deleted file mode 100644 index d6bfdbb3d..000000000 --- a/core/test/context/retrieval/RetrievalPipeline.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { IRetrievalPipeline } from "../../../context/retrieval/pipelines/BaseRetrievalPipeline.js"; - -function testRetrievalPipeline(pipeline: IRetrievalPipeline) { - test("should successfully run"); -} - -describe.skip("RetrievalPipeline", () => { - test.todo("should successfully run"); -}); - -// describe("Retrieval Pipelines", () => { -// const ide = new FileSystemIde(); -// const options: RetrievalPipelineOptions; - -// test("NoRerankerRetrievalPipeline", () => { -// const pipeline = new NoRerankerRetrievalPipeline(options); -// testRetrievalPipeline(pipeline); -// }); - -// test("NoRerankerRetrievalPipeline", () => { -// const pipeline = new NoRerankerRetrievalPipeline(options); -// testRetrievalPipeline(pipeline); -// }); -// }); diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts deleted file mode 100644 index 97c1815b0..000000000 --- a/core/test/fixtures.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { ConfigHandler } from "../config/ConfigHandler"; -import { ControlPlaneClient } from "../control-plane/client"; -import FileSystemIde from "../util/filesystem"; -import { TEST_DIR } from "./testUtils/testDir"; - -export const testIde = new FileSystemIde(TEST_DIR); -export const ideSettingsPromise = testIde.getIdeSettings(); -export const testConfigHandler = new ConfigHandler( - testIde, - ideSettingsPromise, - async (text) => {}, - new ControlPlaneClient(Promise.resolve(undefined)), -); diff --git a/core/test/indexing/crawl.skip.ts b/core/test/indexing/crawl.skip.ts deleted file mode 100644 index 2f4b18817..000000000 --- a/core/test/indexing/crawl.skip.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { crawlPage, PageData } from "../../indexing/docs/crawl"; - -describe("crawlPage - GitHub repository", () => { - const repoUrl = new URL( - "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling", - ); - const maxDepth = 3; - let crawlResults: PageData[]; - - beforeAll(async () => { - crawlResults = []; - for await (const page of crawlPage(repoUrl, maxDepth)) { - crawlResults.push(page); - } - }, 30000); - - test("finds expected markdown files", async () => { - expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( - true, - ); - - expect( - crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), - ).toBe(true); - }); - - test("html includes the correct content", async () => { - const doc = crawlResults.find((page) => - page.path.endsWith("docs-depth-1.md"), - ); - - expect(doc?.html.includes("Test body")).toBe(true); - expect(doc?.html.includes("Test H2 Header")).toBe(true); - }); - - // This test is currently failing, `maxDepth` does not appear to be followed right now - test.todo( - "ignores files past the max depth", - // , () => { - // expect( - // crawlResults.some((page) => page.path.includes("docs-depth-3")), - // ).toBe(false); - // } - ); - - test("ignores non-markdown files, e.g. `test.js` at the root", async () => { - expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( - false, - ); - }); -}); diff --git a/core/test/llm.test.ts b/core/test/llm.test.ts index e3f427731..7b9b861b8 100644 --- a/core/test/llm.test.ts +++ b/core/test/llm.test.ts @@ -1,8 +1,8 @@ import * as dotenv from "dotenv"; -import { CompletionOptions } from "../index.js"; -import { BaseLLM } from "../llm/index.js"; -import OpenAI from "../llm/llms/OpenAI.js"; +import { CompletionOptions } from "../"; +import { BaseLLM } from "../llm/"; +import OpenAI from "../llm/llms/OpenAI"; // jest.setTimeout(100_000); diff --git a/core/test/llm/asyncEncoder.test.ts b/core/test/llm/asyncEncoder.test.ts deleted file mode 100644 index f181a05ca..000000000 --- a/core/test/llm/asyncEncoder.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { GPTAsyncEncoder, LlamaAsyncEncoder } from "../../llm/asyncEncoder"; - -describe("llama encoder", () => { - var tokenizer: LlamaAsyncEncoder; - - beforeAll(() => { - tokenizer = new LlamaAsyncEncoder(); - }); - - afterAll(() => { - tokenizer.close(); - }); - - test("hello world", async () => { - const input = "the quick brown fox jumped over the lazy dog"; - const output = await tokenizer.encode(input); - expect(output).toEqual([1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203]); - const decoded = await tokenizer.decode(output); - expect(decoded).toBe(input); - }); -}); - -describe("tiktoken encoder", () => { - var tokenizer: GPTAsyncEncoder; - - beforeAll(() => { - tokenizer = new GPTAsyncEncoder(); - }); - - afterAll(() => { - tokenizer.close(); - }); - - test("hello world", async () => { - const input = "the quick brown fox jumped over the lazy dog"; - const output = await tokenizer.encode(input); - expect(output).toEqual([1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679]); - const decoded = await tokenizer.decode(output); - expect(decoded).toBe(input); - }); -}); \ No newline at end of file diff --git a/core/test/util/dedentAndGetCommonWhitespace.test.ts b/core/test/util/dedentAndGetCommonWhitespace.test.ts deleted file mode 100644 index d96ccbe8f..000000000 --- a/core/test/util/dedentAndGetCommonWhitespace.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -// File generated by Continue -import { dedentAndGetCommonWhitespace } from "../../util/index.js"; - -describe("dedentAndGetCommonWhitespace", () => { - let originalString: string; - - beforeEach(() => { - // Setup any global variables or states if needed - originalString = " line1\n line2\n line3"; - }); - - afterEach(() => { - // Tear down any changes to global variables or states if needed - originalString = ""; - }); - - test("should dedent and return common whitespace for a simple case", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", " "]); - }); - - test("should handle empty string", () => { - const input = ""; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["", ""]); - }); - - test("should handle string with only whitespace", () => { - const input = " "; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["", ""]); - }); - - test("should handle string with mixed whitespace and content", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([" line1\nline2\n line3", " "]); - }); - - test("should handle string with no common leading whitespace", () => { - const input = "line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([input, ""]); - }); - - test("should handle string with empty lines", () => { - const input = " line1\n\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\n\nline3", " "]); - }); - - test("should handle string with only empty lines", () => { - const input = "\n\n"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["\n\n", ""]); - }); - - test("should handle string with tabs as whitespace", () => { - const input = "\tline1\n\tline2\n\tline3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", "\t"]); - }); - - test("should handle string with mixed tabs and spaces", () => { - const input = "\t line1\n\t line2\n\t line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", "\t "]); - }); - - test("should handle string with different leading whitespace lengths", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([" line1\nline2\n line3", " "]); - }); -}); diff --git a/core/test/util/deduplicateArray.test.ts b/core/test/util/deduplicateArray.test.ts deleted file mode 100644 index f4277916b..000000000 --- a/core/test/util/deduplicateArray.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { deduplicateArray } from "../../util/index.js"; - -describe("deduplicateArray", () => { - it("should return an empty array when given an empty array", () => { - const result = deduplicateArray([], (a, b) => a === b); - expect(result).toEqual([]); - }); - - it("should return the same array when there are no duplicates", () => { - const input = [1, 2, 3, 4, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual(input); - }); - - it("should remove duplicates based on the equality function", () => { - const input = [1, 2, 2, 3, 4, 4, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([1, 2, 3, 4, 5]); - }); - - it("should work with objects using custom equality function", () => { - const input = [ - { id: 1, name: "Alice" }, - { id: 2, name: "Bob" }, - { id: 1, name: "Alice" }, - { id: 3, name: "Charlie" }, - ]; - const result = deduplicateArray(input, (a, b) => a.id === b.id); - expect(result).toEqual([ - { id: 1, name: "Alice" }, - { id: 2, name: "Bob" }, - { id: 3, name: "Charlie" }, - ]); - }); - - it("should preserve the order of items", () => { - const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]); - }); - - it("should work with strings", () => { - const input = ["apple", "banana", "apple", "cherry", "banana", "date"]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual(["apple", "banana", "cherry", "date"]); - }); - - it("should handle arrays with all duplicate elements", () => { - const input = [1, 1, 1, 1, 1]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([1]); - }); - - it("should work with custom equality function for complex objects", () => { - const input = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 1, y: 2 }, - { x: 3, y: 4 }, - ]; - const result = deduplicateArray( - input, - (a, b) => a.x === b.x && a.y === b.y, - ); - expect(result).toEqual([ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 3, y: 4 }, - ]); - }); - - it("should handle large arrays efficiently", () => { - const input = Array(10000) - .fill(0) - .map((_, i) => i % 100); - const start = performance.now(); - const result = deduplicateArray(input, (a, b) => a === b); - const end = performance.now(); - expect(result).toHaveLength(100); - expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second - }); -}); diff --git a/core/test/util/fixtures.ts b/core/test/util/fixtures.ts new file mode 100644 index 000000000..89c1c0b3b --- /dev/null +++ b/core/test/util/fixtures.ts @@ -0,0 +1,19 @@ +import { ConfigHandler } from "../../config/ConfigHandler"; +import { ControlPlaneClient } from "../../control-plane/client"; +import FileSystemIde from "../../util/filesystem"; +import { TEST_DIR } from "./testDir"; + +export const testIde = new FileSystemIde(TEST_DIR); + +export const ideSettingsPromise = testIde.getIdeSettings(); + +export const testControlPlaneClient = new ControlPlaneClient( + Promise.resolve(undefined), +); + +export const testConfigHandler = new ConfigHandler( + testIde, + ideSettingsPromise, + async (text) => {}, + testControlPlaneClient, +); diff --git a/core/test/util/getLastNPathParts.test.ts b/core/test/util/getLastNPathParts.test.ts deleted file mode 100644 index 926218fe2..000000000 --- a/core/test/util/getLastNPathParts.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -// File generated by Continue -import { getLastNPathParts } from "../../util/index.js"; - -describe("getLastNPathParts", () => { - const SEP_REGEX = /[\\/]+/; - - beforeAll(() => { - // Setup code if needed - }); - - afterAll(() => { - // Teardown code if needed - }); - - test("returns the last N parts of a filepath with forward slashes", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); - }); - - test("returns the last N parts of a filepath with backward slashes", () => { - const filepath = "C:\\home\\user\\documents\\project\\file.txt"; - expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); - }); - - test("returns the last part if N is 1", () => { - const filepath = "/home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); - }); - - test("returns the entire path if N is greater than the number of parts", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 10)).toBe( - "home/user/documents/project/file.txt", - ); - }); - - test("returns an empty string if N is 0", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 0)).toBe(""); - }); - - test("handles paths with mixed forward and backward slashes", () => { - const filepath = "home\\user/documents\\project/file.txt"; - expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); - }); - - test("handles edge case with empty filepath", () => { - const filepath = ""; - expect(getLastNPathParts(filepath, 2)).toBe(""); - }); -}); diff --git a/core/test/util/history.test.ts b/core/test/util/history.test.ts new file mode 100644 index 000000000..d3dedac7f --- /dev/null +++ b/core/test/util/history.test.ts @@ -0,0 +1,131 @@ +import { PersistedSessionInfo } from "../.."; +import historyManager from "../../util/history"; +import { getSessionFilePath } from "../../util/paths"; +import { v4 as uuidv4 } from "uuid"; + +const sessionId = uuidv4(); +const testSession: PersistedSessionInfo = { + history: [], + title: `${sessionId} title`, + workspaceDirectory: "workspaceDir", + sessionId: sessionId, +}; + +describe("No sessions have been created", () => { + const testSessionId = "invalid"; + const testSessionPath = getSessionFilePath(testSessionId); + + test("Listing all sessions returns empty list", () => { + const sessions = historyManager.list({}); + expect(sessions).toEqual([]); + }); + + test("Deleting session throws error", () => { + expect(() => { + historyManager.delete(testSessionId); + }).toThrow(`Session file ${testSessionPath} does not exist`); + }); + + test("Loading session returns default session", () => { + const session = historyManager.load(testSessionId); + expect(session).toEqual({ + history: [], + title: "Failed to load session", + workspaceDirectory: "", + sessionId: testSessionId, + }); + }); +}); + +describe("Full session lifecycle", () => { + test("Creating and listing a session", () => { + // save and list + historyManager.save(testSession); + const sessions = historyManager.list({}); + const sessionExists = sessions.some((session) => session?.sessionId === testSession.sessionId); + expect(sessionExists).toBe(true); + }); + + test("Loading session by ID returns correct object", () => { + const retrievedSession = historyManager.load(testSession.sessionId); + expect(retrievedSession).toEqual(testSession); + }); + + test("Saving session with new title updates session", () => { + const modifiedSession = { ...testSession }; + modifiedSession.title = `Edited: ${testSession.title}`; + historyManager.save(modifiedSession); + const session = historyManager.load(testSession.sessionId); + + expect(session.title).toBe(modifiedSession.title); + }); + + test("Deleting session", () => { + historyManager.delete(testSession.sessionId); + const sessions = historyManager.list({}); + const sessionWasDeleted = sessions.every( + (session) => session?.sessionId !== testSession.sessionId, + ); + expect(sessionWasDeleted).toEqual(true); + }); +}); + +describe("Many sessions created", () => { + test("Create 100 sessions and list all", () => { + for (let i = 0; i < 100; i++) { + historyManager.save({ + history: [], + title: `${i}`, + workspaceDirectory: "workspaceDir", + sessionId: `${i}`, + }); + } + const sessions = historyManager.list({}); + expect(sessions.length).toBe(100); + }); + + test("List 10 sessions, offest by 10", () => { + const limit = 10; + const offset = 10; + + const sessions = historyManager.list({ offset: offset, limit: limit }); + const sessionIds = Array.from({ length: limit }, (_, i) => (i + offset).toString()); + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("List 25 sessions, with no offset", () => { + const limit = 25; + + const sessions = historyManager.list({ limit: limit }); + const sessionIds = Array.from({ length: limit }, (_, i) => i.toString()); + + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("List sessions offset by 75", () => { + const offset = 75; + + const sessions = historyManager.list({ offset: offset }); + const sessionIds = Array.from({ length: sessions.length - offset }, (_, i) => + (i + offset).toString(), + ); + + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("Delete all sessions", () => { + let sessions = historyManager.list({}); + + for (let session of sessions) { + historyManager.delete(session.sessionId); + } + sessions = historyManager.list({}); + expect(sessions.length).toBe(0); + }); +}); diff --git a/core/test/util/indexing.ts b/core/test/util/indexing.ts new file mode 100644 index 000000000..650cc5b56 --- /dev/null +++ b/core/test/util/indexing.ts @@ -0,0 +1,88 @@ +import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; +import { IContinueServerClient } from "../../continueServer/interface"; +import { testIde } from "./fixtures"; +import { addToTestDir, TEST_DIR } from "./testDir"; +import { IndexTag } from "../.."; +import { + CodebaseIndex, + PathAndCacheKey, + RefreshIndexResults, +} from "../../indexing/types"; +import { jest } from "@jest/globals"; +import { tagToString } from "../../indexing/refreshIndex"; + +export const mockFilename = "test.py"; +export const mockPathAndCacheKey = { + path: `${TEST_DIR}/${mockFilename}`, + cacheKey: "abc123", +}; + +export const mockFileContents = `\ +def main(): + print("Hello, world!") + +class Foo: + def __init__(self, bar: str): + self.bar = bar +`; + +export const mockTag: IndexTag = { + branch: "main", + directory: "/", + artifactId: "artifactId", +}; + +export const mockTagString = tagToString(mockTag); + +export const testContinueServerClient = { + connected: false, + getFromIndexCache: jest.fn(), +} as unknown as IContinueServerClient; + +const mockContinueServerClient = { + connected: false, + getFromIndexCache: jest.fn(), +} as unknown as IContinueServerClient; + +const mockResults: RefreshIndexResults = { + compute: [], + addTag: [], + removeTag: [], + del: [], +}; + +const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + +export async function insertMockChunks() { + const pathSep = await testIde.pathSep(); + + const index = new ChunkCodebaseIndex( + testIde.readFile.bind(testIde), + pathSep, + mockContinueServerClient, + 1000, + ); + + addToTestDir([[mockFilename, mockFileContents]]); + + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); +} + +export async function updateIndexAndAwaitGenerator( + index: CodebaseIndex, + resultType: keyof RefreshIndexResults, + markComplete: any, + tag: IndexTag = mockTag, +) { + const computeGenerator = index.update( + tag, + { ...mockResults, [resultType]: [mockPathAndCacheKey] }, + markComplete, + "test-repo", + ); + + while (!(await computeGenerator.next()).done) {} +} diff --git a/core/test/util/lcs.test.ts b/core/test/util/lcs.test.ts deleted file mode 100644 index c7116fd8b..000000000 --- a/core/test/util/lcs.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -// This file is generated by Continue -import { longestCommonSubsequence } from "../../util/lcs.js"; - -describe("longestCommonSubsequence", () => { - beforeAll(() => { - // Setup if needed - }); - - afterAll(() => { - // Teardown if needed - }); - - test("should return the longest common subsequence for non-empty strings", () => { - expect(longestCommonSubsequence("abcde", "ace")).toBe("ace"); - expect(longestCommonSubsequence("abc", "abc")).toBe("abc"); - expect(longestCommonSubsequence("abc", "def")).toBe(""); - }); - - test("should handle cases where one or both strings are empty", () => { - expect(longestCommonSubsequence("", "abc")).toBe(""); - expect(longestCommonSubsequence("abc", "")).toBe(""); - expect(longestCommonSubsequence("", "")).toBe(""); - }); - - test("should handle cases with no common subsequence", () => { - expect(longestCommonSubsequence("abc", "def")).toBe(""); - expect(longestCommonSubsequence("xyz", "abc")).toBe(""); - }); - - test("should handle cases with special characters", () => { - expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$"); - expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe(""); - }); - - test("should handle long strings efficiently", () => { - const str1 = "a".repeat(1000) + "b".repeat(1000); - const str2 = "a".repeat(1000) + "c".repeat(1000); - expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000)); - }); -}); diff --git a/core/test/util/ranges/getRangeInString.test.ts b/core/test/util/ranges/getRangeInString.test.ts deleted file mode 100644 index 95d9f25af..000000000 --- a/core/test/util/ranges/getRangeInString.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -// This file is generated by Continue - -import { getRangeInString } from "../../../util/ranges.js"; - -describe.skip("getRangeInString", () => { - let content: string; - - beforeEach(() => { - content = `Line 1 -Line 2 -Line 3 -Line 4 -Line 5`; - }); - - afterEach(() => { - content = ""; - }); - - test("should return substring within the same line", () => { - const range = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 4 }, - }; - expect(getRangeInString(content, range)).toBe("Line"); - }); - - test("should return substring spanning multiple lines", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 3, character: 3 }, - }; - const expected = `ne 2 -Line 3 -Line 4`; - expect(getRangeInString(content, range)).toBe(expected); - }); - - test("should handle range that starts and ends at the same character", () => { - const range = { - start: { line: 2, character: 0 }, - end: { line: 2, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe("L"); - }); - - test("should handle range that spans entire content", () => { - const range = { - start: { line: 0, character: 0 }, - end: { line: 4, character: 5 }, - }; - expect(getRangeInString(content, range)).toBe(content); - }); - - test("should handle range that spans to the end of the last line", () => { - const range = { - start: { line: 3, character: 2 }, - end: { line: 4, character: 5 }, - }; - const expected = `ne 4 -Line 5`; - expect(getRangeInString(content, range)).toBe(expected); - }); - - test("should handle empty content", () => { - content = ""; - const range = { - start: { line: 0, character: 0 }, - end: { line: 0, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle invalid range (start line > end line)", () => { - const range = { - start: { line: 3, character: 0 }, - end: { line: 2, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle invalid range (start character > end character on same line)", () => { - const range = { - start: { line: 1, character: 5 }, - end: { line: 1, character: 2 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle range that starts and ends at the same line but different characters", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 1, character: 6 }, - }; - expect(getRangeInString(content, range)).toBe("ne 2"); - }); - - test("should handle range that starts and ends at the same line and same characters", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 1, character: 2 }, - }; - expect(getRangeInString(content, range)).toBe("n"); - }); -}); diff --git a/core/test/util/ranges/intersection.test.ts b/core/test/util/ranges/intersection.test.ts deleted file mode 100644 index e1b0a3d52..000000000 --- a/core/test/util/ranges/intersection.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -// This file is generated by Continue - -import { intersection } from "../../../util/ranges.js"; - -interface Position { - line: number; - character: number; -} - -interface Range { - start: Position; - end: Position; -} - -describe("intersection", () => { - let rangeA: Range; - let rangeB: Range; - - beforeEach(() => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 3, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 2 }, - end: { line: 4, character: 0 }, - }; - }); - - test("returns correct intersection for overlapping ranges", () => { - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 2 }, - end: { line: 3, character: 5 }, - }); - }); - - test("returns null for non-overlapping ranges", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 2, character: 0 }, - }; - - rangeB = { - start: { line: 3, character: 0 }, - end: { line: 4, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toBeNull(); - }); - - // TODO - test.skip("returns correct intersection for single line overlap", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 5 }, - }; - - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 2, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 3 }, - end: { line: 1, character: 5 }, - }); - }); - - test("returns null for single line non-overlapping ranges", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 2 }, - }; - - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 1, character: 5 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toBeNull(); - }); - - test("returns correct intersection when one range is fully within another", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 4, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 2 }, - end: { line: 3, character: 3 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 2 }, - end: { line: 3, character: 3 }, - }); - }); - - test("returns correct intersection when ranges touch at the edge", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 2, character: 0 }, - }; - - rangeB = { - start: { line: 2, character: 0 }, - end: { line: 3, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 0 }, - end: { line: 2, character: 0 }, - }); - }); -}); diff --git a/core/test/util/ranges/maxMinPosition.test.ts b/core/test/util/ranges/maxMinPosition.test.ts deleted file mode 100644 index 684dced31..000000000 --- a/core/test/util/ranges/maxMinPosition.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { maxPosition, minPosition } from "../../../util/ranges.js"; - -// This file is generated by Continue -interface Position { - line: number; - character: number; -} - -describe("Position comparison functions", () => { - let pos1: Position; - let pos2: Position; - let pos3: Position; - let pos4: Position; - - beforeAll(() => { - // Setup: Initializing positions - pos1 = { line: 1, character: 5 }; - pos2 = { line: 2, character: 3 }; - pos3 = { line: 1, character: 7 }; - pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality - }); - - describe("maxPosition", () => { - it("should return the position with the greater line number", () => { - expect(maxPosition(pos1, pos2)).toEqual(pos2); - }); - - it("should return the position with the greater character number when lines are equal", () => { - expect(maxPosition(pos1, pos3)).toEqual(pos3); - }); - - it("should return the first position when both positions are equal", () => { - expect(maxPosition(pos2, pos4)).toEqual(pos2); - }); - - it("should handle positions with negative line numbers", () => { - const posNegative = { line: -1, character: 0 }; - expect(maxPosition(posNegative, pos1)).toEqual(pos1); - }); - - it("should handle positions with negative character numbers", () => { - const posNegativeChar = { line: 1, character: -1 }; - expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); - }); - }); - - describe("minPosition", () => { - it("should return the position with the lesser line number", () => { - expect(minPosition(pos1, pos2)).toEqual(pos1); - }); - - it("should return the position with the lesser character number when lines are equal", () => { - expect(minPosition(pos1, pos3)).toEqual(pos1); - }); - - it("should return the first position when both positions are equal", () => { - expect(minPosition(pos2, pos4)).toEqual(pos2); - }); - - it("should handle positions with negative line numbers", () => { - const posNegative = { line: -1, character: 0 }; - expect(minPosition(posNegative, pos1)).toEqual(posNegative); - }); - - it("should handle positions with negative character numbers", () => { - const posNegativeChar = { line: 1, character: -1 }; - expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); - }); - }); -}); diff --git a/core/test/util/ranges/union.test.ts b/core/test/util/ranges/union.test.ts deleted file mode 100644 index 0ee62cb4f..000000000 --- a/core/test/util/ranges/union.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { union } from "../../../util/ranges.js"; - -// This file is generated by Continue -interface Position { - line: number; - character: number; -} - -interface Range { - start: Position; - end: Position; -} - -describe("union", () => { - let rangeA: Range; - let rangeB: Range; - - beforeEach(() => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 3, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 3 }, - end: { line: 4, character: 2 }, - }; - }); - - test("should return the union of two overlapping ranges", () => { - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 4, character: 2 }, - }); - }); - - test("should return the union when ranges are identical", () => { - const result = union(rangeA, rangeA); - expect(result).toEqual(rangeA); - }); - - test("should return the union when ranges do not overlap but are adjacent", () => { - rangeB = { - start: { line: 3, character: 5 }, - end: { line: 4, character: 2 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 4, character: 2 }, - }); - }); - - test("should return the union when one range is completely within the other", () => { - rangeB = { - start: { line: 2, character: 1 }, - end: { line: 2, character: 4 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual(rangeA); - }); - - test("should return the union when ranges do not overlap and are not adjacent", () => { - rangeB = { - start: { line: 4, character: 3 }, - end: { line: 5, character: 1 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 5, character: 1 }, - }); - }); - - // TODO - test.skip("should handle edge case where start and end lines are the same", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 5 }, - }; - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 1, character: 7 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 1, character: 7 }, - }); - }); -}); diff --git a/core/test/testUtils/testDir.ts b/core/test/util/testDir.ts similarity index 91% rename from core/test/testUtils/testDir.ts rename to core/test/util/testDir.ts index 557906cef..d6bc462dc 100644 --- a/core/test/testUtils/testDir.ts +++ b/core/test/util/testDir.ts @@ -1,8 +1,9 @@ import fs from "fs"; import path from "path"; +import os from "os"; // Want this outside of the git repository so we can change branches in tests -export const TEST_DIR = path.join(__dirname, "..", "..", "testDir"); +export const TEST_DIR = path.join(os.tmpdir(), "testDir"); export function setUpTestDir() { if (fs.existsSync(TEST_DIR)) { diff --git a/core/util/devdataSqlite.ts b/core/util/devdataSqlite.ts index 9724e9f21..4f86cb1a1 100644 --- a/core/util/devdataSqlite.ts +++ b/core/util/devdataSqlite.ts @@ -21,14 +21,14 @@ export class DevDataSqliteDb { // Add tokens_prompt column if it doesn't exist const columnCheckResult = await db.all( - `PRAGMA table_info(tokens_generated);`, + "PRAGMA table_info(tokens_generated);", ); const columnExists = columnCheckResult.some( (col: any) => col.name === "tokens_prompt", ); if (!columnExists) { await db.exec( - `ALTER TABLE tokens_generated ADD COLUMN tokens_prompt INTEGER NOT NULL DEFAULT 0;`, + "ALTER TABLE tokens_generated ADD COLUMN tokens_prompt INTEGER NOT NULL DEFAULT 0;", ); } } @@ -41,7 +41,7 @@ export class DevDataSqliteDb { ) { const db = await DevDataSqliteDb.get(); await db?.run( - `INSERT INTO tokens_generated (model, provider, tokens_prompt, tokens_generated) VALUES (?, ?, ?, ?)`, + "INSERT INTO tokens_generated (model, provider, tokens_prompt, tokens_generated) VALUES (?, ?, ?, ?)", [model, provider, promptTokens, generatedTokens], ); } diff --git a/core/util/extractMinimalStackTraceInfo.ts b/core/util/extractMinimalStackTraceInfo.ts new file mode 100644 index 000000000..51fcde91a --- /dev/null +++ b/core/util/extractMinimalStackTraceInfo.ts @@ -0,0 +1,16 @@ +/** + * It's helpful to know what functions errors occur in, but absolute + * file paths are sensitive information, so we want to remove them. + * @param stack The stack trace to extract minimal information from. + * @returns A string containing the minimal stack trace information. + */ +export function extractMinimalStackTraceInfo(stack: unknown): string { + if (typeof stack !== "string") {return "";} + const lines = stack.split("\n"); + const minimalLines = lines.filter((line) => { + return line.trimStart().startsWith("at ") && !line.includes("node_modules"); + }); + return minimalLines + .map((line) => line.trimStart().replace("at ", "").split(" (").slice(0, 1)) + .join(", "); +} diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 330776518..06209a474 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -84,12 +84,12 @@ class FileSystemIde implements IDE { } async getTags(artifactId: string): Promise { - const directory =(await this.getWorkspaceDirs())[0] + const directory =(await this.getWorkspaceDirs())[0]; return [{ artifactId, branch: await this.getBranch(directory), directory - }] + }]; } getIdeInfo(): Promise { diff --git a/core/util/index.test.ts b/core/util/index.test.ts new file mode 100644 index 000000000..0d618069c --- /dev/null +++ b/core/util/index.test.ts @@ -0,0 +1,200 @@ +// File generated by Continue +import { + dedentAndGetCommonWhitespace, + deduplicateArray, + getLastNPathParts, +} from "./"; + +describe("getLastNPathParts", () => { + test("returns the last N parts of a filepath with forward slashes", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); + }); + + test("returns the last N parts of a filepath with backward slashes", () => { + const filepath = "C:\\home\\user\\documents\\project\\file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("returns the last part if N is 1", () => { + const filepath = "/home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); + }); + + test("returns the entire path if N is greater than the number of parts", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 10)).toBe( + "home/user/documents/project/file.txt", + ); + }); + + test("returns an empty string if N is 0", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 0)).toBe(""); + }); + + test("handles paths with mixed forward and backward slashes", () => { + const filepath = "home\\user/documents\\project/file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("handles edge case with empty filepath", () => { + const filepath = ""; + expect(getLastNPathParts(filepath, 2)).toBe(""); + }); +}); + +describe("deduplicateArray", () => { + it("should return an empty array when given an empty array", () => { + const result = deduplicateArray([], (a, b) => a === b); + expect(result).toEqual([]); + }); + + it("should return the same array when there are no duplicates", () => { + const input = [1, 2, 3, 4, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual(input); + }); + + it("should remove duplicates based on the equality function", () => { + const input = [1, 2, 2, 3, 4, 4, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([1, 2, 3, 4, 5]); + }); + + it("should work with objects using custom equality function", () => { + const input = [ + { id: 1, name: "Alice" }, + { id: 2, name: "Bob" }, + { id: 1, name: "Alice" }, + { id: 3, name: "Charlie" }, + ]; + const result = deduplicateArray(input, (a, b) => a.id === b.id); + expect(result).toEqual([ + { id: 1, name: "Alice" }, + { id: 2, name: "Bob" }, + { id: 3, name: "Charlie" }, + ]); + }); + + it("should preserve the order of items", () => { + const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]); + }); + + it("should work with strings", () => { + const input = ["apple", "banana", "apple", "cherry", "banana", "date"]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual(["apple", "banana", "cherry", "date"]); + }); + + it("should handle arrays with all duplicate elements", () => { + const input = [1, 1, 1, 1, 1]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([1]); + }); + + it("should work with custom equality function for complex objects", () => { + const input = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 1, y: 2 }, + { x: 3, y: 4 }, + ]; + const result = deduplicateArray( + input, + (a, b) => a.x === b.x && a.y === b.y, + ); + expect(result).toEqual([ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 3, y: 4 }, + ]); + }); + + it("should handle large arrays efficiently", () => { + const input = Array(10000) + .fill(0) + .map((_, i) => i % 100); + const start = performance.now(); + const result = deduplicateArray(input, (a, b) => a === b); + const end = performance.now(); + expect(result).toHaveLength(100); + expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second + }); +}); + +describe("dedentAndGetCommonWhitespace", () => { + let originalString: string; + + beforeEach(() => { + // Setup any global variables or states if needed + originalString = " line1\n line2\n line3"; + }); + + afterEach(() => { + // Tear down any changes to global variables or states if needed + originalString = ""; + }); + + test("should dedent and return common whitespace for a simple case", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", " "]); + }); + + test("should handle empty string", () => { + const input = ""; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with only whitespace", () => { + const input = " "; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with mixed whitespace and content", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); + + test("should handle string with no common leading whitespace", () => { + const input = "line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([input, ""]); + }); + + test("should handle string with empty lines", () => { + const input = " line1\n\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\n\nline3", " "]); + }); + + test("should handle string with only empty lines", () => { + const input = "\n\n"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["\n\n", ""]); + }); + + test("should handle string with tabs as whitespace", () => { + const input = "\tline1\n\tline2\n\tline3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t"]); + }); + + test("should handle string with mixed tabs and spaces", () => { + const input = "\t line1\n\t line2\n\t line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t "]); + }); + + test("should handle string with different leading whitespace lengths", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); +}); diff --git a/core/util/index.ts b/core/util/index.ts index 0c7a06317..a628948c7 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -2,19 +2,19 @@ export function removeQuotesAndEscapes(output: string): string { output = output.trim(); // Replace smart quotes - output = output.replace("“", '"'); - output = output.replace("”", '"'); + output = output.replace("“", "\""); + output = output.replace("”", "\""); output = output.replace("‘", "'"); output = output.replace("’", "'"); // Remove escapes - output = output.replace('\\"', '"'); + output = output.replace("\\\"", "\""); output = output.replace("\\'", "'"); output = output.replace("\\n", "\n"); output = output.replace("\\t", "\t"); output = output.replace("\\\\", "\\"); while ( - (output.startsWith('"') && output.endsWith('"')) || + (output.startsWith("\"") && output.endsWith("\"")) || (output.startsWith("'") && output.endsWith("'")) ) { output = output.slice(1, -1); @@ -120,7 +120,7 @@ export function getUniqueFilePath( } export function shortestRelativePaths(paths: string[]): string[] { - if (paths.length === 0) return []; + if (paths.length === 0) {return [];} const partsLengths = paths.map((x) => x.split(SEP_REGEX).length); const currentRelativePaths = paths.map(getBasename); @@ -135,7 +135,7 @@ export function shortestRelativePaths(paths: string[]): string[] { const firstDuplicatedPath = currentRelativePaths.find( (x, i) => isDuplicated[i], ); - if (!firstDuplicatedPath) break; + if (!firstDuplicatedPath) {break;} currentRelativePaths.forEach((x, i) => { if (x === firstDuplicatedPath) { diff --git a/core/util/lcs.test.ts b/core/util/lcs.test.ts new file mode 100644 index 000000000..2f8e1f92f --- /dev/null +++ b/core/util/lcs.test.ts @@ -0,0 +1,31 @@ +import { longestCommonSubsequence as lcs } from "./lcs"; + +describe("longestCommonSubsequence", () => { + test("should return the longest common subsequence for non-empty strings", () => { + expect(lcs("abcde", "ace")).toBe("ace"); + expect(lcs("abc", "abc")).toBe("abc"); + expect(lcs("abc", "def")).toBe(""); + }); + + test("should handle cases where one or both strings are empty", () => { + expect(lcs("", "abc")).toBe(""); + expect(lcs("abc", "")).toBe(""); + expect(lcs("", "")).toBe(""); + }); + + test("should handle cases with no common subsequence", () => { + expect(lcs("abc", "def")).toBe(""); + expect(lcs("xyz", "abc")).toBe(""); + }); + + test("should handle cases with special characters", () => { + expect(lcs("a!@#b$c", "!@#$")).toBe("!@#$"); + expect(lcs("a!@#b$c", "xyz")).toBe(""); + }); + + test("should handle long strings efficiently", () => { + const str1 = "a".repeat(1000) + "b".repeat(1000); + const str2 = "a".repeat(1000) + "c".repeat(1000); + expect(lcs(str1, str2)).toBe("a".repeat(1000)); + }); +}); diff --git a/core/test/util/merge.test.ts b/core/util/merge.test.ts similarity index 96% rename from core/test/util/merge.test.ts rename to core/util/merge.test.ts index 3bd8309a8..237f362c4 100644 --- a/core/test/util/merge.test.ts +++ b/core/util/merge.test.ts @@ -1,5 +1,6 @@ // File generated by Continue -import { mergeJson } from "../../util/merge.js"; + +import mergeJson from "./merge"; describe("mergeJson", () => { it("should merge two simple JSON objects", () => { @@ -9,7 +10,7 @@ describe("mergeJson", () => { expect(result).toEqual({ a: 1, b: 3, c: 4 }); }); - it('should overwrite values when mergeBehavior is "overwrite"', () => { + it("should overwrite values when mergeBehavior is \"overwrite\"", () => { const first = { a: 1, b: 2 }; const second = { b: 3, c: 4 }; const result = mergeJson(first, second, "overwrite"); diff --git a/core/util/messenger.ts b/core/util/messenger.ts index 416e4e8da..2b0593ef3 100644 --- a/core/util/messenger.ts +++ b/core/util/messenger.ts @@ -75,7 +75,7 @@ export class InProcessMessenger< messageId?: string, ): ToProtocol[T][1] { const listener = this.myTypeListeners.get(messageType); - if (!listener) return; + if (!listener) {return;} const msg: Message = { messageType: messageType as string, diff --git a/core/util/paths.ts b/core/util/paths.ts index 7c208f92c..5bc7fc26b 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -8,9 +8,22 @@ import Types from "../config/types.js"; import { IdeType, SerializedContinueConfig } from "../index.js"; dotenv.config(); + const CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue"); +export function getChromiumPath(): string { + return path.join(getContinueUtilsPath(), ".chromium-browser-snapshots"); +} + +export function getContinueUtilsPath(): string { + const utilsPath = path.join(getContinueGlobalPath(), ".utils"); + if (!fs.existsSync(utilsPath)) { + fs.mkdirSync(utilsPath); + } + return utilsPath; +} + export function getContinueGlobalPath(): string { // This is ~/.continue on mac/linux const continuePath = CONTINUE_GLOBAL_DIR; @@ -200,6 +213,10 @@ export async function migrate( callback: () => void | Promise, onAlreadyComplete?: () => void, ) { + if (process.env.NODE_ENV === "test") { + return await Promise.resolve(callback()); + } + const migrationsPath = getMigrationsFolderPath(); const migrationPath = path.join(migrationsPath, id); diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 3a79814d0..be62977fc 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -1,12 +1,13 @@ import os from "node:os"; import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; +import { IdeInfo } from "../index.js"; export class Telemetry { // Set to undefined whenever telemetry is disabled static client: any = undefined; static uniqueId = "NOT_UNIQUE"; static os: string | undefined = undefined; - static extensionVersion: string | undefined = undefined; + static ideInfo: IdeInfo | undefined = undefined; static async capture( event: string, @@ -19,7 +20,9 @@ export class Telemetry { properties: { ...properties, os: Telemetry.os, - extensionVersion: Telemetry.extensionVersion, + extensionVersion: Telemetry.ideInfo?.extensionVersion, + ideName: Telemetry.ideInfo?.name, + ideType: Telemetry.ideInfo?.ideType, }, }); @@ -32,14 +35,10 @@ export class Telemetry { Telemetry.client?.shutdown(); } - static async setup( - allow: boolean, - uniqueId: string, - extensionVersion: string, - ) { + static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) { Telemetry.uniqueId = uniqueId; Telemetry.os = os.platform(); - Telemetry.extensionVersion = extensionVersion; + Telemetry.ideInfo = ideInfo; if (!allow) { Telemetry.client = undefined; diff --git a/core/util/ranges.test.ts b/core/util/ranges.test.ts new file mode 100644 index 000000000..d9d12c07a --- /dev/null +++ b/core/util/ranges.test.ts @@ -0,0 +1,374 @@ +// This file is generated by Continue + +import { + intersection, + getRangeInString, + maxPosition, + minPosition, + union, +} from "./ranges"; + +interface Position { + line: number; + character: number; +} + +interface Range { + start: Position; + end: Position; +} + +describe("union", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 3 }, + end: { line: 4, character: 2 }, + }; + }); + + test("should return the union of two overlapping ranges", () => { + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when ranges are identical", () => { + const result = union(rangeA, rangeA); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap but are adjacent", () => { + rangeB = { + start: { line: 3, character: 5 }, + end: { line: 4, character: 2 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when one range is completely within the other", () => { + rangeB = { + start: { line: 2, character: 1 }, + end: { line: 2, character: 4 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap and are not adjacent", () => { + rangeB = { + start: { line: 4, character: 3 }, + end: { line: 5, character: 1 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 5, character: 1 }, + }); + }); + + // TODO + test.skip("should handle edge case where start and end lines are the same", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 7 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 1, character: 7 }, + }); + }); +}); + +describe("Position comparison functions", () => { + let pos1: Position; + let pos2: Position; + let pos3: Position; + let pos4: Position; + + beforeAll(() => { + // Setup: Initializing positions + pos1 = { line: 1, character: 5 }; + pos2 = { line: 2, character: 3 }; + pos3 = { line: 1, character: 7 }; + pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality + }); + + describe("maxPosition", () => { + it("should return the position with the greater line number", () => { + expect(maxPosition(pos1, pos2)).toEqual(pos2); + }); + + it("should return the position with the greater character number when lines are equal", () => { + expect(maxPosition(pos1, pos3)).toEqual(pos3); + }); + + it("should return the first position when both positions are equal", () => { + expect(maxPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(maxPosition(posNegative, pos1)).toEqual(pos1); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); + }); + }); + + describe("minPosition", () => { + it("should return the position with the lesser line number", () => { + expect(minPosition(pos1, pos2)).toEqual(pos1); + }); + + it("should return the position with the lesser character number when lines are equal", () => { + expect(minPosition(pos1, pos3)).toEqual(pos1); + }); + + it("should return the first position when both positions are equal", () => { + expect(minPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(minPosition(posNegative, pos1)).toEqual(posNegative); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); + }); + }); +}); + +describe.skip("getRangeInString", () => { + let content: string; + + beforeEach(() => { + content = `Line 1 +Line 2 +Line 3 +Line 4 +Line 5`; + }); + + afterEach(() => { + content = ""; + }); + + test("should return substring within the same line", () => { + const range = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 4 }, + }; + expect(getRangeInString(content, range)).toBe("Line"); + }); + + test("should return substring spanning multiple lines", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 3, character: 3 }, + }; + const expected = `ne 2 +Line 3 +Line 4`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle range that starts and ends at the same character", () => { + const range = { + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe("L"); + }); + + test("should handle range that spans entire content", () => { + const range = { + start: { line: 0, character: 0 }, + end: { line: 4, character: 5 }, + }; + expect(getRangeInString(content, range)).toBe(content); + }); + + test("should handle range that spans to the end of the last line", () => { + const range = { + start: { line: 3, character: 2 }, + end: { line: 4, character: 5 }, + }; + const expected = `ne 4 +Line 5`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle empty content", () => { + content = ""; + const range = { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start line > end line)", () => { + const range = { + start: { line: 3, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start character > end character on same line)", () => { + const range = { + start: { line: 1, character: 5 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle range that starts and ends at the same line but different characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 6 }, + }; + expect(getRangeInString(content, range)).toBe("ne 2"); + }); + + test("should handle range that starts and ends at the same line and same characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe("n"); + }); +}); + +describe("intersection", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 4, character: 0 }, + }; + }); + + test("returns correct intersection for overlapping ranges", () => { + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 5 }, + }); + }); + + test("returns null for non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 3, character: 0 }, + end: { line: 4, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + // TODO + test.skip("returns correct intersection for single line overlap", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 2, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }); + }); + + test("returns null for single line non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 2 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + test("returns correct intersection when one range is fully within another", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 4, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }); + }); + + test("returns correct intersection when ranges touch at the edge", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 2, character: 0 }, + end: { line: 3, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }); + }); +}); diff --git a/core/util/reverseMessageIde.ts b/core/util/reverseMessageIde.ts index 1e5a2d1ca..a65f1f1f2 100644 --- a/core/util/reverseMessageIde.ts +++ b/core/util/reverseMessageIde.ts @@ -124,6 +124,11 @@ export class ReverseMessageIde { return this.ide.listFolders(); }); + this.on("getControlPlaneSessionInfo", async (msg) => { + // Not supported in testing + return undefined; + }); + this.on("getContinueDir", () => { return this.ide.getContinueDir(); }); diff --git a/core/util/tts.ts b/core/util/tts.ts new file mode 100644 index 000000000..248c38518 --- /dev/null +++ b/core/util/tts.ts @@ -0,0 +1,117 @@ +import os from "node:os"; +import { exec, ChildProcess } from "child_process"; +import type { IMessenger } from "./messenger"; +import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; + +// The amount of time before a process is declared +// a zombie after executing .kill() +const ttsKillTimeout: number = 5000; + +/** + * Removes code blocks from a message. + * + * Return modified message text. + */ +function removeCodeBlocks(msgText: string): string { + const codeBlockRegex = /```[\s\S]*?```/g; + + // Remove code blocks from the message text + const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, ""); + + return textWithoutCodeBlocks.trim(); +} + +/** + * Cleans a message text to safely be used in 'exec' context on host. + * + * Return modified message text. + */ +function sanitizeMessageForTTS(message: string): string { + message = removeCodeBlocks(message); + + // Remove or replace problematic characters + message = message + .replace(/"/g, "") + .replace(/`/g, "") + .replace(/\$/g, "") + .replace(/\\/g, "") + .replace(/[&|;()<>]/g, ""); + + message = message.trim().replace(/\s+/g, " "); + + return message; +} + +export class TTS { + static os: string | undefined = undefined; + static handle: ChildProcess | undefined = undefined; + static messenger: IMessenger; + + static async read(message: string) { + message = sanitizeMessageForTTS(message); + + try { + // Kill any active TTS processes + await TTS.kill(); + } catch (e) { + console.warn("Error killing TTS process: ", e); + return; + } + + switch (TTS.os) { + case "darwin": + TTS.handle = exec(`say "${message}"`); + break; + case "win32": + // Replace single quotes on windows + TTS.handle = exec( + `powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('${message.replace( + /'/g, + "''", + )}')"`, + ); + break; + case "linux": + TTS.handle = exec(`espeak "${message}"`); + break; + default: + console.log( + "Text-to-speech is not supported on this operating system.", + ); + return; + } + + TTS.messenger.request("setTTSActive", true); + + TTS.handle?.once("exit", () => { + TTS.messenger.request("setTTSActive", false); + }); + } + + static async kill(): Promise { + return new Promise((resolve, reject) => { + // Only kill a TTS process if it's still running + if (TTS.handle && TTS.handle.exitCode === null) { + // Use a timeout in case of zombie processes + let killTimeout: NodeJS.Timeout = setTimeout(() => { + reject(`Unable to kill TTS process: ${TTS.handle?.pid}`); + }, ttsKillTimeout); + + // Resolve our promise once the program has exited + TTS.handle.once("exit", () => { + clearTimeout(killTimeout); + TTS.handle = undefined; + resolve(); + }); + + TTS.handle.kill(); + } else { + resolve(); + } + }); + } + + static async setup() { + TTS.os = os.platform(); + } +} diff --git a/docs/docs/changelog.mdx b/docs/docs/changelog.mdx index 990953abe..3b703ce52 100644 --- a/docs/docs/changelog.mdx +++ b/docs/docs/changelog.mdx @@ -1,6 +1,6 @@ --- title: 📝 Changelog -description: Changelogs for the latest releases of the VSCode and IntelliJ extensions +description: Changelogs for the latest releases of the VSCode and JetBrains extensions keywords: [changelog] hide_table_of_contents: true --- @@ -8,7 +8,7 @@ hide_table_of_contents: true import VSCodeChangelog from "../../extensions/vscode/CHANGELOG.md"; import IntelliJChangelog from "../../extensions/intellij/CHANGELOG.md"; -Below are the changelogs for the latest releases of the VSCode and IntelliJ extensions. Prior to 2024-07-02, the changelogs do not reflect all updates. +Below are the changelogs for the latest releases of the VSCode and JetBrains extensions. Prior to 2024-07-02, the changelogs do not reflect all updates. import TOCInline from "@theme/TOCInline"; diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index 77d03b683..610e272a9 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -50,35 +50,13 @@ Type '@terminal' to reference the contents of your IDE's terminal. ### Documentation -Type `@docs` to index and retrieve snippets from any documentation site. You can add any site by selecting "Add Docs" in the dropdown, then entering the root URL of the documentation site and a title to remember it by. After the site has been indexed, you can type `@docs`, select your documentation from the dropdown, and Continue will use similarity search to automatically find important sections when answering your question. +Type `@docs` to index and retrieve snippets from any documentation site. ```json { "name": "docs" } ``` -Continue also pre-indexes a number of common sites, listed [here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). The embeddings for these sites are hosted by us, but downloaded for local use after the first time. All other indexing occurs entirely locally. - -#### Adding a Documentation Site via Configuration - -To add a documentation site via configuration, update the `config.json` file as follows: - -```json -{ - "name": "docs", - "params": { - "sites": [ - { - "title": "ExampleDocs", - "startUrl": "https://exampledocs.com/docs", - "rootUrl": "https://exampledocs.com", - "maxDepth": 3 // Default - } - ] - } -} -``` - -The docs are indexed when you modify the configuration file, unless indexing is disabled. If you want to manually trigger the indexing, you can use the command `Continue: Docs Index`. For force indexing, you can use the command `Continue: Docs Force Re-Index`. Note that these commands will work even if automatic indexing is disabled. +To learn more, visit [Talk To Your Docs](../features/talk-to-your-docs.md). ### Open Files diff --git a/docs/docs/features/quick-actions.md b/docs/docs/features/quick-actions.md index 7c6ce8887..a59f8e960 100644 --- a/docs/docs/features/quick-actions.md +++ b/docs/docs/features/quick-actions.md @@ -5,8 +5,6 @@ keywords: [experimental, automate, configuration] toc_max_heading_level: 5 --- -## Quick Actions (experimental, VS Code only) - Quick Actions streamline your development workflow by providing a tool to quickly select an entire class or function to perform a quick edit on. Configure custom actions to execute complex operations with a single click. ![Quick actions example](/img/quick-actions-demo.gif) diff --git a/docs/docs/features/tab-autocomplete.md b/docs/docs/features/tab-autocomplete.md index 1aef6cb6b..008358776 100644 --- a/docs/docs/features/tab-autocomplete.md +++ b/docs/docs/features/tab-autocomplete.md @@ -136,7 +136,7 @@ Follow these steps to ensure that everything is set up correctly: 2. Make sure you have downloaded Ollama. 3. Run `ollama run starcoder2: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. 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). +5. 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). 6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl+, then search for this and check the box) 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. diff --git a/docs/docs/features/talk-to-your-docs.md b/docs/docs/features/talk-to-your-docs.md new file mode 100644 index 000000000..d1088b4ea --- /dev/null +++ b/docs/docs/features/talk-to-your-docs.md @@ -0,0 +1,84 @@ +--- +title: Talk To Your Docs +description: Learn how to access and search your project's documentation directly within Continue +keywords: [documentation, indexing, context provider, embeddings] +toc_max_heading_level: 5 +--- + +The [`@docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. + +## Enabling the `@docs` context provider + +To enable the `@docs` context provider, you need to add it to the list of context providers in your `config.json` file. + +```json +{ + "contextProviders": [ + { "name": "docs" } + ... + ] +} +``` + +## How It Works + +The `@docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content. + +1. We crawl the specified documentation site +2. Generate embeddings for the content +3. Store the embeddings locally on your machine +4. Provide access to the indexed content through the `@docs` context provider + +## Pre-indexed Documentation Sites + +We offer a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). + +## Indexing Your Own Documentation + +### Through the `@docs` Context Provider + +To add a single documentation site, we recommend going through the `@docs` context provider. + +1. Type `@docs` in the chat panel, hit enter +2. Type "add" and select the "Add Docs" option +3. Enter the required information into the dialog + +Indexing will begin upon submission. + +### Through `config.json` + +To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save. + +The configuration schema is as follows: + +```json +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + "maxDepth": 3 + } +] +``` + +- `title`: The name of the documentation site, used for identification in the UI. +- `startUrl`: The URL where the indexing process should begin. +- `rootUrl`: The base URL of the documentation site, used to determine which pages to index. +- `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI. +- `maxDepth`: The maximum number of levels deep the indexer should crawl from the start URL. + +## FAQ + +### Why did my documentation site fail to index? + +Our current crawler is designed to work with static websites and may encounter issues with dynamic or JavaScript-heavy sites. If your documentation site failed to index, it's possible that it contains non-static elements that our crawler couldn't process. + +If you're experiencing issues with indexing a documentation site, please let us know. We're continuously improving our indexing capabilities and would appreciate your feedback to help us enhance the feature. + +Report Indexing Issues on Discord + +### How often is the indexed content updated? + +Currently we do not automatically re-index your docs. If you would like to force a re-index, you can use the following command: `Continue: Docs Force Re-Index`. diff --git a/docs/docs/how-to-use-continue.md b/docs/docs/how-to-use-continue.md index eb6a51fb0..8cbd23216 100644 --- a/docs/docs/how-to-use-continue.md +++ b/docs/docs/how-to-use-continue.md @@ -1,67 +1,85 @@ --- -title: 🧑‍🎓 How to use Continue -description: Using LLMs as you code with Continue +title: How to Use Continue +description: Utilizing LLMs (Large Language Models) as you code with Continue keywords: [how to, edit, refactor, boilerplate, context] --- -# 🧑‍🎓 How to use Continue +Continue is an advanced tool designed to help you integrate the power of Large Language Models (LLMs) seamlessly into your coding environment, providing assistance with understanding code, generating boilerplate, refactoring, and much more. Below are detailed instructions on how you can make the most out of Continue across different integrated development environments (IDEs) like VS Code and JetBrains. -## Easily understand code sections +## Easily Understand Code Sections + +If you ever find yourself puzzled by a piece of code, Continue can help break it down for you. This feature gives you a clear and concise explanation which can significantly speed up the debugging and understanding process. + +- **VS Code**: Press `cmd+L` (MacOS) or `ctrl+L` (Windows) to get insights into the current code section you are working on. +- **JetBrains**: Utilize the same feature with `cmd+J` (MacOS) or `ctrl+J` (Windows). ![understand](/img/understand.gif) -- VS Code: `cmd+L` (MacOS) / `ctrl+L` (Windows) -- JetBrains: `cmd+J` (MacOS) / `ctrl+J` (Windows) +## Tab to Autocomplete Code Suggestions -## Tab to autocomplete code suggestions +Autocomplete can save you time by predicting and inserting code snippets. Continue enhances this feature by using AI to offer smarter autocomplete suggestions tailored to your context. + +- **VS Code**: Simply press `tab` (MacOS) or `tab` (Windows) to autocomplete code suggestions. +- **JetBrains**: Similar functionality is available with the `tab` key on both MacOS and Windows. ![autocomplete](/img/autocomplete.gif) -- VS Code: `tab` (MacOS) / `tab` (Windows) -- JetBrains: `tab` (MacOS) / `tab` (Windows) +## Refactor Functions Where You are Coding -## Refactor functions where you are coding +Refactoring is a crucial part of maintaining and improving your code. With Continue, you can refactor functions right where you are coding, ensuring seamless transitions and minimal interruptions. + +- **VS Code**: Press `cmd+I` (MacOS) or `ctrl+I` (Windows) to refactor in place. +- **JetBrains**: Trigger the same action using `cmd+I` (MacOS) or `ctrl+I` (Windows). ![inline](/img/inline.gif) -- VS Code: `cmd+I` (MacOS) / `ctrl+I` (Windows) -- JetBrains: `cmd+I` (MacOS) / `ctrl+I` (Windows) +## Ask Questions About Your Codebase -## Ask questions about your codebase +Continue allows you to ask questions about your entire codebase, which can be extremely useful for getting quick answers and making informed decisions. + +- **VS Code**: Type `@codebase` followed by your query (works on both MacOS and Windows). +- **JetBrains**: This feature will be available soon. ![codebase](/img/codebase.gif) -- VS Code: `@codebase` (MacOS) / `@codebase` (Windows) -- JetBrains: Support coming soon +## Quickly Use Documentation as Context -## Quickly use documentation as context +Documentation can often be complex and time-consuming to scroll through. Continue can fetch the relevant sections for you, allowing you to use documentation as context efficiently. + +- **VS Code**: Use the `@docs` command (available on both MacOS and Windows). +- **JetBrains**: The same functionality is available using `@docs` on both MacOS and Windows. ![docs](/img/docs.gif) -- VS Code: `@docs` (MacOS) / `@docs` (Windows) -- JetBrains: `@docs` (MacOS) / `@docs` (Windows) +## Kick Off Actions with Slash Commands -## Kick off actions with slash commands +Slash commands in Continue enable you to perform various actions quickly and efficiently without having to leave your coding environment. + +- **VS Code**: Start commands with a `/` (works on both MacOS and Windows) like `/edit`. +- **JetBrains**: Support the use of slash commands by typing `/edit` on MacOS or Windows. ![slash](/img/slash.gif) -- VS Code: `/edit` (MacOS) / `/edit` (Windows) -- JetBrains: `/edit` (MacOS) / `/edit` (Windows) +Learn more about slash commands [here](./customization/slash-commands.md). -Learn more about slash commands [here](./customization/slash-commands.md) +## Add Classes, Files, and More to Context -## Add classes, files, and more to context +Context switching can disrupt your workflow. Continue allows you to add classes, files, and more to your current context, allowing you to see everything you need in one place. + +- **VS Code**: Use the `@files` command (available on both MacOS and Windows) for this purpose. +- **JetBrains**: This feature can also be utilized using `@files` on MacOS and Windows. ![classes](/img/classes.gif) -- VS Code: `@files` (MacOS) / `@files` (Windows) -- JetBrains: `@files` (MacOS) / `@files` (Windows) - Learn more about context providers [here](./customization/context-providers.md). -## Understand terminal errors immediately +## Understand Terminal Errors Immediately + +One of the most frustrating parts of coding is deciphering terminal errors. Continue can help you understand these errors instantly, reducing downtime and confusion. + +- **VS Code**: Press `cmd+shift+R` (MacOS) or `ctrl+shift+R` (Windows) for instant error explanations. +- **JetBrains**: This feature will be supported soon. ![error](/img/error.gif) -- VS Code: `cmd+shift+R` (MacOS) / `ctrl+shift+R` (Windows) -- JetBrains: Support coming soon \ No newline at end of file +By following these extended and detailed instructions, you can significantly improve your coding efficiency and debug processes using Continue. Happy coding! diff --git a/docs/docs/install/jetbrains.md b/docs/docs/install/jetbrains.md new file mode 100644 index 000000000..3ff9ac1fc --- /dev/null +++ b/docs/docs/install/jetbrains.md @@ -0,0 +1,110 @@ +--- +title: Installing Continue in JetBrains IDEs +description: Instructions for installing the Continue extension in JetBrains IDEs +keywords: [install, setup, jetbrains, plugin, continue, intellij, pycharm, webstorm] +--- + +## Prerequisites + +Ensure you have a compatible [JetBrains IDE](https://www.jetbrains.com/products/) installed. Continue is compatible with: + +- IntelliJ IDEA (Ultimate, Community) +- Android Studio +- AppCode +- Aqua +- CLion +- DataGrip +- DataSpell +- GoLand +- PhpStorm +- PyCharm (Professional, Community) +- Rider +- RubyMine +- RustRover +- WebStorm +- Writerside + +## Installation Options + +There are three ways to install the Continue extension in JetBrains IDEs: + +1. Install from JetBrains Marketplace within the IDE +2. Manual Installation from JetBrains Marketplace website +3. Manual Installation using ZIP from GitHub Releases + +Choose the method that best suits your preference and setup. Each option is detailed below. + +### Option 1: Install from JetBrains Marketplace within the IDE + +1. Open your JetBrains IDE. +2. Open the Settings/Preferences dialog (Ctrl+Alt+S on Windows/Linux, ⌘, on macOS). +3. Navigate to "Plugins" in the left sidebar. +4. Click on the "Marketplace" tab. +5. Search for "Continue" in the search bar. +6. Click the "Install" button next to the Continue plugin. +7. Restart your IDE when prompted to complete the installation. + +### Option 2: Manual Installation from JetBrains Marketplace website + +1. Visit the [Continue plugin page on the JetBrains Marketplace](https://plugins.jetbrains.com/plugin/22707-continue). +2. Click the "Get" button on the page. +3. Select your IDE from the list and click "Download". +4. Open your JetBrains IDE. +5. Open the Settings/Preferences dialog (Ctrl+Alt+S on Windows/Linux, ⌘, on macOS). +6. Navigate to "Plugins" in the left sidebar. +7. Click the gear icon and select "Install Plugin from Disk...". +8. Navigate to the downloaded plugin file and select it. +9. Restart your IDE when prompted to complete the installation. + +### Option 3: Manual Installation using ZIP from GitHub Releases + +1. Visit the [Continue GitHub releases page](https://github.com/continuedev/continue/releases). +2. Find the latest release and download the JetBrains ZIP file (e.g., `continue-jetbrains-[version].zip`). +3. Open your JetBrains IDE. +4. Open the Settings/Preferences dialog (Ctrl+Alt+S on Windows/Linux, ⌘, on macOS). +5. Navigate to "Plugins" in the left sidebar. +6. Click the gear icon and select "Install Plugin from Disk...". +7. Navigate to the downloaded ZIP file and select it. +8. Restart your IDE when prompted to complete the installation. + +## Post-Installation Setup + +1. After installation and IDE restart, you'll see the Continue icon in the right toolbar. +2. Click it to open the Continue tool window. + +![jetbrains-quickstart](/img/jetbrains-quickstart.png) + +## Getting Started with Continue + +Now that you've successfully installed Continue, you're ready to enhance your coding experience. Here's a quick summary of what you can do: + +1. **Open the Continue tool window**: Click the Continue icon in the right toolbar to access the extension's features. +2. **Start a conversation**: Use the chat interface to ask questions, get code suggestions, or request explanations. +3. **Explore features**: Familiarize yourself with Continue's features to streamline your workflow. +4. **Customize settings**: Adjust the plugin's settings to suit your preferences and coding style. + +For more detailed information on using Continue, check out our [user guide](../how-to-use-continue.md). + +## Pre-release Version (Optional) + +The Continue plugin for JetBrains IDEs offers a pre-release version through their Early Access Program (EAP) channel. To access the latest EAP version: + +1. Open your JetBrains IDE. +2. Open the Settings/Preferences dialog (Ctrl+Alt+S on Windows/Linux, ⌘, on macOS). +3. Navigate to "Plugins" in the left sidebar. +4. Click the gear icon at the top of the Plugins page. +5. Select "Manage Plugin Repositories...". +6. In the dialog that opens, add the URL to the list: `https://plugins.jetbrains.com/plugins/eap/list` +7. Click "OK" to save the changes. + +After adding the EAP channel, you'll be able to download the latest pre-release version of Continue from the marketplace. To install or update to the EAP version: + +1. Go back to the Plugins page in Settings/Preferences. +2. Search for "Continue" in the marketplace. +3. You should see the EAP version available. Click "Install" or "Update" to get the latest pre-release version. + +Remember that EAP versions may contain experimental features and could be less stable than the regular releases. + +## Troubleshooting + +If you encounter any issues, please refer to our [troubleshooting guide](../troubleshooting.md) or ask for help in [our Discord community](https://discord.gg/NWtdYexhMs). diff --git a/docs/docs/install/vscode.md b/docs/docs/install/vscode.md new file mode 100644 index 000000000..10114d9f1 --- /dev/null +++ b/docs/docs/install/vscode.md @@ -0,0 +1,77 @@ +--- +title: Installing Continue in VS Code +description: Instructions for installing the Continue extension in Visual Studio Code +keywords: [install, setup, vscode, extension, continue, vsix] +--- + +## Prerequisites + +Ensure you have Visual Studio Code installed. If not, download and install it from the [Visual Studio Code download page](https://code.visualstudio.com/download). + +## Installation Options + +There are three ways to install the Continue extension in Visual Studio Code: + +1. Install from VS Code Marketplace (Web) +2. Install from VS Code Extensions Marketplace +3. Manual Installation using VSIX + +Choose the method that best suits your preference and setup. Each option is detailed below. + +### Option 1: Install from VS Code Marketplace (Web) + +1. Visit the [Continue extension page on the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Continue.continue). +2. Click the `Install` button on the page. +3. This will open VS Code (if it's not already open) and take you to the extension page within VS Code. +4. Click `Install` in VS Code to complete the installation. + +### Option 2: Install from VS Code Extensions Marketplace + +1. Open Visual Studio Code. +2. Navigate to the Extensions view (Ctrl+Shift+X or Cmd+Shift+X). +3. Search for "Continue" in the marketplace. +4. Click `Install` next to the Continue extension. + +### Option 3: Manual Installation using VSIX + +1. Download the latest VSIX package from the [Continue GitHub repository](https://github.com/continuedev/continue/releases). +2. In VS Code, go to Extensions view. +3. Click on the "..." menu at the top of the Extensions sidebar. +4. Select `Install from VSIX...`. +5. Navigate to the downloaded VSIX file and select it. + +## Post-Installation Setup + +1. After installation, you'll see the Continue logo in the left sidebar. +2. Click it to open the Continue extension. +3. We recommend moving Continue to VS Code's right sidebar: + +![move-to-right-sidebar](/img/move-to-right-sidebar.png) + +This keeps the file explorer accessible while using Continue. + +## Getting Started with Continue + +Now that you've successfully installed Continue, you're ready to enhance your coding experience. Here's a quick summary of what you can do: + +1. **Open the Continue sidebar**: Click the Continue logo in the sidebar to access the extension's features. +2. **Start a conversation**: Use the chat interface to ask questions, get code suggestions, or request explanations. +3. **Explore commands**: Familiarize yourself with Continue's commands to streamline your workflow. +4. **Customize settings**: Adjust the extension's settings to suit your preferences and coding style. + +For more detailed information on using Continue, check out our [user guide](../how-to-use-continue.md). + +## Pre-release Version (Optional) + +The VS Code Continue extension is currently in beta. A pre-release version is available with the latest fixes and features. To install the pre-release version: + +1. Open Visual Studio Code. +2. Navigate to the Extensions view (Ctrl+Shift+X or Cmd+Shift+X). +3. Search for "Continue" in the installed extensions. +4. Select `Switch to Pre-release Version` from the menu. + +![Pre-Release](../../static/img/prerelease.png) + +## Troubleshooting + +If you encounter any issues, please refer to our [troubleshooting guide](.././troubleshooting.md) or ask for help in [our Discord community](https://discord.gg/NWtdYexhMs). diff --git a/docs/docs/intro.md b/docs/docs/intro.md index e21f85be8..4fed466be 100644 --- a/docs/docs/intro.md +++ b/docs/docs/intro.md @@ -1,24 +1,36 @@ --- -title: 💻 Introduction -description: Continue is the open-source autopilot for software development -keywords: [introduction, intro, continue, autopilot, chatgpt] +title: Introduction +description: The open-source AI code assistant for developers +keywords: [continue, AI, code assistant, autocomplete, chat, VS Code, JetBrains] --- -# 💻 Introduction +![Continue Logo](/img/intro.png) -![continue-cover-logo](/img/intro.png) +## The Open-Source AI Code Assistant -**Continue is the leading open-source AI code assistant. You can connect any models and any context to build custom autocomplete and chat experiences inside [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)** +Continue is the leading open-source AI code assistant, designed to enhance your development workflow. It seamlessly integrates with popular IDEs like [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension), providing custom autocomplete and chat experiences. -Some examples of what you can achieve are: +### Key Features -- [Easily understand code sections](how-to-use-continue.md#easily-understand-code-sections) -- [Tab to autocomplete code suggestions](how-to-use-continue.md#tab-to-autocomplete-code-suggestions) -- [Refactor functions where you are coding](how-to-use-continue.md#refactor-functions-where-you-are-coding) -- [Ask questions about your codebase](how-to-use-continue.md#ask-questions-about-your-codebase) -- [Quickly use documentation as context](how-to-use-continue.md#quickly-use-documentation-as-context) -- [Kick off actions with slash commands](how-to-use-continue.md#kick-off-actions-with-slash-commands) -- [Add classes, files, and more to context](how-to-use-continue.md#add-classes-files-and-more-to-context) -- [Understand terminal errors immediately](how-to-use-continue.md#understand-terminal-errors-immediately) +- **Flexible Model Integration**: Use any AI model, whether open-source or commercial, local or remote. +- **Versatile Applications**: Ideal for chat, autocomplete, and embeddings. +- **Highly Customizable**: Configure to fit your existing workflows. -Continue enables you to use the right model for the job, whether it's open-source or commercial, running local or remote, and used for chat, autocomplete, or embeddings. And we provide numerous points of configuration, so that you can customize the extension to fit into your existing workflows. +### What You Can Do with Continue + +1. [Understand code sections easily](how-to-use-continue.md#easily-understand-code-sections) +2. [Autocomplete code with tab](how-to-use-continue.md#tab-to-autocomplete-code-suggestions) +3. [Refactor functions in-place](how-to-use-continue.md#refactor-functions-where-you-are-coding) +4. [Query your codebase](how-to-use-continue.md#ask-questions-about-your-codebase) +5. [Leverage documentation as context](how-to-use-continue.md#quickly-use-documentation-as-context) +6. [Use slash commands for quick actions](how-to-use-continue.md#kick-off-actions-with-slash-commands) +7. [Add various elements to context](how-to-use-continue.md#add-classes-files-and-more-to-context) +8. [Instantly understand terminal errors](how-to-use-continue.md#understand-terminal-errors-immediately) + +Explore these features to supercharge your development process with Continue! + +## See Continue in Action + +
+ +
diff --git a/docs/docs/reference/Model Providers/assets/Watsonx1.gif b/docs/docs/reference/Model Providers/assets/Watsonx1.gif index 4d12fd7b4..e37443ad6 100644 Binary files a/docs/docs/reference/Model Providers/assets/Watsonx1.gif and b/docs/docs/reference/Model Providers/assets/Watsonx1.gif differ diff --git a/docs/docs/reference/Model Providers/azure.md b/docs/docs/reference/Model Providers/azure.md index 1f1518c92..7ae359910 100644 --- a/docs/docs/reference/Model Providers/azure.md +++ b/docs/docs/reference/Model Providers/azure.md @@ -15,20 +15,21 @@ You can configure Azure OpenAI service through the UI, or you can configure it m ```json title="~/.continue/config.json" "models": [{ "title": "Azure OpenAI", - "provider": "openai", + "provider": "azure", "model": "", "apiBase": "", "engine": "", "apiVersion": "", - "apiType": "azure", + "apiType": "openai", "apiKey": "" }] ``` -To find out the information from *Azure AI Studio*, select the model that you would like to connect. Under the *Endpoint* section and capture the Target URI. +To find out the information from _Azure AI Studio_, select the model that you would like to connect. Under the _Endpoint_ section and capture the Target URI. For example, Target URI of https://just-an-example.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2023-13-15-preview Maps to: -* model = gpt-4o -* engine = gpt-4o -* apiVersion = 2023-13-15-preview -* apiBase = just-an-example.openai.azure.com + +- model = gpt-4o +- engine = gpt-4o +- apiVersion = 2023-13-15-preview +- apiBase = just-an-example.openai.azure.com diff --git a/docs/docs/reference/Model Providers/bedrock.md b/docs/docs/reference/Model Providers/bedrock.md index daac562af..d720de66f 100644 --- a/docs/docs/reference/Model Providers/bedrock.md +++ b/docs/docs/reference/Model Providers/bedrock.md @@ -1,4 +1,4 @@ -# AWS Bedrock +# AWS Bedrock To setup Bedrock, add the following to your `config.json` file: @@ -9,18 +9,19 @@ To setup Bedrock, add the following to your `config.json` file: "title": "Bedrock: Claude 3 Sonnet", "provider": "bedrock", "model": "anthropic.claude-3-sonnet-20240229-v1:0", - "region": "us-east-1" + "region": "us-east-1", + "profile": "bedrock", } ] } ``` -Authentication will be through temporary or long-term credentials in -~/.aws/credentials under a profile called "bedrock". +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). ```title="~/.aws/credentials [bedrock] aws_access_key_id = abcdefg aws_secret_access_key = hijklmno -aws_session_token = pqrstuvwxyz # Optional: means short term creds. +aws_session_token = pqrstuvwxyz # Optional: means short term creds. ``` diff --git a/docs/docs/reference/Model Providers/bedrockimport.md b/docs/docs/reference/Model Providers/bedrockimport.md new file mode 100644 index 000000000..6a8c50d68 --- /dev/null +++ b/docs/docs/reference/Model Providers/bedrockimport.md @@ -0,0 +1,28 @@ +# AWS Bedrock Custom Imported Models + +To setup Bedrock using custom imported models, add the following to your `config.json` file: + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "AWS Bedrock deepseek-coder-6.7b-instruct", + "provider": "bedrockimport", + "model": "deepseek-coder-6.7b-instruct", + "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX", + "region": "us-west-2", + "profile": "bedrock" + } + ] +} +``` + +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). + +```title="~/.aws/credentials +[bedrock] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` diff --git a/docs/docs/reference/Model Providers/kindo.md b/docs/docs/reference/Model Providers/kindo.md new file mode 100644 index 000000000..442e30b10 --- /dev/null +++ b/docs/docs/reference/Model Providers/kindo.md @@ -0,0 +1,42 @@ +# Kindo +Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create your API key on the [API keys page](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the [plugins tab](https://app.kindo.ai/plugins). + +## Config Example + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "kindo", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "" + } + ] +} +``` + +## Tab Autocomplete Config Example + +```json title="~/.continue/config.json" +{ + "tabAutocompleteModel": [ + { + "title": "WhiteRabbitNeo", + "provider": "kindo", + "model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder", + "apiKey": "" + }, + { + "title": "DeepSeek", + "provider": "kindo", + "model": "deepseek-ai/deepseek-coder-33b-instruct", + "apiKey": "" + } + ] +} +``` + +## Security + +To update your organization's model access, adjust the controls in [security settings](https://app.kindo.ai/security-settings). \ No newline at end of file diff --git a/docs/docs/reference/Model Providers/llamafile.md b/docs/docs/reference/Model Providers/llamafile.md index 04d12aeff..cc969f8d8 100644 --- a/docs/docs/reference/Model Providers/llamafile.md +++ b/docs/docs/reference/Model Providers/llamafile.md @@ -14,6 +14,4 @@ A [llamafile](https://github.com/Mozilla-Ocho/llamafile#readme) is a self-contai } ``` -Optionally, you can set the `llamafile_command` property, which will be run to start the llamafile if it isn't already running on port 8080. Be sure to use an absolute path to the llamafile binary. For example: `/Users/yourusername/mistral-7b-instruct-v0.1-Q4_K_M-server.llamafile`. - [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Llamafile.ts) diff --git a/docs/docs/reference/Model Providers/openrouter.md b/docs/docs/reference/Model Providers/openrouter.md index 5f2558399..eabc291bb 100644 --- a/docs/docs/reference/Model Providers/openrouter.md +++ b/docs/docs/reference/Model Providers/openrouter.md @@ -2,14 +2,14 @@ OpenRouter is a unified interface for commercial and open-source models, giving you access to the best models at the best prices. You can sign up [here](https://openrouter.ai/signup), create your API key on the [keys page](https://openrouter.ai/keys), and then choose a model from the [list of supported models](https://openrouter.ai/models). -Change `~/.continue/config.json` to look like the following. Since OpenRouter is fully API compatible with OpenAI, it is recommended to stick with `"provider": "openai"`, even if they aren't necessarily the upstream provider. +Change `~/.continue/config.json` to look like the following. ```json title="~/.continue/config.json" { "models": [ { "title": "OpenRouter LLaMA 70 8B", - "provider": "openai", + "provider": "openrouter", "model": "meta-llama/llama-3-70b-instruct", "apiBase": "https://openrouter.ai/api/v1", "apiKey": "..." diff --git a/docs/docs/reference/Model Providers/textgenwebui.md b/docs/docs/reference/Model Providers/textgenwebui.md index f52e44219..1aee87049 100644 --- a/docs/docs/reference/Model Providers/textgenwebui.md +++ b/docs/docs/reference/Model Providers/textgenwebui.md @@ -7,7 +7,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. "models": [ { "title": "Text Generation WebUI", - "provider": "openai", + "provider": "text-gen-webui", "apiBase": "http://localhost:5000", "model": "MODEL_NAME" } diff --git a/docs/docs/reference/Model Providers/watsonx.md b/docs/docs/reference/Model Providers/watsonx.md index b6a239946..9e2a345d4 100644 --- a/docs/docs/reference/Model Providers/watsonx.md +++ b/docs/docs/reference/Model Providers/watsonx.md @@ -1,15 +1,38 @@ -# Watsonx +# IBM watsonx -Watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks. +watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks. ## Setup -To access the Watsonx models, create an instance in the [IBM cloud](https://cloud.ibm.com) which supports watsonx studio. Then to create a project refer [this](https://www.ibm.com/docs/en/watsonx/saas?topic=projects-creating-project). +Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or using a dedicated watsonx.ai Software instance. -You can set it up in two different ways : -1. **Using API** : Create Your IBM cloud API key by referring [this](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). -2. **Using Credentials** : Use your Username and Password to authenticate +### watsonx.ai SaaS - IBM Cloud +To get started with watsonx SaaS, visit the [registration page](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx). If you do not have an existing IBM Cloud account, you can sign up for a free trial. + +To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [setup an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue: +- Set **watsonx URL** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region. +- Set **watsonx Project ID** to your watsonx project ID. +- Set **watsonx API Key** to your watsonx API Key. + +### watsonx.ai Software + +To authenticate to your watsonx.ai Software instance with Continue, you can use either `username/password` or `ZenApiKey` method: +1. *Option 1* (Recommended): using `ZenApiKey` authentication: + - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **watsonx Project ID** to your watsonx project ID. + - Set **watsonx API Key** to your watsonx Zen API Key. To generate it: + 1. Log in to the CPD web client. + 2. From the toolbar, click your avatar. + 3. Click **Profile and settings**. + 4. Click **API key** > **Generate new key**. + 5. Click **Generate**. + 6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it. + 7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo ":" | base64`, replacing `` with your CPD username and `` with the API Key you just created. +2. *Option 2*: using `username/password` authentication: + - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **watsonx Project ID** to your watsonx project ID. + - Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format. ## Usage -![usage-gif](../Model%20Providers/assets/Watsonx1.gif) \ No newline at end of file +![usage-gif](../Model%20Providers/assets/watsonx1.gif) diff --git a/docs/docs/setup/model-providers.md b/docs/docs/setup/model-providers.md index ab774d242..3175da802 100644 --- a/docs/docs/setup/model-providers.md +++ b/docs/docs/setup/model-providers.md @@ -46,7 +46,7 @@ You can run a model on your local computer using: - [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) (OpenAI compatible server) - [IPEX-LLM](../reference/Model%20Providers/ipex_llm.md) (Local LLM on Intel GPU) - [Msty](../reference/Model%20Providers/msty.md) -- [Watsonx](../reference/Model%20Providers/watsonx.md) +- [IBM watsonx](../reference/Model%20Providers/watsonx.md) - [Nvidia NIMS](../reference/Model%20Providers/openai.md) (OpenAI compatible server) ### Remote @@ -63,6 +63,7 @@ You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-co You can access both open-source and commercial LLMs via: - [OpenRouter](../reference/Model%20Providers/openrouter.md) +- [Kindo](../reference/Model%20Providers/kindo.md) ### Open-source models diff --git a/docs/docs/setup/overview.md b/docs/docs/setup/overview.md index d8c1bc8dc..23bae96cd 100644 --- a/docs/docs/setup/overview.md +++ b/docs/docs/setup/overview.md @@ -1,13 +1,54 @@ +--- +title: Overview +description: Get started with Continue and tailor it to your needs +keywords: [setup, customization, models, configuration, LLMs] +--- + # Overview -Continue gives you choice over what [Large Language Models (LLMs)](https://www.youtube.com/watch?v=zjkBMFhNj_g) you use. You can use it with commercial models like Claude 3 Opus via the Anthropic API, open-source models like Llama 3 running on your laptop with Ollama, and everything in between. +Continue is a flexible AI coding assistant that allows you to choose and customize your Large Language Models (LLMs). This guide will help you get started and make Continue work best for you. -When you first install Continue, you can try it out for free using a proxy server that securely makes calls with our API keys. Once you're ready to use your own API keys or different models / providers, you can add them to the `config.json`. +## Quick Start -You will need to decide which models and providers you use for [chat](select-model.md#chat), [autocomplete](select-model.md#autocomplete), and [embeddings](select-model.md#embeddings). +1. When you first install Continue, you can use it immediately with our free proxy server. +2. As you get familiar with Continue, you can set up your own API keys and customize your experience. -Learn more: +## Choosing Your Models -- [Configuration](configuration.md) -- [Model Providers](model-providers.md) -- [Select models](select-model.md) +Continue works with a variety of LLMs: + +- Commercial models (e.g., Claude 3 Opus via Anthropic API) +- Open-source models (e.g., Llama 3 running locally with Ollama) +- And many options in between + +You'll need to select models for three main functions: + +- [Chat](select-model.md#chat) +- [Autocomplete](select-model.md#autocomplete) +- [Embeddings](select-model.md#embeddings) + +## Customization Options + +Continue offers deep customization through `config.json` and `config.ts` files. These are located in: + +- MacOS: `~/.continue/` +- Windows: `%userprofile%\.continue` + +You can customize: + +1. [Basic Configuration](configuration.md) +2. [Model Providers](model-providers.md) +3. [Model Selection](select-model.md) +4. [Context Providers](../customization/context-providers.md) +5. [Slash Commands](../customization/slash-commands.md) +6. [Advanced Options](../reference/config.mdx) + +## Sharing Your Configuration + +To share your Continue setup with a team: + +1. Create a `.continuerc.json` file in your project's root directory. +2. Use the same JSON Schema as `config.json`. +3. This file will automatically apply on top of the local `config.json`. + +Get started with Continue today and shape it to fit your coding workflow perfectly! diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index f330345a7..44742c0de 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -1,12 +1,16 @@ --- -title: ❓ Troubleshooting +title: Troubleshooting description: Troubleshooting while waiting for help during beta / alpha testing keywords: [reload, delete, manually, logs, server, console] --- -# ❓ Troubleshooting +The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below. -The Continue VS Code extension is currently in beta, and the Intellij extension is in Alpha. If you are having trouble, please follow the steps below. +1. [Check the logs](#check-the-logs) +2. [Try the latest pre-release](#download-the-latest-pre-release) +3. [Download an older version](#download-an-older-version) +4. [Resolve keyboard shortcut issues](#keyboard-shortcuts-not-resolving) +5. [Check FAQs for common issues](#faqs) ## Check the logs @@ -32,7 +36,7 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c ### JetBrains -Open `~/.continue/core.log`. The most recent logs are found at the bottom of the file. +Open `~/.continue/logs/core.log`. The most recent logs are found at the bottom of the file. ## Download the latest pre-release @@ -49,7 +53,7 @@ On JetBrains, the "pre-release" happens through their Early Access Program (EAP) 1. Open JetBrains settings (cmd/ctrl+,) and go to "Plugins" 2. Click the gear icon at the top 3. Select "Manage Plugin Repositories..." -4. Add "https://plugins.jetbrains.com/plugins/eap/list" to the list +4. Add "[https://plugins.jetbrains.com/plugins/eap/list>](https://plugins.jetbrains.com/plugins/eap/list>)" to the list 5. You'll now always be able to download the latest EAP version from the marketplace ## Download an Older Version @@ -108,6 +112,12 @@ By default the Continue window is on the left side of VS Code, but it can be dra If you have entered a valid API key and model, but are still getting a 404 error from OpenAI, this may be because you need to add credits to your billing account. You can do so from the [billing console](https://platform.openai.com/settings/organization/billing/overview). If you just want to check that this is in fact the cause of the error, you can try adding $1 to your account and checking whether the error persists. +### Indexing issues + +If you are having persistent errors with indexing, our recommendation is to rebuild your index from scratch. Note that for large codebases this may take some time. + +This can be accomplished using the following command: `Continue: Rebuild codebase index`. + ## Still having trouble? -Create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), leaving the details of your problem, and we'll be able to more quickly help you out. +You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly. diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index e6ec86dcd..006981beb 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -82,6 +82,12 @@ const config = { position: "left", label: "Docs", }, + { + type: "docSidebar", + sidebarId: "referenceSidebar", + position: "left", + label: "Reference", + }, { to: "https://github.com/continuedev/continue", label: "GitHub", diff --git a/docs/package-lock.json b/docs/package-lock.json index 68e4cd8fa..7387674fb 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -19,7 +19,8 @@ "react-dom": "^18.2.0" }, "devDependencies": { - "@docusaurus/module-type-aliases": "^3.2.1" + "@docusaurus/module-type-aliases": "^3.2.1", + "nodemon": "^3.1.4" }, "engines": { "node": ">=20.11.0" @@ -7534,6 +7535,12 @@ "node": ">= 4" } }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", + "dev": true + }, "node_modules/image-size": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.1.1.tgz", @@ -10569,6 +10576,55 @@ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==" }, + "node_modules/nodemon": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.4.tgz", + "integrity": "sha512-wjPBbFhtpJwmIeY2yP7QF+UKzPfltVGtfce1g/bB15/8vCGZj8uxD62b/b9M9/WVgme0NZudpownKN+c0plXlQ==", + "dev": true, + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nodemon/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/nodemon/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -11739,6 +11795,12 @@ "node": ">= 0.10" } }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "dev": true + }, "node_modules/punycode": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", @@ -13057,6 +13119,18 @@ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dev": true, + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/sirv": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/sirv/-/sirv-2.0.4.tgz", @@ -13628,6 +13702,15 @@ "node": ">=6" } }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "dev": true, + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, "node_modules/trim-lines": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", @@ -13714,6 +13797,12 @@ "node": ">=14.17" } }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "dev": true + }, "node_modules/undici-types": { "version": "5.26.5", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", diff --git a/docs/package.json b/docs/package.json index d37e79266..3e212827e 100644 --- a/docs/package.json +++ b/docs/package.json @@ -5,7 +5,7 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "start": "docusaurus start", + "start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec 'docusaurus start'", "build": "docusaurus build", "build:netlify": "docusaurus build --out-dir build/docs", "swizzle": "docusaurus swizzle", @@ -27,7 +27,8 @@ "react-dom": "^18.2.0" }, "devDependencies": { - "@docusaurus/module-type-aliases": "^3.2.1" + "@docusaurus/module-type-aliases": "^3.2.1", + "nodemon": "^3.1.4" }, "browserslist": { "production": [ @@ -45,4 +46,4 @@ "engines": { "node": ">=20.11.0" } -} +} \ No newline at end of file diff --git a/docs/sidebars.js b/docs/sidebars.js index 84493e2bd..b569b31d8 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -14,9 +14,39 @@ /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ const sidebars = { docsSidebar: [ - "intro", - "quickstart", - "how-to-use-continue", + { + type: "category", + label: "🚀 Install", + collapsible: true, + collapsed: true, + items: [ + { + type: "doc", + id: "intro", + label: "Introduction", + }, + { + type: "doc", + id: "install/vscode", + label: "VS Code", + }, + { + type: "doc", + id: "install/jetbrains", + label: "JetBrains", + }, + { + type: "doc", + id: "how-to-use-continue", + label: "How to use Continue", + }, + { + type: "doc", + id: "troubleshooting", + label: "Troubleshooting", + }, + ], + }, { type: "category", label: "🌉 Setup", @@ -31,25 +61,25 @@ const sidebars = { }, { type: "category", - label: "🎨 Customization", - collapsible: true, - collapsed: true, - items: [ - "customization/overview", - "customization/context-providers", - "customization/slash-commands", - ], - }, - { - type: "category", - label: "🪄 Features", + label: "⭐ Features", collapsible: true, collapsed: true, items: [ "features/codebase-embeddings", + "features/talk-to-your-docs", "features/tab-autocomplete", - "features/prompt-files", - "features/quick-actions", + "customization/context-providers", + "customization/slash-commands", + { + type: "doc", + id: "features/prompt-files", + label: "Prompt Files (experimental)", + }, + { + type: "doc", + id: "features/quick-actions", + label: "Quick Actions (experimental)", + }, ], }, { @@ -68,27 +98,29 @@ const sidebars = { "development-data", "telemetry", { - type: 'link', - label: 'Privacy Policy', - href: 'https://www.continue.dev/privacy', - }, - ], - }, - "troubleshooting", - { - type: "category", - label: "📖 Reference", - collapsible: true, - collapsed: true, - items: [ - { - type: "autogenerated", - dirName: "reference", + type: "link", + label: "Privacy Policy", + href: "https://www.continue.dev/privacy", }, ], }, "changelog", ], + referenceSidebar: [ + "reference/config", + { + type: "category", + label: "LLM Providers", + collapsible: true, + collapsed: true, + items: [ + { + type: "autogenerated", + dirName: "reference/Model Providers", + }, + ], + }, + ], }; module.exports = sidebars; diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 180454880..da74c837e 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -189,7 +190,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -197,6 +199,8 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -214,7 +218,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, @@ -239,6 +244,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", @@ -1223,13 +1233,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2374,7 +2378,19 @@ "defaultContext": { "type": "array", "items": { - "enum": ["activeFile"] + "allOf": [ + { + "$ref": "#/definitions/ContextProviderWithParams" + }, + { + "properties": { + "query": { + "type": "string", + "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." + } + } + } + ] } }, "modelRoles": { @@ -2385,6 +2401,11 @@ } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index e3eba0461..ac38ac9fc 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -37,6 +37,7 @@ dependencies { implementation("io.ktor:ktor-server-cors:2.3.7"){ exclude(group = "org.slf4j", module = "slf4j-api") } + implementation("com.posthog.java:posthog:1.+") } @@ -142,6 +143,9 @@ tasks { // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels = properties("pluginVersion").map { listOf(it.split('-').getOrElse(1) { "default" }.split('.').first()) } + channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap"))) + + // We always hide the stable releases until a few days of EAP have proven them stable + hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false) } } diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index cb39f4eee..723551552 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.59 +pluginVersion = 0.0.62 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 444a4d397..caf9b4720 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -9,6 +9,7 @@ import com.github.continuedev.continueintellijextension.listeners.ContinuePlugin import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.services.SettingsListener +import com.github.continuedev.continueintellijextension.services.TelemetryService import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.application.ApplicationManager @@ -206,22 +207,21 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { val targetPath = Paths.get(corePath, target).toString() val continueCorePath = Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString() - // Copy targetPath / node_sqlite3.node to core / node_sqlite3.node - val nodeSqlite3Path = Paths.get(targetPath, "node_sqlite3.node") - - // Create the build/Release path first - File(Paths.get(corePath, "build", "Release").toString()).mkdirs() - - val coreNodeSqlite3Path = Paths.get(corePath, "build", "Release", "node_sqlite3.node") - if (!File(coreNodeSqlite3Path.toString()).exists()) { - Files.copy(nodeSqlite3Path, coreNodeSqlite3Path) - } - // esbuild needs permissions val esbuildPath = Paths.get(targetPath, "esbuild"+ (if (os == "win32") ".exe" else "")).toString() val coreMessenger = CoreMessenger(project, esbuildPath, continueCorePath, ideProtocolClient) continuePluginService.coreMessenger = coreMessenger + + coreMessenger.request("config/getSerializedProfileInfo", null, null) { resp -> + val data = resp as? Map + val profileInfo = data?.get("config") as? Map + val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean + val telemetryService = service() + if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { + telemetryService.setup(getMachineUniqueID()) + } + } } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index ded887c76..80ec73b70 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -1,15 +1,12 @@ package com.github.continuedev.continueintellijextension.`continue` + import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import java.io.BufferedReader -import java.io.InputStreamReader -import java.io.OutputStreamWriter - -import java.io.* - +import com.github.continuedev.continueintellijextension.services.TelemetryService import com.google.gson.Gson import com.intellij.openapi.components.service import com.intellij.openapi.project.Project +import java.io.* import java.net.Socket import java.nio.charset.StandardCharsets import java.nio.file.Files @@ -238,9 +235,24 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) process!!.onExit().thenRun { - val err = process?.errorStream?.bufferedReader()?.readText()?.trim() + var err = process?.errorStream?.bufferedReader()?.readText()?.trim() + if (err != null) { + // There are often "⚡️Done in Xms" messages, and we want everything after the last one + val delimiter = "⚡️Done in" + val doneIndex = err.lastIndexOf(delimiter) + if (doneIndex != -1) { + err = err.substring(doneIndex + delimiter.length) + } + } + println("Core process exited with output: $err") ideProtocolClient.showMessage("Core process exited with output: $err") + + // Log the cause of the failure + val telemetryService = service() + telemetryService.capture("jetbrains_core_exit", mapOf( + "error" to err + )) } Thread { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index e8aa27b6c..cead14fbf 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -31,6 +31,7 @@ import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor +import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbAware @@ -44,6 +45,8 @@ import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.awt.RelativePoint +import com.intellij.ui.content.ContentManagerUtil +import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.* import java.awt.Toolkit import java.awt.datatransfer.StringSelection @@ -605,8 +608,10 @@ class IdeProtocolClient ( respond(currentFile) } "getPinnedFiles" -> { - val openFiles = visibleFiles() - respond(openFiles) + ApplicationManager.getApplication().invokeLater { + val pinnedFiles = pinnedFiles() + respond(pinnedFiles) + } } "insertAtCursor" -> { val msg = data as Map; @@ -964,6 +969,14 @@ class IdeProtocolClient ( return fileEditorManager.openFiles.toList().map { it.path } } + @RequiresEdt + private fun pinnedFiles(): List { + val fileEditorManager = FileEditorManager.getInstance(project) as? FileEditorManagerImpl ?: return listOf() + val openFiles = fileEditorManager.openFiles.map { it.path }.toList() + val pinnedFiles = fileEditorManager.windows.flatMap { window -> window.files.filter { window.isFilePinned(it) } }.map { it.path }.toSet() + return openFiles.intersect(pinnedFiles).toList() + } + private fun currentFile(): String? { val fileEditorManager = FileEditorManager.getInstance(project) val editor = fileEditorManager.selectedTextEditor diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index e974cf8fd..1ec77b738 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -195,7 +195,7 @@ class InlineEditAction : AnAction(), DumbAware { background = GetTheme().getSecondaryDark() maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) margin = JBUI.insets(8) - font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) } textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) @@ -260,7 +260,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List isEditable = true background = defaultBackground foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) isOpaque = false isEditable = false @@ -315,7 +315,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List isEditable = true background = defaultBackground foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) isOpaque = false isEditable = false @@ -352,7 +352,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply { val leftLabel = JLabel("Enter follow-up instructions").apply { foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) } val leftButton = CustomButton("${getAltKeyLabel()}⇧N") { onReject() }.apply { @@ -445,7 +445,7 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { }) // verticalAlignment = CENTER - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) } override fun paintComponent(g: Graphics) { @@ -477,7 +477,7 @@ class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { // Draw placeholder if (text.isEmpty()) { g.color = Color(128, 128, 128, 255) - g.font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE) + g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) g.drawString("Enter instructions to edit highlighted code", 8, 20) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt new file mode 100644 index 000000000..5b7f00678 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/TelemetryService.kt @@ -0,0 +1,28 @@ +package com.github.continuedev.continueintellijextension.services + +import com.intellij.openapi.components.Service +import com.posthog.java.PostHog +import com.posthog.java.PostHog.Builder + +@Service +class TelemetryService { + private val POSTHOG_API_KEY = "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs" + private var posthog: PostHog? = null; + private var distinctId: String? = null; + + fun setup(distinctId: String) { + this.posthog = Builder(POSTHOG_API_KEY).host("https://app.posthog.com").build() + this.distinctId = distinctId + } + + fun capture(eventName: String, properties: Map) { + if (this.posthog == null || this.distinctId == null) { + return; + } + this.posthog?.capture(this.distinctId, eventName, properties) + } + + fun shutdown() { + this.posthog?.shutdown() + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 180454880..da74c837e 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -189,7 +190,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -197,6 +199,8 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -214,7 +218,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, @@ -239,6 +244,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", @@ -1223,13 +1233,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2374,7 +2378,19 @@ "defaultContext": { "type": "array", "items": { - "enum": ["activeFile"] + "allOf": [ + { + "$ref": "#/definitions/ContextProviderWithParams" + }, + { + "properties": { + "query": { + "type": "string", + "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." + } + } + } + ] } }, "modelRoles": { @@ -2385,6 +2401,11 @@ } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 180454880..da74c837e 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -189,7 +190,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -197,6 +199,8 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -214,7 +218,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, @@ -239,6 +244,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", @@ -1223,13 +1233,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2374,7 +2378,19 @@ "defaultContext": { "type": "array", "items": { - "enum": ["activeFile"] + "allOf": [ + { + "$ref": "#/definitions/ContextProviderWithParams" + }, + { + "properties": { + "query": { + "type": "string", + "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." + } + } + } + ] } }, "modelRoles": { @@ -2385,6 +2401,11 @@ } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index fcbba3140..1fea6afb5 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -174,6 +174,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -192,7 +193,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -200,6 +202,8 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -217,7 +221,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, @@ -242,6 +247,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", @@ -2669,8 +2679,18 @@ "defaultContext": { "type": "array", "items": { - "enum": [ - "activeFile" + "allOf": [ + { + "$ref": "#/definitions/ContextProviderWithParams" + }, + { + "properties": { + "query": { + "type": "string", + "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." + } + } + } ] } }, @@ -2682,6 +2702,11 @@ } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e8a3b9674..b4a4dab39 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.196", + "version": "0.9.199", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.196", + "version": "0.9.199", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -108,7 +108,6 @@ "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", @@ -130,8 +129,11 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", + "puppeteer": "^22.4.0", + "puppeteer-chromium-resolver": "^23.0.0", "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 64ce17a70..a87c6ac3c 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.8.46", + "version": "0.9.199", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -174,7 +174,7 @@ { "command": "continue.debugTerminal", "category": "Continue", - "title": "Continue: Debug Terminal", + "title": "Debug Terminal", "group": "Continue" }, { @@ -199,7 +199,7 @@ { "command": "continue.selectFilesAsContext", "category": "Continue", - "title": "Continue: Select Files as Context", + "title": "Select Files as Context", "group": "Continue" }, { @@ -252,6 +252,12 @@ "title": "Codebase Force Re-Index", "group": "Continue" }, + { + "command": "continue.rebuildCodebaseIndex", + "category": "Continue", + "title": "Rebuild codebase index", + "group": "Continue" + }, { "command": "continue.docsIndex", "category": "Continue", @@ -276,11 +282,6 @@ "mac": "cmd+shift+l", "key": "ctrl+shift+l" }, - { - "command": "continue.toggleAuxiliaryBar", - "mac": "alt+cmd+l", - "key": "alt+ctrl+l" - }, { "command": "continue.acceptDiff", "mac": "shift+cmd+enter", diff --git a/extensions/vscode/scripts/prepackage-cross-platform.js b/extensions/vscode/scripts/prepackage-cross-platform.js index 59089dd62..018ea70c2 100644 --- a/extensions/vscode/scripts/prepackage-cross-platform.js +++ b/extensions/vscode/scripts/prepackage-cross-platform.js @@ -24,6 +24,7 @@ const { copySqliteBinary, installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, + copyTokenizers, } = require("./utils"); // Clear folders that will be packaged to ensure clean slate @@ -104,6 +105,9 @@ async function package(target, os, arch, exe) { // *** onnxruntime-node *** await copyOnnxRuntimeFromNodeModules(target); + // copy llama tokenizers to out + copyTokenizers(); + // *** Install @lancedb binary *** const lancePackageToInstall = { "darwin-arm64": "@lancedb/vectordb-darwin-arm64", diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index f7ca0e5d7..f002e3c50 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -94,7 +94,7 @@ const exe = os === "win32" ? ".exe" : ""; execCmdSync("npm run build"); } - // Copy over the dist folder to the Intellij extension // + // Copy over the dist folder to the JetBrains extension // const intellijExtensionWebviewPath = path.join( "..", "extensions", @@ -114,7 +114,7 @@ const exe = os === "win32" ? ".exe" : ""; ncp("dist", intellijExtensionWebviewPath, (error) => { if (error) { console.warn( - "[error] Error copying React app build to Intellij extension: ", + "[error] Error copying React app build to JetBrains extension: ", error, ); reject(error); @@ -136,7 +136,7 @@ const exe = os === "win32" ? ".exe" : ""; path.join(intellijExtensionWebviewPath, "onigasm.wasm"), ); - console.log("[info] Copied gui build to Intellij extension"); + console.log("[info] Copied gui build to JetBrains extension"); // Then copy over the dist folder to the VSCode extension // const vscodeGuiPath = path.join("../extensions/vscode/gui"); @@ -247,8 +247,12 @@ const exe = os === "win32" ? ".exe" : ""; "../../../core/llm/llamaTokenizer.mjs", "../../../core/llm/tiktokenWorkerPool.mjs", ]; + for (const f of filesToCopy) { - fs.copyFileSync(path.join(__dirname, f), path.join(__dirname, "..", "out", path.basename(f))); + fs.copyFileSync( + path.join(__dirname, f), + path.join(__dirname, "..", "out", path.basename(f)), + ); console.log(`[info] Copied ${path.basename(f)}`); } @@ -457,6 +461,7 @@ const exe = os === "win32" ? ".exe" : ""; "@vscode/ripgrep", "workerpool", ]; + fs.mkdirSync("out/node_modules", { recursive: true }); await Promise.all( @@ -504,8 +509,8 @@ const exe = os === "win32" ? ".exe" : ""; os === "darwin" ? "libonnxruntime.1.14.0.dylib" : os === "linux" - ? "libonnxruntime.so.1.14.0" - : "onnxruntime.dll" + ? "libonnxruntime.so.1.14.0" + : "onnxruntime.dll" }`, "builtin-themes/dark_modern.json", @@ -544,8 +549,8 @@ const exe = os === "win32" ? ".exe" : ""; target === "win32-arm64" ? "esbuild.exe" : target === "win32-x64" - ? "win32-x64/esbuild.exe" - : `${target}/bin/esbuild` + ? "win32-x64/esbuild.exe" + : `${target}/bin/esbuild` }`, `out/node_modules/@lancedb/vectordb-${ os === "win32" diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index b0d7def7d..93c1928ce 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -39,6 +39,20 @@ function copyConfigSchema() { fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2)); } +function copyTokenizers() { + fs.copyFileSync( + path.join(__dirname, "../../../core/llm/llamaTokenizerWorkerPool.mjs"), + path.join(__dirname, "../out/llamaTokenizerWorkerPool.mjs"), + ); + console.log("[info] Copied llamaTokenizerWorkerPool"); + + fs.copyFileSync( + path.join(__dirname, "../../../core/llm/llamaTokenizer.mjs"), + path.join(__dirname, "../out/llamaTokenizer.mjs"), + ); + console.log("[info] Copied llamaTokenizer"); +} + function installNodeModules() { // Make sure we are in the right directory if (!process.cwd().endsWith("vscode")) { @@ -64,7 +78,7 @@ async function buildGui(isGhAction) { execCmdSync("npm run build"); } - // Copy over the dist folder to the Intellij extension // + // Copy over the dist folder to the JetBrains extension // const intellijExtensionWebviewPath = path.join( "..", "extensions", @@ -84,7 +98,7 @@ async function buildGui(isGhAction) { ncp("dist", intellijExtensionWebviewPath, (error) => { if (error) { console.warn( - "[error] Error copying React app build to Intellij extension: ", + "[error] Error copying React app build to JetBrains extension: ", error, ); reject(error); @@ -106,7 +120,7 @@ async function buildGui(isGhAction) { path.join(intellijExtensionWebviewPath, "onigasm.wasm"), ); - console.log("[info] Copied gui build to Intellij extension"); + console.log("[info] Copied gui build to JetBrains extension"); // Then copy over the dist folder to the VSCode extension // const vscodeGuiPath = path.join("../extensions/vscode/gui"); @@ -242,6 +256,7 @@ async function copyNodeModules() { "@esbuild", "@lancedb", "@vscode/ripgrep", + "workerpool", ]; fs.mkdirSync("out/node_modules", { recursive: true }); @@ -313,15 +328,13 @@ async function downloadEsbuildBinary(target) { "win32-x64": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", }[target]; - execCmdSync( - `curl -L -o out/tmp/esbuild.tgz ${downloadUrl}`, - ); + execCmdSync(`curl -L -o out/tmp/esbuild.tgz ${downloadUrl}`); execCmdSync("cd out/tmp && tar -xvzf esbuild.tgz"); // Copy the installed package back to the current directory let tmpPath = "out/tmp/package/bin"; let outPath = `out/node_modules/@esbuild/${target}/bin`; if (target.startsWith("win")) { - tmpPath = 'out/tmp/package'; + tmpPath = "out/tmp/package"; outPath = `out/node_modules/@esbuild/${target}`; } @@ -332,10 +345,7 @@ async function downloadEsbuildBinary(target) { { dereference: true }, (error) => { if (error) { - console.error( - `[error] Error copying esbuild package`, - error, - ); + console.error(`[error] Error copying esbuild package`, error); reject(error); } else { resolve(); @@ -343,7 +353,7 @@ async function downloadEsbuildBinary(target) { }, ); }); - rimrafSync("out/tmp") + rimrafSync("out/tmp"); } async function downloadSqliteBinary(target) { @@ -393,7 +403,8 @@ async function copySqliteBinary() { async function downloadRipgrepBinary(target) { console.log("[info] Downloading pre-built ripgrep binary"); rimrafSync("node_modules/@vscode/ripgrep/bin"); - fs.mkdirSync("node_modules/@vscode/ripgrep/bin", { recursive: true });4 + fs.mkdirSync("node_modules/@vscode/ripgrep/bin", { recursive: true }); + 4; const downloadUrl = { "darwin-arm64": "https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-aarch64-apple-darwin.tar.gz", @@ -409,8 +420,7 @@ async function downloadRipgrepBinary(target) { "https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-x86_64-pc-windows-msvc.zip", }[target]; - - if(target.startsWith("win")) { + if (target.startsWith("win")) { execCmdSync( `curl -L -o node_modules/@vscode/ripgrep/bin/build.zip ${downloadUrl}`, ); @@ -420,7 +430,9 @@ async function downloadRipgrepBinary(target) { execCmdSync( `curl -L -o node_modules/@vscode/ripgrep/bin/build.tar.gz ${downloadUrl}`, ); - execCmdSync("cd node_modules/@vscode/ripgrep/bin && tar -xvzf build.tar.gz"); + execCmdSync( + "cd node_modules/@vscode/ripgrep/bin && tar -xvzf build.tar.gz", + ); fs.unlinkSync("node_modules/@vscode/ripgrep/bin/build.tar.gz"); } } @@ -497,4 +509,5 @@ module.exports = { installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, downloadRipgrepBinary, + copyTokenizers, }; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index b2ec0dea7..4226b1328 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -284,12 +284,12 @@ const commandsMap: ( streamInlineEdit("docstring", prompt, false, range); }, - "continue.toggleAuxiliaryBar": () => { - vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); - }, "continue.codebaseForceReIndex": async () => { core.invoke("index/forceReIndex", undefined); }, + "continue.rebuildCodebaseIndex": async () => { + core.invoke("index/forceReIndex", { shouldClearIndexes: true }); + }, "continue.docsIndex": async () => { core.invoke("context/indexDocs", { reIndex: false }); }, diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index d63b92e1a..563c0d068 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -293,7 +293,7 @@ export class VsCodeExtension { currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] ) { // Trigger refresh of index only in this directory - this.core.invoke("index/forceReIndex", dir); + this.core.invoke("index/forceReIndex", { dir }); } } diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts index ed79e1a05..02521c2ae 100644 --- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts +++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts @@ -74,12 +74,12 @@ export async function getContextProviderQuickPickVal( const val = await new Promise((resolve) => { quickPick.onDidAccept(async () => { const selectedItems = Array.from(quickPick.selectedItems); - const context = await getContextProvidersString( - selectedItems, - config, - ide, - ); - resolve(context); + getContextProvidersString(selectedItems, config, ide) + .then(resolve) + .catch((e) => { + console.warn(`Fail to get context providers: ${e}`); + resolve(""); + }); }); }); diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index f515995b8..eed3d15a0 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -1,4 +1,5 @@ import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; +import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { Message } from "core/util/messenger"; import { Telemetry } from "core/util/posthog"; import fs from "node:fs"; @@ -159,6 +160,7 @@ export class VsCodeWebviewProtocol { messageType: msg.messageType, errorMsg: message.split("\n\n")[0], + stack: extractMinimalStackTraceInfo(e.stack), }, false, ); diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index 639fc167c..d2f8575e0 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -6,16 +6,12 @@ "outDir": "out/tsc/src", "sourceMap": true, "rootDir": "../../", - "strict": true /* enable all strict type-checking options */, - /* Additional Checks */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, - "resolveJsonModule": true /* Enable importing .json files */, + "strict": true, + "esModuleInterop": true, + "resolveJsonModule": true, "types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007 }, "include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"], // core/test uses @types/jest, which conflicts with @types/mocha - "exclude": ["../../core/dist/**/*", "../../core/test/**/*"] + "exclude": ["../../core/dist/**/*", "../../core/**/*.test.ts"] } diff --git a/gui/package-lock.json b/gui/package-lock.json index 23ff1c5ac..774db75f8 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -101,7 +101,6 @@ "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", @@ -123,8 +122,11 @@ "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", "openai": "^4.20.1", + "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", + "puppeteer": "^22.4.0", + "puppeteer-chromium-resolver": "^23.0.0", "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", @@ -6311,40 +6313,6 @@ "node": ">=10" } }, - "../core/node_modules/cheerio": { - "version": "1.0.0-rc.12", - "license": "MIT", - "dependencies": { - "cheerio-select": "^2.1.0", - "dom-serializer": "^2.0.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "htmlparser2": "^8.0.1", - "parse5": "^7.0.0", - "parse5-htmlparser2-tree-adapter": "^7.0.0" - }, - "engines": { - "node": ">= 6" - }, - "funding": { - "url": "https://github.com/cheeriojs/cheerio?sponsor=1" - } - }, - "../core/node_modules/cheerio-select": { - "version": "2.1.0", - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^1.0.0", - "css-select": "^5.1.0", - "css-what": "^6.1.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/fb55" - } - }, "../core/node_modules/chownr": { "version": "2.0.0", "license": "ISC", @@ -8311,23 +8279,6 @@ "dev": true, "license": "MIT" }, - "../core/node_modules/htmlparser2": { - "version": "8.0.2", - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "entities": "^4.4.0" - } - }, "../core/node_modules/http-cache-semantics": { "version": "4.1.1", "license": "BSD-2-Clause", @@ -10573,17 +10524,6 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, - "../core/node_modules/parse5-htmlparser2-tree-adapter": { - "version": "7.0.0", - "license": "MIT", - "dependencies": { - "domhandler": "^5.0.2", - "parse5": "^7.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, "../core/node_modules/path-exists": { "version": "4.0.0", "license": "MIT", diff --git a/gui/public/logos/WatsonX.png b/gui/public/logos/WatsonX.png index 66cf02a03..ba4807267 100644 Binary files a/gui/public/logos/WatsonX.png and b/gui/public/logos/WatsonX.png differ diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index f556e824a..3c97e09e6 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -7,8 +7,6 @@ import { Button, HelperText, Input, lightGray } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; -const DEFAULT_MAX_DEPTH = 3; - function AddDocsDialog() { const posthog = usePostHog(); const dispatch = useDispatch(); @@ -17,9 +15,7 @@ function AddDocsDialog() { const [title, setTitle] = useState(""); const [startUrl, setStartUrl] = useState(""); - const [rootUrl, setRootUrl] = useState(""); const [faviconUrl, setFaviconUrl] = useState(""); - const [maxDepth, setMaxDepth] = useState(""); const [isOpen, setIsOpen] = useState(false); const ideMessenger = useContext(IdeMessengerContext); @@ -39,18 +35,14 @@ function AddDocsDialog() { const siteIndexingConfig: SiteIndexingConfig = { startUrl, - rootUrl, title, - maxDepth: typeof maxDepth === "string" ? DEFAULT_MAX_DEPTH : maxDepth, - faviconUrl: new URL("/favicon.ico", startUrl).toString(), + faviconUrl, }; ideMessenger.post("context/addDocs", siteIndexingConfig); setTitle(""); setStartUrl(""); - setRootUrl(""); - setMaxDepth(""); setFaviconUrl(""); dispatch(setShowDialog(false)); @@ -126,22 +118,6 @@ function AddDocsDialog() { {isOpen && (
- - - -
)} diff --git a/gui/src/components/dialogs/ConfirmationDialog.tsx b/gui/src/components/dialogs/ConfirmationDialog.tsx index 6cb4dd18f..cf32d52c2 100644 --- a/gui/src/components/dialogs/ConfirmationDialog.tsx +++ b/gui/src/components/dialogs/ConfirmationDialog.tsx @@ -36,7 +36,7 @@ function ConfirmationDialog(props: ConfirmationDialogProps) { return (

{props.title ?? "Confirmation"}

-

{props.text}

+

{props.text}

{!!props.hideCancelButton || ( diff --git a/gui/src/components/index.tsx b/gui/src/components/index.tsx index a186d0e6b..eac6bf022 100644 --- a/gui/src/components/index.tsx +++ b/gui/src/components/index.tsx @@ -192,7 +192,12 @@ const TooltipStyles = { }; export function StyledTooltip(props: any) { - return ; + const combinedStyles = { + ...TooltipStyles, + ...props.style, // Merge any additional styles passed via props + }; + + return ; } export const TextArea = styled.textarea` diff --git a/gui/src/components/loaders/IndexingProgressBar.tsx b/gui/src/components/loaders/IndexingProgressBar.tsx index 6fcb38e48..7446f8df9 100644 --- a/gui/src/components/loaders/IndexingProgressBar.tsx +++ b/gui/src/components/loaders/IndexingProgressBar.tsx @@ -2,13 +2,19 @@ import { IndexingProgressUpdate } from "core"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; import { useContext, useEffect, useState } from "react"; import ReactDOM from "react-dom"; -import { useSelector } from "react-redux"; +import { useSelector, useDispatch } from "react-redux"; import styled from "styled-components"; import { StyledTooltip, lightGray, vscForeground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { RootState } from "../../redux/store"; import { getFontSize, isJetBrains } from "../../util"; import StatusDot from "./StatusDot"; +import ConfirmationDialog from "../dialogs/ConfirmationDialog"; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; +import { usePostHog } from "posthog-js/react"; const STATUS_COLORS = { DISABLED: lightGray, // light gray @@ -69,16 +75,36 @@ interface ProgressBarProps { const IndexingProgressBar = ({ indexingState: indexingStateProp, }: ProgressBarProps) => { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const posthog = usePostHog(); + + const [paused, setPaused] = useState(undefined); + const [hovered, setHovered] = useState(false); + + const embeddingsProvider = useSelector( + (state: RootState) => state.state.config.embeddingsProvider, + ); + // If sidebar is opened before extension initiates, define a default indexingState const defaultIndexingState: IndexingProgressUpdate = { status: "loading", progress: 0, desc: "", }; + const indexingState = indexingStateProp || defaultIndexingState; + const fillPercentage = Math.min( + 100, + Math.max(0, indexingState.progress * 100), + ); + + const tooltipPortalDiv = document.getElementById("tooltip-portal-div"); + // If sidebar is opened after extension initializes, retrieve saved states. let initialized = false; + useEffect(() => { if (!initialized) { // Triggers retrieval for possible non-default states set prior to IndexingProgressBar initialization @@ -87,58 +113,80 @@ const IndexingProgressBar = ({ } }, []); - const fillPercentage = Math.min( - 100, - Math.max(0, indexingState.progress * 100), - ); - - const ideMessenger = useContext(IdeMessengerContext); - - const embeddingsProvider = useSelector( - (state: RootState) => state.state.config.embeddingsProvider, - ); - - const tooltipPortalDiv = document.getElementById("tooltip-portal-div"); - - const [paused, setPaused] = useState(undefined); - const [hovered, setHovered] = useState(false); - useEffect(() => { if (paused === undefined) return; ideMessenger.post("index/setPaused", paused); }, [paused]); + function onClick() { + switch (indexingState.status) { + case "failed": + // For now, we don't show in JetBrains since the reindex command + // is not yet implemented + if (indexingState.shouldClearIndexes && !isJetBrains()) { + dispatch(setShowDialog(true)); + dispatch( + setDialogMessage( + { + posthog.capture("rebuild_index_clicked"); + ideMessenger.post("index/forceReIndex", { + shouldClearIndexes: true, + }); + }} + />, + ), + ); + } else { + ideMessenger.post("index/forceReIndex", undefined); + } + + break; + case "indexing": + case "paused": + if (indexingState.progress < 1 && indexingState.progress >= 0) { + setPaused((prev) => !prev); + } else { + ideMessenger.post("index/forceReIndex", undefined); + } + + break; + default: + ideMessenger.post("index/forceReIndex", undefined); + break; + } + } + function getIndexingErrMsg(msg: string): string { if ( isJetBrains() && embeddingsProvider === TransformersJsEmbeddingsProvider.model ) { - return "The 'transformers.js' embeddingsProvider is currently unsupported in JetBrains. To enable codebase indexing, you can use any of the other providers described in the docs: https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers"; + return ( + "The 'transformers.js' embeddingsProvider is currently unsupported in JetBrains. " + + "To enable codebase indexing, you can use any of the other providers described " + + "in the docs: https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers" + ); } + return msg; } return ( -
{ - if ( - indexingState.status !== "failed" && - indexingState.progress < 1 && - indexingState.progress >= 0 - ) { - setPaused((prev) => !prev); - } else { - ideMessenger.post("index/forceReIndex", undefined); - } - }} - className="cursor-pointer" - > +
{indexingState.status === "failed" ? (
Indexing error - click to retry - {/* {getIndexingErrMsg(indexingState.desc)} */}
{tooltipPortalDiv && ReactDOM.createPortal( diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 8ab8f190e..83752c95f 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -56,6 +56,7 @@ import { getSlashCommandDropdownOptions, } from "./getSuggestion"; import { ComboBoxItem } from "./types"; +import { debounce } from "lodash"; const InputBoxDiv = styled.div` resize: none; @@ -473,6 +474,31 @@ function TipTapEditor(props: TipTapEditorProps) { }, }); + const [shouldHideToolbar, setShouldHideToolbar] = useState(false); + const debouncedShouldHideToolbar = debounce((value) => { + setShouldHideToolbar(value); + }, 200); + + useEffect(() => { + if (editor) { + const handleFocus = () => { + debouncedShouldHideToolbar(false); + } + + const handleBlur = () => { + debouncedShouldHideToolbar(true); + }; + + editor.on('focus', handleFocus); + editor.on('blur', handleBlur); + + return () => { + editor.off('focus', handleFocus); + editor.off('blur', handleBlur); + }; + } + }, [editor]); + const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); useEffect(() => { @@ -831,7 +857,7 @@ function TipTapEditor(props: TipTapEditorProps) { />