Merge branch 'main' into nate/apply-edge-cases

This commit is contained in:
Nate 2024-12-22 22:36:16 -05:00
commit eb633f335a
770 changed files with 44102 additions and 23736 deletions

View file

@ -0,0 +1,6 @@
## 0.8.62 - 2024-12-10
### Added
* Tool use
* Support for Model Context Protocol
### Fixed
* hotfix: context providers no longer hidden when not in edit mode

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Changed
body: Improved autocomplete in untitled files
time: 2024-12-13T09:15:05.552877-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Display more mid-line completions
time: 2024-12-13T09:14:54.808683-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Restored syntax highlighting
time: 2024-12-13T09:15:19.485189-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Fix tool use bug for models that don't support tools
time: 2024-12-16T22:08:02.399772-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Autodetect mistral API key type
time: 2024-12-16T22:08:18.369444-08:00

View file

@ -0,0 +1,41 @@
name: Write Core Unit Test
description: Generate unit tests for core utilities
---
Write jest tests for the provided code.
Use jest version ^29 (e.g. jest 29.7.0)
Use best practices. Be clear and consise.
Aim for 100% code coverage where reasonable.
Multiple tests can be written, split up tests for best clarity and readability.
Only use typescript, and if the file/code is not typescript, warn the user.
IMPORTANT Use ESM to import modules, do NOT use `require` anywhere
Tests are to be described in an adjacent file with a path identical except for a `.test.ts` rather than a `.ts` file extension
Use double quotes (or backticks if needed) for strings
The code being tested is used in IDE extensions, and it:
- accesses code workspaces through the IDE ("workspace directories")
- persists extension-related data to the the local machine of the user ("global directory"), and
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accesed via a remote "control plane" using the `ControlPlaneClient`
Jest testing setup includes
- @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live.
- @core/test/testDir.ts provides utils for creating and working with the temporary workspace directory. Use `setUpTestDir` and `tearDownTestDir` explicitly in tests that work with workspace files
- @core/test/jest.setup-after-env.ts gives tests access to node and jest globals
@core/test/fixtures.ts provides fixtures that should be used in tests to emulate extension behavior
- import `testIde` for IDE/workspace operations
- import `testConfigHandler` for any ConfigHandler needs
- import `testControlPlaneClient` for control plane operations
- import `ideSettingsPromise` for any IdeSettings needs
- import `testLLM` for any ILLM/BaseLLM needs. Set the `completion` property to the desired completion, e.g. `testLLM.completion = "Desired completion";`
Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests.
IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible.
Instead, generate actual mock files and data for operations
Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests
Additional types can be imported from @core/index.d.ts
If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests.
Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath)

View file

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

10
.github/auto_assign.yml vendored Normal file
View file

@ -0,0 +1,10 @@
# Reference: https://github.com/marketplace/actions/auto-assign-action
addAssignees: true
assignees:
- sestinj
- Patrick-Erichsen
- tomasz-stefaniak
- RomneyDa
numberOfAssignees: 2

View file

@ -5,12 +5,12 @@
## Checklist
- [] The relevant docs, if any, have been updated or created
- [] The relevant tests, if any, have been updated or created
## Screenshots
[ For visual changes, include screenshots. ]
## Testing
## Testing instructions
[ For new or modified features, provide step-by-step testing instructions to validate the intended behavior of the change. ]
[ For new UI features, ensure that the changes look good across viewport widths, light/dark theme, etc ]
[ For new or modified features, provide step-by-step testing instructions to validate the intended behavior of the change, including any relevant tests to run. ]

10
.github/workflows/auto-assign-pr.yaml vendored Normal file
View file

@ -0,0 +1,10 @@
name: PR assignment
on:
pull_request:
types: [opened, ready_for_review]
jobs:
add-reviews:
runs-on: ubuntu-latest
steps:
- uses: kentaro-m/auto-assign-action@v2.0.0

View file

@ -406,7 +406,7 @@ jobs:
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2024.1.5
uses: JetBrains/qodana-action@v2024.3.2
with:
cache-default-branch-only: true

View file

@ -49,11 +49,11 @@ jobs:
platform: alpine
arch: x64
npm_config_arch: x64
- os: macos-12 # should migrate this to the newer x64 version of macos-14
- os: macos-13
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-12 # same here, especially
- os: macos-13
platform: darwin
arch: arm64
npm_config_arch: arm64

View file

@ -4,110 +4,572 @@ on:
pull_request:
branches:
- main
paths:
- "extensions/vscode/**"
- "core/**"
- "gui/**"
- ".github/workflows/**"
push:
branches:
- main
paths:
- "extensions/intellij/**"
- "extensions/vscode/**"
- "core/**"
- "gui/**"
- ".github/workflows/**"
jobs:
tsc-check:
install-root:
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
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Cache root node_modules
uses: actions/cache@v3
- uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- name: Cache extension node_modules
uses: actions/cache@v3
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
install-core:
needs: install-root
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }}
node-version-file: ".nvmrc"
- name: Cache core node_modules
uses: actions/cache@v3
- uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
id: core-cache
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
key: ${{ runner.os }}-core-node-modules-${{ 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: root install
run: |
npm ci
- 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
- name: Install core dependencies
if: steps.core-cache.outputs.cache-hit != 'true'
run: |
cd core
npm ci
- name: gui install
run: |
cd gui
npm ci
core-checks:
needs: install-core
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: binary install
run: |
cd binary
npm ci
- uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- name: extensions/vscode checks
run: |
cd extensions/vscode
npx tsc --noEmit
npm run lint
- uses: actions/cache@v4
id: core-cache
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- name: core checks
- name: Type check and lint
run: |
cd core
npm ci
npx tsc --noEmit
npm run lint
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
- name: gui checks
install-gui:
needs: [install-root, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: gui-cache
with:
path: gui/node_modules
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
- name: Install gui dependencies
if: steps.gui-cache.outputs.cache-hit != 'true'
run: |
cd gui
npm ci
gui-checks:
needs: install-gui
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: gui-cache
with:
path: gui/node_modules
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
- name: Type check
run: |
cd gui
npx tsc --noEmit
- name: binary checks
binary-checks:
needs: [install-root, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: binary-cache
with:
path: binary/node_modules
key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
- name: Install binary dependencies
if: steps.binary-cache.outputs.cache-hit != 'true'
run: |
cd binary
npm ci
- name: Type check
run: |
cd binary
npx tsc --noEmit
install-vscode:
needs: [install-root, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: vscode-cache
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Install vscode dependencies
if: steps.vscode-cache.outputs.cache-hit != 'true'
run: |
cd extensions/vscode
npm ci
env:
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
vscode-checks:
needs: install-vscode
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- uses: actions/cache@v4
id: vscode-cache
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Type check and lint
run: |
cd extensions/vscode
npx tsc --noEmit
npm run lint
core-tests:
needs: install-core
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- name: Run core tests
run: |
cd core
npm test
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode]
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
- uses: actions/checkout@v4
- name: Cache node modules
uses: actions/cache@v3
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Get test files
id: vscode-get-test-file-matrix
run: |
cd extensions/vscode
npm ci
npm run e2e:compile
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Debug Outputs
run: |
echo "Test files: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}"
vscode-package-extension:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
id: vscode-node-modules-cache
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- uses: actions/cache@v4
id: core-node-modules-cache
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- name: Package extension
run: |
cd extensions/vscode
npm run package
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: vscode-extension-build
path: extensions/vscode/build
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
id: vscode-node-modules-cache
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- uses: actions/cache@v4
id: storage-cache
with:
path: extensions/vscode/e2e/storage
key: ${{ runner.os }}-vscode-storage-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Download Dependencies
if: steps.storage-cache.outputs.cache-hit != 'true'
run: |
cd extensions/vscode
npm run e2e:ci:download
- name: Upload e2e dependencies
uses: actions/upload-artifact@v4
with:
name: vscode-e2e-dependencies
path: extensions/vscode/e2e/storage
vscode-e2e-tests:
name: ${{ matrix.test_file }}"
needs:
[
vscode-download-e2e-dependencies,
vscode-get-test-file-matrix,
vscode-package-extension,
install-vscode,
install-core,
]
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
id: vscode-node-modules-cache
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Download build artifact
uses: actions/download-artifact@v4
with:
name: vscode-extension-build
path: extensions/vscode/build
- name: Download e2e dependencies
uses: actions/download-artifact@v4
with:
name: vscode-e2e-dependencies
path: extensions/vscode/e2e/storage
- name: Fix VSCode binary permissions
run: |
chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code
chmod +x extensions/vscode/e2e/storage/chromedriver-linux64/chromedriver
- name: Set up SSH
env:
SSH_KEY: ${{ secrets.GH_ACTIONS_SSH_TEST_KEY_PEM }}
SSH_HOST: ${{ secrets.GH_ACTIONS_SSH_TEST_DNS_NAME }}
run: |
mkdir -p ~/.ssh
echo "$SSH_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts
echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config
- name: Set up Xvfb
run: |
Xvfb :99 &
export DISPLAY=:99
- name: Run e2e tests
run: |
cd extensions/vscode
TEST_FILE="${{ matrix.test_file }}" npm run e2e:ci:run
env:
DISPLAY: :99
- name: Upload e2e test screenshots
if: failure()
uses: actions/upload-artifact@v4
with:
name: e2e-failure-screenshots
path: extensions/vscode/e2e/storage/screenshots
gui-tests:
needs: [install-gui, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
id: gui-cache
with:
path: gui/node_modules
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- name: Install GUI dependencies
if: steps.gui-cache.outputs.cache-hit != 'true'
run: cd gui && npm ci
env:
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: Run gui tests
run: |
cd gui
npm test
jetbrains-tests:
needs: [install-root, install-core]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: core/node_modules
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
- name: Setup Java
uses: actions/setup-java@v4.5.0
with:
distribution: zulu
java-version: 17
- name: Setup FFmpeg
uses: AnimMouse/setup-ffmpeg@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
id: gui-cache
with:
path: gui/node_modules
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
# We can shave off another minute off our CI script by finding a way to share this with vscode-tests
- 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 }}
- uses: actions/cache@v4
id: binary-cache
with:
path: binary/node_modules
key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
- name: Build the binaries
run: |
cd binary
npm run build
- name: Start test IDE
run: |
cd extensions/intellij
export DISPLAY=:99.0
Xvfb -ac :99 -screen 0 1920x1080x24 &
sleep 10
mkdir -p build/reports
./gradlew runIdeForUiTests &
- name: Wait for JB connection
uses: jtalk/url-health-check-action@v3
with:
url: http://127.0.0.1:8082
max-attempts: 15
retry-delay: 5s
- name: Run tests
run: |
cd extensions/intellij
export DISPLAY=:99.0
./gradlew test
- name: Move video
if: ${{ failure() }}
run: |
cd extensions/intellij
mv video build/reports
- name: Copy logs
if: ${{ failure() }}
run: |
cd extensions/intellij
mv build/idea-sandbox/system/log/ build/reports
- name: Save fails report
if: ${{ failure() }}
uses: actions/upload-artifact@v4
with:
name: jb-failure-report
path: |
${{ github.workspace }}/extensions/intellij/build/reports

View file

@ -49,11 +49,11 @@ jobs:
platform: alpine
arch: x64
npm_config_arch: x64
- os: macos-12 # should migrate this to the newer x64 version of macos-14
- os: macos-13
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-12 # same here, especially
- os: macos-13
platform: darwin
arch: arm64
npm_config_arch: arm64

View file

@ -0,0 +1,25 @@
name: Submit Gradle Dependency Graph For Dependabot
on:
push:
branches: ['main']
permissions:
contents: write
jobs:
dependency-submission:
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: 17
- name: Generate and submit dependency graph
uses: gradle/actions/dependency-submission@v4
with:
# The gradle project is not in the root of the repository.
build-root-directory: extensions/intellij

View file

@ -1,100 +0,0 @@
name: TypeScript Check
on:
pull_request:
branches:
- main
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 root node_modules
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
- 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: Install Root Dependencies
run: |
npm ci
- name: Install extension Dependencies
run: |
cd extensions/vscode
npm ci
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: Install gui Dependencies
run: |
cd gui
npm ci
- name: Install Core Dependencies
run: |
cd core
npm ci
- name: Install Binary Dependencies
run: |
cd binary
npm ci
- name: tsc core
run: |
cd core
npx tsc --noEmit
npm run lint
- name: tsc extensions/vscode
run: |
cd extensions/vscode
npx tsc --noEmit
npm run lint
- name: tsc binary
run: |
cd binary
npx tsc --noEmit
- name: tsc gui
run: |
cd gui
npx tsc --noEmit

8
.gitignore vendored
View file

@ -135,9 +135,7 @@ cached_embeddings.pkl
.ruff_cache
codeql
**/.continue
.DS_Store
.continue
.test
.tiktoken_cache
@ -153,9 +151,7 @@ continue_server.dist
Icon
Icon?
.continue
.continuerc.json
.prompts/
.aider*
notes.md
@ -170,4 +166,6 @@ extensions/intellij/.idea/**
extensions/intellij/bin
extensions/.continue-debug/
*.vsix
*.vsix
.continuerules

View file

@ -1 +0,0 @@
npx prettier --write .

View file

@ -16,5 +16,10 @@
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
<remote-repository>
<option name="id" value="maven" />
<option name="name" value="maven" />
<option name="url" value="https://packages.jetbrains.team/maven/p/ij/intellij-dependencies" />
</remote-repository>
</component>
</project>

View file

@ -34,7 +34,12 @@
"extensions/vscode/tag-qry/**": true,
"extensions/vscode/textmate-syntaxes/**": true,
"extensions/vscode/tree-sitter/**": true,
"gui/dist/**": true
"gui/dist/**": true,
"extensions/vscode/e2e/.test-extensions": true,
"extensions/vscode/e2e/_output": true,
"extensions/vscode/e2e/storage": true,
"extensions/vscode/e2e/vsix": true,
"extensions/.continue-debug": true
// "sync/**": true
},
"eslint.workingDirectories": ["./core"]

44
.vscode/tasks.json vendored
View file

@ -1,16 +1,36 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "tsc:watch",
"type": "npm",
"script": "tsc:watch",
"isBackground": true,
"problemMatcher": {
"base": "$tsc-watch",
"background": {
"activeOnStart": true,
"beginsPattern": "Starting compilation in watch mode...",
"endsPattern": "Found 0 errors"
}
},
"presentation": {
"revealProblems": "onProblem"
}
},
// Compile and bundle the extension
{
"label": "vscode-extension:build",
"dependsOn": [
// To detect compile errors
"vscode-extension:tsc",
// TSC type checking
"tsc:watch",
// To build the React app that is used in the extension
"vscode-extension:continue-ui:build",
// // To bundle the code the same way we do for publishing
"vscode-extension:esbuild",
// To ensure extension.js is regenerated even if
// vscode-extension:esbuild was already running in background
"vscode-extension:esbuild-notify",
// Start the React app that is used in the extension
"gui:dev"
],
@ -19,6 +39,13 @@
"isDefault": true
}
},
{
"label": "vscode-extension:esbuild-notify",
"dependsOn": ["vscode-extension:esbuild"],
"type": "npm",
"script": "esbuild-notify",
"path": "extensions/vscode"
},
{
"label": "vscode-extension:esbuild",
"dependsOn": ["vscode-extension:continue-ui:build"],
@ -46,17 +73,6 @@
}
]
},
{
"label": "vscode-extension:tsc",
"type": "npm",
"script": "tsc",
"path": "extensions/vscode",
"problemMatcher": ["$tsc"],
"presentation": {
"revealProblems": "onProblem",
"clear": true
}
},
// Build the React app. It gets bundled into the extension as a file resource and has a seprate build step
{
"label": "vscode-extension:continue-ui:build",
@ -80,7 +96,7 @@
// Build the extension
"vscode-extension:build",
// To detect compile errors - this type checks both the extension and the tests
"vscode-extension:tsc",
"tsc:watch",
"vscode-extension:tests:esbuild"
]
},

View file

@ -15,11 +15,12 @@
- [🧑‍💻 Contributing Code](#-contributing-code)
- [Environment Setup](#environment-setup)
- [Pre-requisites](#pre-requisites)
- [Fork the Continue Repository with All Branches](#fork-the-continue-repository)
- [Fork the Continue Repository](#fork-the-continue-repository)
- [VS Code](#vs-code)
- [Debugging](#debugging)
- [JetBrains](#jetbrains)
- [Our Git Workflow](#our-git-workflow)
- [Testing](#testing)
- [Formatting](#formatting)
- [Writing Slash Commands](#writing-slash-commands)
- [Writing Context Providers](#writing-context-providers)
@ -143,7 +144,13 @@ See the [`CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBr
### Our Git Workflow
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v0.9.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v0.8.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by http://releaseflow.org.
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v0.9.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v0.8.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by <http://releaseflow.org>.
### Testing
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you resolve the issue before we merge.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
### Formatting

View file

@ -118,8 +118,21 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
(async () => {
fs.mkdirSync("out/node_modules", { recursive: true });
fs.mkdirSync("bin/node_modules", { recursive: true });
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// This is only needed for our `pkg` command
fs.writeFileSync(
"out/package.json",
JSON.stringify(
{
name: "binary",
version: "1.0.0",
author: "Continue Dev, Inc",
license: "Apache-2.0",
},
undefined,
2,
),
);
console.log("[info] Downloading prebuilt lancedb...");
for (const target of targets) {
@ -196,6 +209,8 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
format: "cjs",
platform: "node",
sourcemap: true,
minify: true,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
@ -239,21 +254,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
// 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
try {
const [platform, arch] = target.split("-");
@ -278,6 +278,11 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
);
}
// Our dummy `package.json` is no longer needed so we can remove it.
// If it isn't removed, then running locally via `node out/index.js` will fail
// with a `Failed to locate bindings` error
fs.unlinkSync("out/package.json");
const pathsToVerify = [];
for (target of targets) {
const exe = target.startsWith("win") ? ".exe" : "";

View file

@ -48,7 +48,11 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.0",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",
"@modelcontextprotocol/sdk": "^1.0.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@ -59,7 +63,7 @@
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.11.0",
"dbinfoz": "^0.14.0",
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
@ -80,8 +84,9 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.20.1",
"openai": "^4.76.0",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",

View file

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

View file

@ -13,7 +13,8 @@
"../../out/tree-sitter-wasms/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
"../../out/tiktokenWorkerPool.mjs",
"../../out/package.json"
],
"targets": [
"node18-macos-arm64"

View file

@ -13,7 +13,8 @@
"../../out/tree-sitter-wasms/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
"../../out/tiktokenWorkerPool.mjs",
"../../out/package.json"
],
"targets": [
"node18-macos-x64"

View file

@ -13,7 +13,8 @@
"../../out/tree-sitter-wasms/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
"../../out/tiktokenWorkerPool.mjs",
"../../out/package.json"
],
"targets": [
"node18-linux-arm64"

View file

@ -13,7 +13,8 @@
"../../out/tree-sitter-wasms/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
"../../out/tiktokenWorkerPool.mjs",
"../../out/package.json"
],
"targets": [
"node18-linux-x64"

View file

@ -16,7 +16,8 @@
"../../node_modules/win-ca/lib/roots.exe",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
"../../out/tiktokenWorkerPool.mjs",
"../../out/package.json"
],
"targets": [
"node18-win-arm64"

View file

@ -16,7 +16,8 @@
"../../node_modules/win-ca/lib/roots.exe",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs"
"../../out/tiktokenWorkerPool.mjs",
"../../out/package.json"
],
"targets": [
"node18-win-x64"

View file

@ -1,5 +1,5 @@
import { TODO } from "core/util";
import { MessageIde } from "core/util/messageIde";
import { MessageIde } from "core/protocol/messenger/messageIde";
export class IpcIde extends MessageIde {
constructor(messenger: TODO) {

View file

@ -1,5 +1,5 @@
import { IProtocol } from "core/protocol/index.js";
import { IMessenger, type Message } from "core/util/messenger";
import { IMessenger, type Message } from "core/protocol/messenger";
import { ChildProcessWithoutNullStreams } from "node:child_process";
import * as fs from "node:fs";
import net from "node:net";

View file

@ -1,5 +1,5 @@
import { IProtocol } from "core/protocol";
import { IMessenger, Message } from "core/util/messenger";
import { IMessenger, Message } from "core/protocol/messenger";
import net from "net";
import { v4 as uuidv4 } from "uuid";

View file

@ -2,7 +2,7 @@ process.env.IS_BINARY = "true";
import { Command } from "commander";
import { Core } from "core/core";
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
import { IMessenger } from "core/util/messenger";
import { IMessenger } from "core/protocol/messenger";
import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths";
import fs from "node:fs";
import { IpcIde } from "./IpcIde";
@ -20,11 +20,11 @@ program.action(async () => {
let messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>;
if (process.env.CONTINUE_DEVELOPMENT === "true") {
messenger = new TcpMessenger<ToCoreProtocol, FromCoreProtocol>();
console.log("Waiting for connection");
console.log("[binary] Waiting for connection");
await (
messenger as TcpMessenger<ToCoreProtocol, FromCoreProtocol>
).awaitConnection();
console.log("Connected");
console.log("[binary] Connected");
} else {
setupCoreLogging();
// await setupCa();
@ -32,10 +32,12 @@ program.action(async () => {
}
const ide = new IpcIde(messenger);
const promptLogsPath = getPromptLogsPath();
const core = new Core(messenger, ide, async (text) => {
new Core(messenger, ide, async (text) => {
fs.appendFileSync(promptLogsPath, text + "\n\n");
});
console.log("Core started");
console.log("[binary] Core started");
} catch (e) {
fs.writeFileSync("./error.log", `${new Date().toISOString()} ${e}\n`);
console.log("Error: ", e);

View file

@ -2,8 +2,7 @@ import { SerializedContinueConfig } from "core";
// import Mock from "core/llm/llms/Mock.js";
import { FromIdeProtocol, ToIdeProtocol } from "core/protocol/index.js";
import FileSystemIde from "core/util/filesystem";
import { IMessenger } from "core/util/messenger";
import { ReverseMessageIde } from "core/util/reverseMessageIde";
import { IMessenger } from "core/protocol/messenger";
import fs from "fs";
import {
ChildProcessWithoutNullStreams,
@ -133,7 +132,7 @@ describe("Test Suite", () => {
fs.mkdirSync(testDir);
}
const ide = new FileSystemIde(testDir);
const reverseIde = new ReverseMessageIde(messenger.on.bind(messenger), ide);
// const reverseIde = new ReverseMessageIde(messenger.on.bind(messenger), ide);
// Wait for core to set itself up
await new Promise((resolve) => setTimeout(resolve, 1000));

View file

@ -7,7 +7,8 @@
"sourceMap": true,
"rootDirs": ["src", "../core"],
"allowJs": true,
"strict": true /* enable all strict type-checking options */,
"skipLibCheck": true,
"strict": true /* enable all strict tsc:watching 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. */

3
core/.gitignore vendored
View file

@ -3,6 +3,5 @@ target
**/.DS_Store
npm-debug.log*
.env
.continue-test
testDir
test/.continue-test
coverage

View file

@ -3,19 +3,19 @@ import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
import { IDE, ILLM } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
import { PosthogFeatureFlag, Telemetry } from "../util/posthog.js";
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js";
import { aggregateSnippets } from "./aggregateSnippets";
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
// @prettier-ignore
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import { AutocompleteSnippet } from "./context/ranking/index.js";
import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
import { postprocessCompletion } from "./postprocessing/index.js";
import { shouldPrefilter } from "./prefiltering/index.js";
import { getAllSnippets } from "./snippets/index.js";
import { renderPrompt } from "./templating/index.js";
import { GetLspDefinitionsFunction } from "./types.js";
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js";
import AutocompleteLruCache from "./util/AutocompleteLruCache.js";
@ -32,14 +32,6 @@ const ERRORS_TO_IGNORE = [
"operation was aborted",
];
export type GetLspDefinitionsFunction = (
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE,
lang: AutocompleteLanguageInfo,
) => Promise<AutocompleteSnippet[]>;
export class CompletionProvider {
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
@ -67,6 +59,11 @@ export class CompletionProvider {
return undefined;
}
// Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022
if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
llm.model = llm.completionOptions.model;
}
// Ignore empty API keys for Mistral since we currently write
// a template provider without one during onboarding
if (llm.providerName === "mistral" && llm.apiKey === "") {
@ -171,28 +168,18 @@ export class CompletionProvider {
token = controller.signal;
}
//////////
// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems,
// or they might separately track recently edited ranges)
const extraSnippets = await this._getExtraSnippets(helper);
const [snippets, diff, clipboardContent, workspaceDirs] =
await Promise.all([
aggregateSnippets(
helper,
extraSnippets,
this.contextRetrievalService,
),
this.ide.getDiff(true),
this.ide.getClipboardContent(),
this.ide.getWorkspaceDirs(),
]);
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
helper,
ide: this.ide,
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
contextRetrievalService: this.contextRetrievalService,
}),
this.ide.getWorkspaceDirs(),
]);
const { prompt, prefix, suffix, completionOptions } = renderPrompt({
snippets,
diff,
clipboardContent,
snippetPayload,
workspaceDirs,
helper,
});
@ -271,7 +258,7 @@ export class CompletionProvider {
//////////
// Save to cache
if (!outcome.cacheHit) {
if (!outcome.cacheHit && helper.options.useCache) {
(await this.autocompleteCache).put(outcome.prefix, outcome.completion);
}
@ -288,32 +275,4 @@ export class CompletionProvider {
this.loggingService.deleteAbortController(input.completionId);
}
}
private async _getExtraSnippets(
helper: HelperVars,
): Promise<AutocompleteSnippet[]> {
let extraSnippets = helper.options.useOtherFiles
? ((await Promise.race([
this.getDefinitionsFromLsp(
helper.input.filepath,
helper.fullPrefix + helper.fullSuffix,
helper.fullPrefix.length,
this.ide,
helper.lang,
),
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
}),
])) as AutocompleteSnippet[])
: [];
const workspaceDirs = await this.ide.getWorkspaceDirs();
if (helper.options.onlyMyCode) {
extraSnippets = extraSnippets.filter((snippet) => {
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
});
}
return extraSnippets;
}
}

View file

@ -28,11 +28,10 @@ Example:
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5b",
"model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
"provider": "lmstudio",
},
...
"title": "Qwen2.5-Coder 1.5b",
"model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
"provider": "lmstudio"
}
}
```
@ -87,7 +86,6 @@ This is just another object like the ones in the `"models"` array of `config.jso
This object allows you to customize the behavior of tab-autocomplete. The available options are:
- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean)
- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number)
- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number)
@ -107,7 +105,6 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
"useCopyBuffer": false,
"maxPromptTokens": 400,
"prefixPercentage": 0.5
}

View file

@ -1,45 +0,0 @@
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import {
fillPromptWithSnippets,
rankAndOrderSnippets,
type AutocompleteSnippet,
} from "./context/ranking/index.js";
import { HelperVars } from "./util/HelperVars.js";
function filterSnippetsAlreadyInCaretWindow(
snippets: AutocompleteSnippet[],
caretWindow: string,
): AutocompleteSnippet[] {
return snippets
.map((snippet) => ({ ...snippet }))
.filter(
(s) =>
s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()),
);
}
export async function aggregateSnippets(
helper: HelperVars,
extraSnippets: AutocompleteSnippet[],
contextRetrievalService: ContextRetrievalService,
): Promise<AutocompleteSnippet[]> {
let snippets = await contextRetrievalService.retrieveCandidateSnippets(
helper,
extraSnippets,
);
snippets = filterSnippetsAlreadyInCaretWindow(
snippets,
helper.prunedCaretWindow,
);
const scoredSnippets = rankAndOrderSnippets(snippets, helper);
const finalSnippets = fillPromptWithSnippets(
scoredSnippets,
helper.maxSnippetTokens,
helper.modelName,
);
return finalSnippets;
}

View file

@ -1,3 +1,4 @@
import { getUriFileExtension } from "../../util/uri";
import { BracketMatchingService } from "../filtering/BracketMatchingService";
import {
CharacterFilter,
@ -9,7 +10,6 @@ export interface AutocompleteLanguageInfo {
topLevelKeywords: string[];
singleLineComment?: string;
endOfLine: string[];
stopWords?: string[];
lineFilters?: LineFilter[];
charFilters?: CharacterFilter[];
useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
@ -28,7 +28,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: [],
};
@ -369,8 +369,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
md: Markdown,
};
export function languageForFilepath(
filepath: string,
): AutocompleteLanguageInfo {
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
export function languageForFilepath(fileUri: string): AutocompleteLanguageInfo {
const extension = getUriFileExtension(fileUri);
return LANGUAGES[extension] || Typescript;
}

View file

@ -1,9 +1,12 @@
import { IDE } from "../..";
import {
AutocompleteCodeSnippet,
AutocompleteSnippetType,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { RecentlyEditedRange } from "../util/types";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking";
import { getSymbolsForSnippet } from "./ranking";
import { RootPathContextService } from "./root-path-context/RootPathContextService";
export class ContextRetrievalService {
@ -18,79 +21,14 @@ export class ContextRetrievalService {
);
}
public async retrieveCandidateSnippets(
public async getSnippetsFromImportDefinitions(
helper: HelperVars,
extraSnippets: AutocompleteSnippet[],
) {
if (helper.options.useOtherFiles === false) {
return [];
}
let snippets: AutocompleteSnippet[] = [];
// Snippets injected by the IDE for IDE-specific reasons
snippets.push(...extraSnippets);
// If a recently edited range has a line that is a perfect match with the start of the current line
snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper));
// Import definitions of any symbols in near range of the caret
snippets.push(...(await this.getSnippetsFromImportDefinitions(helper)));
// Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/
if (helper.options.useRootPathContext && helper.treePath) {
snippets.push(
...(await this.rootPathContextService.getContextForPath(
helper.filepath,
helper.treePath,
)),
);
}
return snippets;
}
private getSnippetsFromRecentlyEditedRanges(
helper: HelperVars,
): AutocompleteSnippet[] {
if (helper.options.useRecentlyEdited === false) {
return [];
}
const currentLinePrefix = helper.prunedPrefix
.trim()
.split("\n")
.slice(-1)[0];
if (
currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength
) {
const matchingRange = this.findMatchingRange(
helper.input.recentlyEditedRanges,
currentLinePrefix,
);
if (matchingRange) {
return [
{
...matchingRange,
contents: matchingRange.lines.join("\n"),
score: 0.8,
},
];
}
}
return [];
}
private async getSnippetsFromImportDefinitions(
helper: HelperVars,
): Promise<AutocompleteSnippet[]> {
): Promise<AutocompleteCodeSnippet[]> {
if (helper.options.useImports === false) {
return [];
}
const importSnippets = [];
const importSnippets: AutocompleteCodeSnippet[] = [];
const fileInfo = this.importDefinitionsService.get(helper.filepath);
if (fileInfo) {
const { imports } = fileInfo;
@ -104,21 +42,32 @@ export class ContextRetrievalService {
for (const symbol of symbols) {
const rifs = imports[symbol];
if (Array.isArray(rifs)) {
importSnippets.push(...rifs);
const snippets: AutocompleteCodeSnippet[] = rifs.map((rif) => {
return {
filepath: rif.filepath,
content: rif.contents,
type: AutocompleteSnippetType.Code,
};
});
importSnippets.push(...snippets);
}
}
}
return importSnippets;
}
findMatchingRange(
recentlyEditedRanges: RecentlyEditedRange[],
linePrefix: string,
): RecentlyEditedRange | undefined {
return recentlyEditedRanges.find((recentlyEditedRange) => {
return recentlyEditedRange.lines.some((line) =>
line.startsWith(linePrefix),
);
});
public async getRootPathSnippets(
helper: HelperVars,
): Promise<AutocompleteCodeSnippet[]> {
if (!helper.treePath) {
return [];
}
return this.rootPathContextService.getContextForPath(
helper.filepath,
helper.treePath,
);
}
}

View file

@ -29,14 +29,28 @@ export class ImportDefinitionsService {
return this.cache.get(filepath);
}
private async _getFileInfo(filepath: string): Promise<FileInfo> {
private async _getFileInfo(filepath: string): Promise<FileInfo | null> {
if (filepath.endsWith(".ipynb")) {
// Commenting out this line was the solution to https://github.com/continuedev/continue/issues/1463
return null;
}
const parser = await getParserForFile(filepath);
if (!parser) {
return {
imports: {},
};
}
const ast = parser.parse(await this.ide.readFile(filepath), undefined, {
let fileContents: string | undefined = undefined;
try {
fileContents = await this.ide.readFile(filepath);
} catch (err) {
// File removed
return null;
}
const ast = parser.parse(fileContents, undefined, {
includedRanges: [
{
startIndex: 0,

View file

@ -1,46 +0,0 @@
import { IDE, Location } from "../..";
import { LANGUAGES } from "../constants/AutocompleteLanguageInfo";
import { getSymbolsForSnippet } from "./ranking";
interface FileInfo {
filepath: string;
}
export class NearbyDefinitionsService {
static N = 10;
constructor(private readonly ide: IDE) {}
async getDefinitionsForLine(filepath: string, line: number) {
const lineContent = await this.ide.readRangeInFile(filepath, {
start: {
line,
character: 0,
},
end: {
line: line + 1,
character: 0,
},
});
// Remove keywords
const lang = LANGUAGES[filepath.split(".").slice(-1)[0]];
const symbols = Array.from(getSymbolsForSnippet(lineContent))
.filter((s) => s.length > 0)
.filter((s) => !(lang && lang?.stopWords?.includes(s)));
return Promise.all(
symbols.map((s) => {
const character = lineContent.indexOf(s);
const pos: Location = {
filepath,
position: {
line,
character,
},
};
}),
);
}
}

View file

@ -1,11 +1,8 @@
import { Range, RangeInFileWithContents } from "../../../";
import { RangeInFileWithContents } from "../../../";
import { countTokens } from "../../../llm/countTokens";
import { AutocompleteSnippetDeprecated } from "../../types";
import { HelperVars } from "../../util/HelperVars";
export type AutocompleteSnippet = RangeInFileWithContents & {
score?: number;
};
const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g;
export function getSymbolsForSnippet(snippet: string): Set<string> {
const symbols = snippet
@ -18,7 +15,7 @@ export function getSymbolsForSnippet(snippet: string): Set<string> {
/**
* Calculate similarity as number of shared symbols divided by total number of unique symbols between both.
*/
export function jaccardSimilarity(a: string, b: string): number {
function jaccardSimilarity(a: string, b: string): number {
const aSet = getSymbolsForSnippet(a);
const bSet = getSymbolsForSnippet(b);
const union = new Set([...aSet, ...bSet]).size;
@ -42,9 +39,9 @@ export function jaccardSimilarity(a: string, b: string): number {
* Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array.
*/
export function rankAndOrderSnippets(
ranges: AutocompleteSnippet[],
ranges: AutocompleteSnippetDeprecated[],
helper: HelperVars,
): Required<AutocompleteSnippet>[] {
): Required<AutocompleteSnippetDeprecated>[] {
const windowAroundCursor =
helper.fullPrefix.slice(
-helper.options.slidingWindowSize *
@ -55,11 +52,14 @@ export function rankAndOrderSnippets(
(1 - helper.options.slidingWindowPrefixPercentage),
);
const snippets: Required<AutocompleteSnippet>[] = ranges.map((snippet) => ({
score:
snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor),
...snippet,
}));
const snippets: Required<AutocompleteSnippetDeprecated>[] = ranges.map(
(snippet) => ({
score:
snippet.score ??
jaccardSimilarity(snippet.contents, windowAroundCursor),
...snippet,
}),
);
const uniqueSnippets = deduplicateSnippets(snippets);
return uniqueSnippets.sort((a, b) => a.score - b.score);
}
@ -67,11 +67,13 @@ export function rankAndOrderSnippets(
/**
* Deduplicate code snippets by merging overlapping ranges into a single range.
*/
export function deduplicateSnippets(
snippets: Required<AutocompleteSnippet>[],
): Required<AutocompleteSnippet>[] {
function deduplicateSnippets(
snippets: Required<AutocompleteSnippetDeprecated>[],
): Required<AutocompleteSnippetDeprecated>[] {
// Group by file
const fileGroups: { [key: string]: Required<AutocompleteSnippet>[] } = {};
const fileGroups: {
[key: string]: Required<AutocompleteSnippetDeprecated>[];
} = {};
for (const snippet of snippets) {
if (!fileGroups[snippet.filepath]) {
fileGroups[snippet.filepath] = [];
@ -88,8 +90,8 @@ export function deduplicateSnippets(
}
function mergeSnippetsByRange(
snippets: Required<AutocompleteSnippet>[],
): Required<AutocompleteSnippet>[] {
snippets: Required<AutocompleteSnippetDeprecated>[],
): Required<AutocompleteSnippetDeprecated>[] {
if (snippets.length <= 1) {
return snippets;
}
@ -97,7 +99,7 @@ function mergeSnippetsByRange(
const sorted = snippets.sort(
(a, b) => a.range.start.line - b.range.start.line,
);
const merged: Required<AutocompleteSnippet>[] = [];
const merged: Required<AutocompleteSnippetDeprecated>[] = [];
while (sorted.length > 0) {
const next = sorted.shift()!;
@ -133,12 +135,12 @@ function mergeOverlappingRangeContents(
* It is assumed that the snippets are sorted by score.
*/
export function fillPromptWithSnippets(
snippets: Required<AutocompleteSnippet>[],
snippets: Required<AutocompleteSnippetDeprecated>[],
maxSnippetTokens: number,
modelName: string,
): Required<AutocompleteSnippet>[] {
): Required<AutocompleteSnippetDeprecated>[] {
let tokensRemaining = maxSnippetTokens;
const keptSnippets: Required<AutocompleteSnippet>[] = [];
const keptSnippets: Required<AutocompleteSnippetDeprecated>[] = [];
for (let i = 0; i < snippets.length; i++) {
const snippet = snippets[i];
const tokenCount = countTokens(snippet.contents, modelName);
@ -151,58 +153,3 @@ export function fillPromptWithSnippets(
return keptSnippets;
}
/**
* Remove one range from another range, which may lead to returning two disjoint ranges
*/
function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
if (
orig.start.line >= remove.start.line &&
orig.end.line <= remove.end.line
) {
// / | | /
return [];
}
if (
orig.start.line <= remove.start.line &&
orig.end.line >= remove.end.line
) {
// | / / |
// Splits the range
return [
{
start: orig.start,
end: remove.start,
},
{
start: remove.end,
end: orig.end,
},
];
}
if (
orig.start.line >= remove.start.line &&
orig.end.line >= remove.end.line
) {
// \ | / |
return [
{
start: remove.end,
end: orig.end,
},
];
}
if (
orig.start.line <= remove.start.line &&
orig.end.line <= remove.end.line
) {
// | / | /
return [
{
start: orig.start,
end: remove.start,
},
];
}
return [orig];
}

View file

@ -1,60 +0,0 @@
import { RangeInFileWithContents } from "../../../";
import { AutocompleteSnippet, jaccardSimilarity } from "./";
function* slidingWindow(
content: string,
windowSize: number,
): Generator<string> {
const lines = content.split("\n");
let charCount = 0;
let currWindowLines: string[] = [];
for (let i = 0; i < lines.length; i++) {
if (charCount + lines[i].length >= windowSize) {
yield currWindowLines.join("\n");
currWindowLines = [lines[i]];
charCount = 0;
} else {
currWindowLines.push(lines[i]);
}
charCount += lines[i].length;
}
if (currWindowLines.length > 0) {
yield currWindowLines.join("\n");
}
}
/**
* Match by similarity over sliding windows of recent documents.
* @param recentFiles
* @param prefix
* @param suffix
*/
export async function slidingWindowMatcher(
recentFiles: RangeInFileWithContents[],
windowAroundCursor: string,
topN: number,
windowSize: number,
): Promise<AutocompleteSnippet[]> {
// Sorted lowest similarity to highest
const topMatches: Required<AutocompleteSnippet>[] = [];
for (const { filepath, contents, range } of recentFiles) {
for (const window of slidingWindow(contents, windowSize)) {
const score = jaccardSimilarity(window, windowAroundCursor);
// Insertion sort
let i = -1;
while (++i < topMatches.length && score > topMatches[i].score) {}
topMatches.splice(i + 1, 0, { filepath, contents, score, range });
if (topMatches.length > topN) {
topMatches.shift();
}
}
}
// TODO: convert the arbitrary window frame to some whole AST node?
return topMatches;
}

View file

@ -10,27 +10,31 @@ import {
IGNORE_PATH_PATTERNS,
LanguageName,
} from "../../../util/treeSitter";
import {
AutocompleteCodeSnippet,
AutocompleteSnippetType,
} from "../../snippets/types";
import { AutocompleteSnippetDeprecated } from "../../types";
import { AstPath } from "../../util/ast";
import { ImportDefinitionsService } from "../ImportDefinitionsService";
import { AutocompleteSnippet } from "../ranking";
function getSyntaxTreeString(
node: Parser.SyntaxNode,
indent: string = "",
): string {
let result = "";
const nodeInfo = `${node.type} [${node.startPosition.row}:${node.startPosition.column} - ${node.endPosition.row}:${node.endPosition.column}]`;
result += `${indent}${nodeInfo}\n`;
// function getSyntaxTreeString(
// node: Parser.SyntaxNode,
// indent: string = "",
// ): string {
// let result = "";
// const nodeInfo = `${node.type} [${node.startPosition.row}:${node.startPosition.column} - ${node.endPosition.row}:${node.endPosition.column}]`;
// result += `${indent}${nodeInfo}\n`;
for (const child of node.children) {
result += getSyntaxTreeString(child, indent + " ");
}
// for (const child of node.children) {
// result += getSyntaxTreeString(child, indent + " ");
// }
return result;
}
// return result;
// }
export class RootPathContextService {
private cache = new LRUCache<string, AutocompleteSnippet[]>({
private cache = new LRUCache<string, AutocompleteSnippetDeprecated[]>({
max: 100,
});
@ -72,8 +76,8 @@ export class RootPathContextService {
private async getSnippetsForNode(
filepath: string,
node: Parser.SyntaxNode,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
): Promise<AutocompleteSnippetDeprecated[]> {
const snippets: AutocompleteSnippetDeprecated[] = [];
const language = getFullLanguageName(filepath);
let query: Parser.Query | undefined;
@ -108,7 +112,6 @@ export class RootPathContextService {
);
snippets.push(...newSnippets);
} catch (e) {
debugger;
throw e;
}
}
@ -123,7 +126,7 @@ export class RootPathContextService {
filepath: string,
endPosition: Parser.Point,
language: LanguageName,
): Promise<AutocompleteSnippet[]> {
): Promise<AutocompleteSnippetDeprecated[]> {
const definitions = await this.ide.gotoDefinition({
filepath,
position: {
@ -153,8 +156,8 @@ export class RootPathContextService {
filepath: string,
astPath: AstPath,
// cursorIndex: number,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
): Promise<AutocompleteCodeSnippet[]> {
const snippets: AutocompleteCodeSnippet[] = [];
let parentKey = filepath;
for (const astNode of astPath.filter((node) =>
@ -167,7 +170,16 @@ export class RootPathContextService {
const foundInCache = this.cache.get(key);
const newSnippets =
foundInCache ?? (await this.getSnippetsForNode(filepath, astNode));
snippets.push(...newSnippets);
const formattedSnippets: AutocompleteCodeSnippet[] = newSnippets.map(
(item) => ({
filepath: item.filepath,
content: item.contents,
type: AutocompleteSnippetType.Code,
}),
);
snippets.push(...formattedSnippets);
if (!foundInCache) {
this.cache.set(key, newSnippets);

View file

@ -4,7 +4,7 @@ import path from "path";
import Parser from "web-tree-sitter";
import { Position } from "../../../..";
import { testIde } from "../../../../test/util/fixtures";
import { testIde } from "../../../../test/fixtures";
import { getAst, getTreePathAtCursor } from "../../../util/ast";
import { ImportDefinitionsService } from "../../ImportDefinitionsService";
import { RootPathContextService } from "../RootPathContextService";

View file

@ -1,20 +1,24 @@
import { streamLines } from "../../../diff/util";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters";
import { PosthogFeatureFlag, Telemetry } from "../../../util/posthog";
import { HelperVars } from "../../util/HelperVars";
import { stopAtStopTokens } from "./charStream";
import { stopAtStartOf, stopAtStopTokens } from "./charStream";
import {
avoidEmptyComments,
avoidPathLine,
noDoubleNewLine,
showWhateverWeHaveAtXMs,
skipPrefixes,
stopAtLines,
stopAtLinesExact,
stopAtRepeatingLines,
stopAtSimilarLine,
stopNCharsAfterClosingBracket,
streamWithNewLines,
} from "./lineStream";
const STOP_AT_PATTERNS = ["diff --git"];
export class StreamTransformPipeline {
async *transform(
generator: AsyncGenerator<string>,
@ -27,7 +31,11 @@ export class StreamTransformPipeline {
): AsyncGenerator<string> {
let charGenerator = generator;
charGenerator = stopAtStopTokens(generator, stopTokens);
charGenerator = stopAtStopTokens(generator, [
...stopTokens,
...STOP_AT_PATTERNS,
]);
charGenerator = stopAtStartOf(charGenerator, suffix);
for (const charFilter of helper.lang.charFilters ?? []) {
charGenerator = charFilter({
chars: charGenerator,
@ -41,6 +49,12 @@ export class StreamTransformPipeline {
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator, fullStop);
const lineBelowCursor = this.getLineBelowCursor(helper);
if (lineBelowCursor.trim() !== "") {
lineGenerator = stopAtLinesExact(lineGenerator, fullStop, [
lineBelowCursor,
]);
}
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidEmptyComments(
lineGenerator,
@ -48,7 +62,7 @@ export class StreamTransformPipeline {
);
lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = stopNCharsAfterClosingBracket(lineGenerator);
lineGenerator = noDoubleNewLine(lineGenerator);
for (const lineFilter of helper.lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
@ -60,11 +74,14 @@ export class StreamTransformPipeline {
fullStop,
);
lineGenerator = showWhateverWeHaveAtXMs(
lineGenerator,
const timeoutValue =
helper.options.showWhateverWeHaveAtXMs ??
(DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs as number),
);
(await Telemetry.getValueForFeatureFlag(
PosthogFeatureFlag.AutocompleteTimeout,
)) ??
DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs;
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
const finalGenerator = streamWithNewLines(lineGenerator);
for await (const update of finalGenerator) {

View file

@ -1,12 +1,20 @@
import { stopAtStopTokens } from "./charStream";
import { stopAtStartOf, stopAtStopTokens } from "./charStream";
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
for (const chunk of chunks) {
yield chunk;
}
}
async function streamToString(stream: AsyncGenerator<string>): Promise<string> {
let result = "";
for await (const chunk of stream) {
result += chunk;
}
return result;
}
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
for (const chunk of chunks) {
yield chunk;
}
}
it("should yield characters until a stop token is encountered", async () => {
const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]);
const stopTokens = ["Stop"];
@ -30,12 +38,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["END", "STOP", "HALT"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a test. ");
expect(await streamToString(result)).toBe("This is a test. ");
});
it("should handle stop tokens split across chunks", async () => {
@ -67,12 +70,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["END"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a complete stream");
expect(await streamToString(result)).toBe("This is a complete stream");
});
it("should handle empty chunks", async () => {
@ -80,12 +78,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world! ");
expect(await streamToString(result)).toBe("Hello world! ");
});
it("should handle stop token at the beginning of the stream", async () => {
@ -106,12 +99,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world");
expect(await streamToString(result)).toBe("Hello world");
});
it("should handle multiple stop tokens of different lengths", async () => {
@ -124,12 +112,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["STOP", "END", "HALT"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a test with multiple ");
expect(await streamToString(result)).toBe("This is a test with multiple ");
});
it("should handle an empty stream", async () => {
@ -137,12 +120,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("");
expect(await streamToString(result)).toBe("");
});
it("should handle an empty stop tokens array", async () => {
@ -166,11 +144,72 @@ describe("stopAtStopTokens", () => {
];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world!");
expect(await streamToString(result)).toBe("Hello world!");
});
});
describe("stopAtStartOf", () => {
const sampleCode = ` {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: \`Bearer \${this.workOsAccessToken}\`,
},
},
);
const data = await response.json();
return data.items;
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const response = await extras.fetch(
new URL(
\`/proxy/context/\${this.options.id}/retrieve\`,
controlPlaneEnv.CONTROL_PLANE_URL,
),
`;
/* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input
and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */
it("should stop if the start of the suffix is reached", async () => {
const suffix = `
const data = await response.json();
return data.items;
}`;
const mockStream = createMockStream(sampleCode.split(/(?! )/g));
const result = stopAtStartOf(mockStream, suffix);
const resultStr = await streamToString(result);
expect(resultStr).toBe(` {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: \`Bearer \${this.workOsAccessToken}\`,
},
},
);
`);
});
it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => {
const suffix = `
xxxconst data = await response.json();
return data.items;
}`;
const mockStream = createMockStream(sampleCode.split(/(?! )/g));
const result = stopAtStartOf(mockStream, suffix);
const resultStr = await streamToString(result);
expect(resultStr).toBe(` {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: \`Bearer \${this.workOsAccessToken}\`,
},
},
);
`);
});
});

View file

@ -117,3 +117,47 @@ export async function* stopAtStopTokens(
yield char;
}
}
/**
* Asynchronously yields characters from the input stream.
* Stops if the beginning of the suffix is detected in the stream.
*/
export async function* stopAtStartOf(
stream: AsyncGenerator<string>,
suffix: string,
sequenceLength: number = 20,
): AsyncGenerator<string> {
if (suffix.length < sequenceLength) {
for await (const chunk of stream) {
yield chunk;
}
return;
}
// We use sequenceLength * 1.5 as a heuristic to make sure we don't miss the sequence if the
// stream is not perfectly aligned with the sequence (small whitespace differences etc).
const targetPart = suffix
.trimStart()
.slice(0, Math.floor(sequenceLength * 1.5));
let buffer = "";
for await (const chunk of stream) {
buffer += chunk;
// Check if the targetPart contains contains the buffer at any point
if (buffer.length >= sequenceLength && targetPart.includes(buffer)) {
return; // Stop processing when the sequence is found
}
// Yield chunk by chunk, ensuring not to exceed sequenceLength in the buffer
while (buffer.length > sequenceLength) {
yield buffer[0];
buffer = buffer.slice(1);
}
}
// Yield the remaining buffer if it is not contained in the `targetPart`
if (buffer.length > 0) {
yield buffer;
}
}

View file

@ -98,7 +98,7 @@ describe("lineStream", () => {
describe("stopAtSimilarLine", () => {
it("should stop at the exact same line", async () => {
const lineToTest = "const x = 6;";
const lineToTest = "const x = 6";
const linesGenerator = await getLineGenerator([
"console.log();",
"const y = () => {};",
@ -116,7 +116,7 @@ describe("lineStream", () => {
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it.only("should stop at a similar line", async () => {
it("should stop at a similar line", async () => {
const lineToTest = "const x = 6;";
const linesGenerator = await getLineGenerator([
"console.log();",

View file

@ -2,7 +2,6 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";
import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService";
export type LineFilter = (args: {
lines: LineStream;
@ -83,7 +82,7 @@ export const LINES_TO_REMOVE_BEFORE_START = [
"<COMPLETION>",
"[CODE]",
"<START EDITING HERE>",
"{{FILL_HERE}}"
"{{FILL_HERE}}",
];
export const ENGLISH_START_PHRASES = [
@ -270,6 +269,20 @@ export async function* stopAtLines(
}
}
export async function* stopAtLinesExact(
stream: LineStream,
fullStop: () => void,
linesToStopAt: string[],
): LineStream {
for await (const line of stream) {
if (linesToStopAt.some((stopAt) => line === stopAt)) {
fullStop();
break;
}
yield line;
}
}
/**
* Filters a LineStream, skipping specified prefixes on the first line.
* @param {LineStream} lines - The input stream of lines.
@ -537,66 +550,32 @@ export async function* showWhateverWeHaveAtXMs(
ms: number,
): LineStream {
const startTime = Date.now();
let firstNonWhitespaceLineYielded = false;
for await (const line of lines) {
// Always get at least one line
yield line;
// But after that, soft break at X ms
if (Date.now() - startTime > ms) {
if (!firstNonWhitespaceLineYielded && line.trim() !== "") {
firstNonWhitespaceLineYielded = true;
}
const isTakingTooLong = Date.now() - startTime > ms;
if (isTakingTooLong && firstNonWhitespaceLineYielded) {
break;
}
}
}
export async function* stopNCharsAfterClosingBracket(
lines: LineStream,
n: number = 20,
): LineStream {
const bracketTypeCounts = new Map<string, number>();
let charsToStopAt: number | null = null;
export async function* noDoubleNewLine(lines: LineStream): LineStream {
let isFirstLine = true;
for await (const line of lines) {
let outputLine = "";
let i = 0;
while (i < line.length) {
const char = line[i];
// Update bracket counts
if (BRACKETS[char]) {
// It's an opening bracket
const count = bracketTypeCounts.get(char) || 0;
bracketTypeCounts.set(char, count + 1);
} else if (BRACKETS_REVERSE[char]) {
// It's a closing bracket
const openingBracket = BRACKETS_REVERSE[char];
const count = bracketTypeCounts.get(openingBracket) || 0;
const newCount = count - 1;
bracketTypeCounts.set(openingBracket, newCount);
if (newCount < 0 && charsToStopAt === null) {
// Unmatched closing bracket detected
charsToStopAt = n;
}
}
// Add the character to the output line
outputLine += char;
// If we've started counting down, decrement the remaining characters
if (charsToStopAt !== null) {
charsToStopAt -= 1;
if (charsToStopAt <= 0) {
// Yield the output line up to this point and stop the generator
yield outputLine;
return;
}
}
i += 1;
if (line.trim() === "" && !isFirstLine) {
return;
}
// Yield whatever we've accumulated for this line
yield outputLine;
isFirstLine = false;
yield line;
}
}

View file

@ -1,143 +0,0 @@
import { stopNCharsAfterClosingBracket } from "./lineStream";
describe("noDoubleNewlineAfterClosingBracket", () => {
// Helper function to convert an array to an async generator
async function* arrayToAsyncGenerator<T>(array: T[]): AsyncGenerator<T> {
for (const item of array) {
yield item;
}
}
// Helper function to collect lines from the async generator
async function collectLines(lines: AsyncIterable<string>): Promise<string[]> {
const result: string[] = [];
for await (const line of lines) {
result.push(line);
}
return result;
}
test("should yield all lines when no unmatched brackets", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
stopNCharsAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should yield all lines when >20 chars after brackets but brackets are matched", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
"// End of function and start of something else",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
stopNCharsAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should stop yielding after 20 chars when unmatched closing bracket is found", async () => {
const inputLines = [
// "function test() {",
' console.log("Hello World");',
// Unmatched closing bracket
"}",
"1234567890123456789",
'console.log("End");',
];
const expectedOutputLines = [
' console.log("Hello World");',
"}",
"1234567890123456789",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
stopNCharsAfterClosingBracket(lines),
);
expect(outputLines).toEqual(expectedOutputLines);
});
test("should stop yielding after 2 chars when unmatched closing bracket is found", async () => {
const inputLines = [
// "function test() {",
' console.log("Hello World");',
// Unmatched closing bracket
"}",
"12",
'console.log("End");',
];
const expectedOutputLines = [' console.log("Hello World");', "}", "1"];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
stopNCharsAfterClosingBracket(lines, 2),
);
expect(outputLines).toEqual(expectedOutputLines);
});
test("should stop yielding after 4 chars when unmatched closing bracket is found, on same line", async () => {
const inputLines = [
// "function test() {",
' console.log("Hello World");',
// Unmatched closing bracket
"}23456",
];
const expectedOutputLines = [' console.log("Hello World");', "}234"];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
stopNCharsAfterClosingBracket(lines, 4),
);
expect(outputLines).toEqual(expectedOutputLines);
});
test("should yield all lines when unmatched brackets but less <20 chars after", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
// Unmatched closing bracket
")",
"// Continue code",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
stopNCharsAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should yield all lines when brackets are matched even with many characters", async () => {
const inputLines = [
"const arr = [",
" 1, 2, 3,",
"];",
"",
"",
"console.log(arr);",
"console.log(arr);",
"console.log(arr);",
"console.log(arr);",
"console.log(arr);",
"console.log(arr);",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
stopNCharsAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
});

View file

@ -1,4 +1,4 @@
import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir";
import { setUpTestDir, tearDownTestDir } from "../../../test/testDir";
import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
import {

View file

@ -110,6 +110,7 @@ Here is a list of features:
- Feature 2`,
},
{
// options: { only: true },
description: "Should autocomplete a Java method within a class",
filename: "Calculator.java",
input: `
@ -150,26 +151,8 @@ public class Calculator {
POSTGRES_DB: mydb
`,
expectedCompletion: `
POSTGRES_DB: mydb
`,
POSTGRES_DB: mydb`,
},
// TODO
// {
// description: "Should autocomplete a Markdown list with nested items",
// filename: "test.md",
// input: `
// - Item 1
// - Item 2
// - Subitem 1
// <|fim|>
// - Item 3
// `,
// llmOutput: ` - Subitem 2
// - Subitem 3
// `,
// expectedCompletion: ` - Subitem 2
// - Subitem 3`,
// },
{
description: "Should enforce bracket matching in JSON files",
filename: "test.json",
@ -181,7 +164,7 @@ public class Calculator {
"state": "California",
"city": "San BERNARDINO",
"coordinates": {
<FIM>
<|fim|>
}
},
"employees": [
@ -230,8 +213,171 @@ public class Calculator {
"required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"],
"optional": ["Photoshop", "Illustrator"]`,
expectedCompletion: `"latitude": 34.10834,
"longitude": -117.28977
"longitude": -117.28977`,
},
{
description:
"Should return nothing when output is duplicated lines in TypeScript",
filename: "file.ts",
input: `
async getContextForPath(
filepath: string,
astPath: AstPatt,
language: LanguageName,
options: ContextOptions = {},
<|fim|>
): Promise<AutocompleteCodeSnippet[]> {
const snippets: AutocompleteCodeSnippet[] = [];
let parentKey = filepath;
`,
llmOutput: ` ): Promise<AutocompleteCodeSnippet[]> {
const snippets: AutocompleteCodeSnippet[] = [];
`,
expectedCompletion: undefined,
},
{
description:
"Should return partial result when output is duplicated lines in TypeScript",
filename: "file.ts",
input: `
async getContextForPath(
filepath: string,
astPath: AstPatt,
language: LanguageName,
options: ContextOptions = {},
<|fim|>
): Promise<AutocompleteCodeSnippet[]> {
const snippets: AutocompleteCodeSnippet[] = [];
let parentKey = filepath;
`,
llmOutput: `console.log('TEST');
): Promise<AutocompleteCodeSnippet[]> {
const snippets: AutocompleteCodeSnippet[] = [];
`,
expectedCompletion: `console.log('TEST');`,
},
{
description: "Should autocomplete React effect hook",
input: `import React, { useState, useEffect } from "react";
export const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds + 1);
}, 1000);
<|fim|>;
return () => clearInterval(interval);
}, [seconds]);
return (
<div>
<p>{seconds} seconds have passed.</p>
</div>
);
};`,
llmOutput: "return () => clearInterval(interval);",
expectedCompletion: undefined,
filename: "Timer.tsx",
},
{
description: "Should autocomplete simple return statement in TypeScript",
filename: "file.ts",
input: `
multiply(number) {
this.result *= number;
return <|fim|>
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
`,
llmOutput: ` this;`,
expectedCompletion: `this;`,
},
{
description: "Should complete YAML list item and preserve structure",
filename: "test.yaml",
input: `
services:
- name: web
image: nginx
- name: app<|fim|>
volumes:
- volume1
- volume2
`,
llmOutput: `
image: node
`,
expectedCompletion: `
image: node`,
},
{
description:
"Should complete YAML key-value pair inside a nested structure",
filename: "test.yaml",
input: `
version: '3'
services:
db:
image: postgres
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb<|fim|>
`,
llmOutput: `
PGDATA: /var/lib/postgresql/data/pgdata
`,
expectedCompletion: `
PGDATA: /var/lib/postgresql/data/pgdata`,
},
{
description: "Should complete YAML block within an existing block",
filename: "test.yaml",
input: `
pipelines:
branches:
master:
- step:
name: Build and Test
script:
- npm install
- npm run test
- step:
name: Deploy<|fim|>
`,
llmOutput: `
script:
- npm run deploy
`,
expectedCompletion: `
script:
- npm run deploy`,
},
{
description:
"Should autocomplete SQL query with subquery and alias in SELECT clause",
filename: "complex_query.sql",
input: `SELECT u.id,
u.name,
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
FROM users u
WHERE u.active = 1
<|fim|>`,
llmOutput:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion:
"AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
},
];
@ -530,35 +676,6 @@ export const Counter = () => {
expectedCompletion: "0",
filename: "Counter.tsx",
},
{
description: "Should autocomplete React effect hook",
input: `import React, { useState, useEffect } from "react";
export const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds + 1);
}, 1000);
<|fim|>;
return () => clearInterval(interval);
}, [seconds]);
return (
<div>
<p>{seconds} seconds have passed.</p>
</div>
);
};`,
llmOutput: "return () => clearInterval(interval);",
expectedCompletion: "return () => clearInterval(interval);",
filename: "Timer.tsx",
},
{
description: "Should autocomplete React component methods",
input: `import React from "react";
@ -693,8 +810,7 @@ func main() {}`,
}`,
expectedCompletion: `string
State string
ZipCode string
}`,
ZipCode string`,
},
{
@ -746,7 +862,7 @@ func main() {
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(8,2) NOT NULL<FIM> '0.00',
price DECIMAL(8,2) NOT NULL<|fim|> '0.00',
quantity INT NOT NULL DEFAULT '0'
);
@ -761,21 +877,6 @@ func main() {
llmOutput: " DEFAULT",
expectedCompletion: " DEFAULT",
},
{
description:
"Should autocomplete SQL query with subquery and alias in SELECT clause",
filename: "complex_query.sql",
input: `SELECT u.id,
u.name,
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
FROM users u
WHERE u.active = 1
<|fim|>`,
llmOutput:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
},
{
description:
"Should autocomplete multi-line SQL query with CASE statements",
@ -959,70 +1060,6 @@ Smart<|fim|>`,
llmOutput: "ob, 2023-02-10",
expectedCompletion: "ob, 2023-02-10",
},
{
description: "Should complete YAML list item and preserve structure",
filename: "test.yaml",
input: `
services:
- name: web
image: nginx
- name: app<|fim|>
volumes:
- volume1
- volume2
`,
llmOutput: `
image: node
`,
expectedCompletion: `
image: node
`,
},
{
description:
"Should complete YAML key-value pair inside a nested structure",
filename: "test.yaml",
input: `
version: '3'
services:
db:
image: postgres
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb<|fim|>
`,
llmOutput: `
PGDATA: /var/lib/postgresql/data/pgdata
`,
expectedCompletion: `
PGDATA: /var/lib/postgresql/data/pgdata
`,
},
{
description: "Should complete YAML block within an existing block",
filename: "test.yaml",
input: `
pipelines:
branches:
master:
- step:
name: Build and Test
script:
- npm install
- npm run test
- step:
name: Deploy<|fim|>
`,
llmOutput: `
script:
- npm run deploy
`,
expectedCompletion: `
script:
- npm run deploy
`,
},
{
description:
"Should autocomplete a Rust function implementation inside a struct",
@ -1080,8 +1117,7 @@ impl Calculator {
self.result /= number;
} else {
println!("Cannot divide by zero.");
}
}`,
}`,
},
{
description: "Should autocomplete Rust struct definition",
@ -1562,10 +1598,21 @@ interface User {
age: number;
}`,
expectedCompletion: `mail: string;
age: number;
age: number;`,
},
{
description: "Should autocomplete TypeScript interface declarations",
filename: "autocomplete.ts",
input: `interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {}
interface AutocompleteCodeSnippet`,
llmOutput: ` extends BaseAutocompleteSnippet {
filepath: string;
}`,
expectedCompletion: ` extends BaseAutocompleteSnippet {
filepath: string;
}`,
},
{
description:
"Should autocomplete a TypeScript arrow function inside a variable assignment",
@ -1803,8 +1850,7 @@ let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`,
Address: string
}`,
expectedCompletion: `
Address: string
}`,
Address: string`,
},
{
@ -2085,4 +2131,70 @@ export default {
llmOutput: "}",
expectedCompletion: "}",
},
{
description:
"Should handle autocomplete in two similar TypeScript functions",
filename: "List.svelte",
input: `
import { createClient, RedisClientType } from "redis";
import { IKeyValueStore } from "./index.js";
export class RedisKeyValueStore implements IKeyValueStore {
private client: RedisClientType;
constructor(redisUrl: string) {
this.client = createClient({
url: redisUrl
.replace("https://", "redis://")
.replace("http://", "redis://"),
});
this.client.on("connect", () => console.log("Redis Connected"));
this.client.on("error", (err) => console.log("Redis Client Error", err));
this.client.connect();
}
public async has(tableName: string, key: string): Promise<boolean> {
return (await this.client.exists(this._getKey(tableName, key))) > 0;
}
public async keys(tableName: string): Promise<string[]> {
const keys = await this.client.keys(this._getTableKey(tableName));
return keys.map((key) => key.split("::")[1]);
}
public async put(
tableName: string,
key: string,
value: string,
): Promise<void> {
await this.client.set(this._getKey(tableName, key), value);
}
public async get(
tableName: string,
key: string,
): Promise<string | undefined> {
const value = await this.client.get(this._getKey(tableName, key));
return value ?? undefined;
}
public async deleteAll(tableName: string): Promise<void> {
await this.client.del(this._getTableKey(tableName));
}
<|fim|>
public async remove(tableName: string, key: string): Promise<boolean> {
const result = await this.client.del(this._getKey(tableName, key));
return result > 0;
}
}
`,
llmOutput: ` public async delete(tableName: string, key: string): Promise<void> {
await this.client.del(this._getKey(tableName, key));
}`,
expectedCompletion: ` public async delete(tableName: string, key: string): Promise<void> {
await this.client.del(this._getKey(tableName, key));
}`,
},
];

View file

@ -1,8 +1,6 @@
import fs from "node:fs";
import path from "node:path";
import Mock from "../../../llm/llms/Mock";
import { testConfigHandler, testIde } from "../../../test/util/fixtures";
import MockLLM from "../../../llm/llms/Mock";
import { testConfigHandler, testIde } from "../../../test/fixtures";
import { joinPathsToUri } from "../../../util/uri";
import { CompletionProvider } from "../../CompletionProvider";
import { AutocompleteInput } from "../../util/types";
@ -18,7 +16,7 @@ export interface AutocompleteFileringTestInput {
filename: string;
input: string;
llmOutput: string;
expectedCompletion: string | null;
expectedCompletion: string | null | undefined;
options?: {
only?: boolean;
};
@ -30,7 +28,7 @@ export async function testAutocompleteFiltering(
const { prefix, suffix } = parseFimExample(test.input);
// Setup necessary objects
const llm = new Mock({
const llm = new MockLLM({
model: "mock",
});
llm.completion = test.llmOutput;
@ -39,8 +37,8 @@ export async function testAutocompleteFiltering(
// Create a real file
const [workspaceDir] = await ide.getWorkspaceDirs();
const filepath = path.join(workspaceDir, test.filename);
fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, ""));
const fileUri = joinPathsToUri(workspaceDir, test.filename);
await ide.writeFile(fileUri, test.input.replace(FIM_DELIMITER, ""));
// Prepare completion input and provider
const completionProvider = new CompletionProvider(
@ -54,9 +52,9 @@ export async function testAutocompleteFiltering(
const line = prefix.split("\n").length - 1;
const character = prefix.split("\n")[line].length;
const autocompleteInput: AutocompleteInput = {
clipboardText: "",
isUntitledFile: false,
completionId: "test-completion-id",
filepath,
filepath: fileUri,
pos: {
line,
character,

View file

@ -1,4 +1,5 @@
import { jest } from "@jest/globals";
import { ListenableGenerator } from "./ListenableGenerator";
describe("ListenableGenerator", () => {

View file

@ -43,11 +43,15 @@ function isExtremeRepetition(completion: string): boolean {
}
return false;
}
export function isOnlyWhitespace(completion: string): boolean {
function isOnlyWhitespace(completion: string): boolean {
const whitespaceRegex = /^[\s]+$/;
return whitespaceRegex.test(completion);
}
function isBlank(completion: string): boolean {
return completion.trim().length === 0;
}
export function postprocessCompletion({
completion,
llm,
@ -60,6 +64,11 @@ export function postprocessCompletion({
suffix: string;
}): string | undefined {
// Don't return empty
if (isBlank(completion)) {
return undefined;
}
// Don't return whitespace
if (isOnlyWhitespace(completion)) {
return undefined;
}
@ -81,6 +90,17 @@ export function postprocessCompletion({
completion = completion.slice(1);
}
}
// When there is no suffix, Codestral tends to begin with a new line
// We do this to avoid double new lines
if (
suffix.length === 0 &&
prefix.endsWith("\n\n") &&
completion.startsWith("\n")
) {
// Remove a single leading \n from the completion
completion = completion.slice(1);
}
}
if (llm.model.includes("granite")) {
@ -112,16 +132,8 @@ export function postprocessCompletion({
// }
// If prefix ends with space and so does completion, then remove the space from completion
if (
prefix.split("\n").pop()?.trim() !== "" &&
prefix.endsWith(" ") &&
completion.startsWith(" ")
) {
completion = completion.slice(1);
}
// Qwen often adds an extra space to the start
if (llm.model.toLowerCase().includes("qwen") && completion.startsWith(" ")) {
if (prefix.endsWith(" ") && completion.startsWith(" ")) {
completion = completion.slice(1);
}

View file

@ -1,10 +1,8 @@
import path from "node:path";
import ignore from "ignore";
import { IDE } from "../..";
import { getBasename } from "../../util";
import { getConfigJsonPath } from "../../util/paths";
import { findUriInDirs } from "../../util/uri";
import { HelperVars } from "../util/HelperVars";
async function isDisabledForFile(
@ -15,26 +13,14 @@ async function isDisabledForFile(
if (disableInFiles) {
// Relative path needed for `ignore`
const workspaceDirs = await ide.getWorkspaceDirs();
let filepath = currentFilepath;
for (const workspaceDir of workspaceDirs) {
const relativePath = path.relative(workspaceDir, filepath);
const relativePathBase = relativePath.split(path.sep).at(0);
const isInWorkspace =
!path.isAbsolute(relativePath) && relativePathBase !== "..";
if (isInWorkspace) {
filepath = path.relative(workspaceDir, filepath);
break;
}
}
// Worst case we can check filetype glob patterns
if (filepath === currentFilepath) {
filepath = getBasename(filepath);
}
const { relativePathOrBasename } = findUriInDirs(
currentFilepath,
workspaceDirs,
);
// @ts-ignore
const pattern = ignore.default().add(disableInFiles);
if (pattern.ignores(filepath)) {
if (pattern.ignores(relativePathOrBasename)) {
return true;
}
}
@ -64,8 +50,15 @@ export async function shouldPrefilter(
}
// Check whether autocomplete is disabled for this file
const disableInFiles = [...(helper.options.disableInFiles ?? []), "*.prompt"];
if (await isDisabledForFile(helper.filepath, disableInFiles, ide)) {
return true;
}
// Don't offer completions when we have no information (untitled file and no file contents)
if (
await isDisabledForFile(helper.filepath, helper.options.disableInFiles, ide)
helper.filepath.includes("Untitled") &&
helper.fileContents.trim() === ""
) {
return true;
}

View file

@ -0,0 +1,139 @@
import { IDE } from "../../index";
import { findUriInDirs } from "../../util/uri";
import { ContextRetrievalService } from "../context/ContextRetrievalService";
import { GetLspDefinitionsFunction } from "../types";
import { HelperVars } from "../util/HelperVars";
import {
AutocompleteClipboardSnippet,
AutocompleteCodeSnippet,
AutocompleteDiffSnippet,
AutocompleteSnippetType,
} from "./types";
export interface SnippetPayload {
rootPathSnippets: AutocompleteCodeSnippet[];
importDefinitionSnippets: AutocompleteCodeSnippet[];
ideSnippets: AutocompleteCodeSnippet[];
recentlyEditedRangeSnippets: AutocompleteCodeSnippet[];
diffSnippets: AutocompleteDiffSnippet[];
clipboardSnippets: AutocompleteClipboardSnippet[];
}
function racePromise<T>(promise: Promise<T[]>): Promise<T[]> {
const timeoutPromise = new Promise<T[]>((resolve) => {
setTimeout(() => resolve([]), 100);
});
return Promise.race([promise, timeoutPromise]);
}
// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems,
// or they might separately track recently edited ranges)
async function getIdeSnippets(
helper: HelperVars,
ide: IDE,
getDefinitionsFromLsp: GetLspDefinitionsFunction,
): Promise<AutocompleteCodeSnippet[]> {
const ideSnippets = await getDefinitionsFromLsp(
helper.input.filepath,
helper.fullPrefix + helper.fullSuffix,
helper.fullPrefix.length,
ide,
helper.lang,
);
if (helper.options.onlyMyCode) {
const workspaceDirs = await ide.getWorkspaceDirs();
return ideSnippets.filter((snippet) =>
workspaceDirs.some(
(dir) => !!findUriInDirs(snippet.filepath, [dir]).foundInDir,
),
);
}
return ideSnippets;
}
function getSnippetsFromRecentlyEditedRanges(
helper: HelperVars,
): AutocompleteCodeSnippet[] {
if (helper.options.useRecentlyEdited === false) {
return [];
}
return helper.input.recentlyEditedRanges.map((range) => {
return {
filepath: range.filepath,
content: range.lines.join("\n"),
type: AutocompleteSnippetType.Code,
};
});
}
const getClipboardSnippets = async (
ide: IDE,
): Promise<AutocompleteClipboardSnippet[]> => {
const content = await ide.getClipboardContent();
return [content].map((item) => {
return {
content: item.text,
copiedAt: item.copiedAt,
type: AutocompleteSnippetType.Clipboard,
};
});
};
const getDiffSnippets = async (
ide: IDE,
): Promise<AutocompleteDiffSnippet[]> => {
const diff = await ide.getDiff(true);
return diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
});
};
export const getAllSnippets = async ({
helper,
ide,
getDefinitionsFromLsp,
contextRetrievalService,
}: {
helper: HelperVars;
ide: IDE;
getDefinitionsFromLsp: GetLspDefinitionsFunction;
contextRetrievalService: ContextRetrievalService;
}): Promise<SnippetPayload> => {
const recentlyEditedRangeSnippets =
getSnippetsFromRecentlyEditedRanges(helper);
const [
rootPathSnippets,
importDefinitionSnippets,
ideSnippets,
diffSnippets,
clipboardSnippets,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
),
racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)),
racePromise(getDiffSnippets(ide)),
racePromise(getClipboardSnippets(ide)),
]);
return {
rootPathSnippets,
importDefinitionSnippets,
ideSnippets,
recentlyEditedRangeSnippets,
diffSnippets,
clipboardSnippets,
};
};

View file

@ -0,0 +1 @@
export * from "./getAllSnippets";

View file

@ -0,0 +1,29 @@
export enum AutocompleteSnippetType {
Code = "code",
Diff = "diff",
Clipboard = "clipboard",
}
interface BaseAutocompleteSnippet {
content: string;
type: AutocompleteSnippetType;
}
export interface AutocompleteCodeSnippet extends BaseAutocompleteSnippet {
filepath: string;
type: AutocompleteSnippetType.Code;
}
export interface AutocompleteDiffSnippet extends BaseAutocompleteSnippet {
type: AutocompleteSnippetType.Diff;
}
export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {
type: AutocompleteSnippetType.Clipboard;
copiedAt: string;
}
export type AutocompleteSnippet =
| AutocompleteCodeSnippet
| AutocompleteDiffSnippet
| AutocompleteClipboardSnippet;

View file

@ -1,8 +1,15 @@
// Fill in the middle prompts
import { CompletionOptions } from "../../index.js";
import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js";
import { AutocompleteSnippet } from "../context/ranking/index.js";
import {
getLastNUriRelativePathParts,
getShortestUniqueRelativeUriPaths,
} from "../../util/uri.js";
import {
AutocompleteCodeSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
} from "../snippets/types.js";
export interface AutocompleteTemplate {
compilePrefixSuffix?: (
@ -11,6 +18,7 @@ export interface AutocompleteTemplate {
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
workspaceUris: string[],
) => [string, string];
template:
| string
@ -21,6 +29,7 @@ export interface AutocompleteTemplate {
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
workspaceUris: string[],
) => string);
completionOptions?: Partial<CompletionOptions>;
}
@ -69,25 +78,43 @@ const codestralFimTemplate: AutocompleteTemplate = {
const codestralMultifileFimTemplate: AutocompleteTemplate = {
compilePrefixSuffix: (
prefix: string,
suffix: string,
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
prefix,
suffix,
filepath,
reponame,
snippets,
workspaceUris,
): [string, string] => {
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
return [`+++++ ${getLastNPathParts(filepath, 2)}\n${prefix}`, suffix];
return [
`+++++ ${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n${prefix}`,
suffix,
];
}
return [prefix, suffix];
}
const relativePaths = shortestRelativePaths([
...snippets.map((snippet) => snippet.filepath),
filepath,
]);
const relativePaths = getShortestUniqueRelativeUriPaths(
[
...snippets.map((snippet) =>
"filepath" in snippet ? snippet.filepath : "file:///Untitled.txt",
),
filepath,
],
workspaceUris,
);
const otherFiles = snippets
.map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`)
.map((snippet, i) => {
if (snippet.type === AutocompleteSnippetType.Diff) {
return snippet.content;
}
return `+++++ ${relativePaths[i]}\n${snippet.content}`;
})
.join("\n\n");
return [
`${otherFiles}\n\n+++++ ${
relativePaths[relativePaths.length - 1]
@ -95,14 +122,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
suffix,
];
},
template: (
prefix: string,
suffix: string,
filepath: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
): string => {
template: (prefix: string, suffix: string): string => {
return `[SUFFIX]${suffix}[PREFIX]${prefix}`;
},
completionOptions: {
@ -128,20 +148,20 @@ const codegemmaFimTemplate: AutocompleteTemplate = {
// https://arxiv.org/pdf/2402.19173.pdf section 5.1
const starcoder2FimTemplate: AutocompleteTemplate = {
template: (
prefix: string,
suffix: string,
filename: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
prefix,
suffix,
filename,
reponame,
language,
snippets,
workspaceUris,
): string => {
const otherFiles =
snippets.length === 0
? ""
: `<file_sep>${snippets
.map((snippet) => {
return snippet.contents;
// return `${getBasename(snippet.filepath)}\n${snippet.contents}`;
return snippet.content;
})
.join("<file_sep>")}<file_sep>`;
@ -182,17 +202,22 @@ const deepseekFimTemplate: AutocompleteTemplate = {
// https://github.com/THUDM/CodeGeeX4/blob/main/guides/Infilling_guideline.md
const codegeexFimTemplate: AutocompleteTemplate = {
template: (
prefix: string,
suffix: string,
filepath: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
prefix,
suffix,
filepath,
reponame,
language,
allSnippets,
workspaceUris,
): string => {
const relativePaths = shortestRelativePaths([
...snippets.map((snippet) => snippet.filepath),
filepath,
]);
const snippets = allSnippets.filter(
(snippet) => snippet.type === AutocompleteSnippetType.Code,
) as AutocompleteCodeSnippet[];
const relativePaths = getShortestUniqueRelativeUriPaths(
[...snippets.map((snippet) => snippet.filepath), filepath],
workspaceUris,
);
const baseTemplate = `###PATH:${
relativePaths[relativePaths.length - 1]
}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
@ -200,7 +225,7 @@ const codegeexFimTemplate: AutocompleteTemplate = {
return `<|user|>\n${baseTemplate}<|assistant|>\n`;
}
const references = `###REFERENCE:\n${snippets
.map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.contents}\n`)
.map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.content}\n`)
.join("###REFERENCE:\n")}`;
const prompt = `<|user|>\n${references}\n${baseTemplate}<|assistant|>\n`;
return prompt;
@ -227,14 +252,7 @@ Fill in the blank to complete the code block. Your response should include only
};
const holeFillerTemplate: AutocompleteTemplate = {
template: (
prefix: string,
suffix: string,
filename: string,
reponame: string,
language: string,
snippets: AutocompleteSnippet[],
) => {
template: (prefix: string, suffix: string) => {
// From https://github.com/VictorTaelin/AI-scripts
const SYSTEM_MSG = `You are a HOLE FILLER. You are provided with a file containing holes, formatted as '{{HOLE_NAME}}'. Your TASK is to complete with a string to replace this hole with, inside a <COMPLETION/> XML tag, including context-aware indentation, if needed. All completions MUST be truthful, accurate, well-written and correct.

View file

@ -0,0 +1,75 @@
import { countTokens } from "../../llm/countTokens";
import { SnippetPayload } from "../snippets";
import {
AutocompleteCodeSnippet,
AutocompleteSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { isValidSnippet } from "./validation";
const getRemainingTokenCount = (helper: HelperVars): number => {
const tokenCount = countTokens(helper.prunedCaretWindow, helper.modelName);
return helper.options.maxPromptTokens - tokenCount;
};
const TOKEN_BUFFER = 10; // We may need extra tokens for snippet description etc.
/**
* Shuffles an array in place using the Fisher-Yates algorithm.
* @param array The array to shuffle.
* @returns The shuffled array.
*/
const shuffleArray = <T>(array: T[]): T[] => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
};
function filterSnippetsAlreadyInCaretWindow(
snippets: AutocompleteCodeSnippet[],
caretWindow: string,
): AutocompleteCodeSnippet[] {
return snippets.filter(
(s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()),
);
}
export const getSnippets = (
helper: HelperVars,
payload: SnippetPayload,
): AutocompleteSnippet[] => {
const snippets = [
...payload.diffSnippets,
...payload.clipboardSnippets,
...shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
),
),
];
const finalSnippets = [];
let remainingTokenCount = getRemainingTokenCount(helper);
while (remainingTokenCount > 0 && snippets.length > 0) {
const snippet = snippets.shift();
if (!snippet || !isValidSnippet(snippet)) {
continue;
}
const snippetSize =
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
if (remainingTokenCount >= snippetSize) {
finalSnippets.push(snippet);
remainingTokenCount -= snippetSize;
}
}
return finalSnippets;
};

View file

@ -0,0 +1,91 @@
import { getLastNUriRelativePathParts } from "../../util/uri";
import {
AutocompleteClipboardSnippet,
AutocompleteCodeSnippet,
AutocompleteDiffSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
const getCommentMark = (helper: HelperVars) => {
return helper.lang.singleLineComment;
};
const addCommentMarks = (text: string, helper: HelperVars) => {
const commentMark = getCommentMark(helper);
return text
.trim()
.split("\n")
.map((line) => `${commentMark} ${line}`)
.join("\n");
};
const formatClipboardSnippet = (
snippet: AutocompleteClipboardSnippet,
workspaceDirs: string[],
): AutocompleteCodeSnippet => {
return formatCodeSnippet(
{
filepath: "file:///Untitled.txt",
content: snippet.content,
type: AutocompleteSnippetType.Code,
},
workspaceDirs,
);
};
const formatCodeSnippet = (
snippet: AutocompleteCodeSnippet,
workspaceDirs: string[],
): AutocompleteCodeSnippet => {
return {
...snippet,
content: `Path: ${getLastNUriRelativePathParts(workspaceDirs, snippet.filepath, 2)}\n${snippet.content}`,
};
};
const formatDiffSnippet = (
snippet: AutocompleteDiffSnippet,
): AutocompleteDiffSnippet => {
return snippet;
};
const commentifySnippet = (
helper: HelperVars,
snippet: AutocompleteSnippet,
): AutocompleteSnippet => {
return {
...snippet,
content: addCommentMarks(snippet.content, helper),
};
};
export const formatSnippets = (
helper: HelperVars,
snippets: AutocompleteSnippet[],
workspaceDirs: string[],
): string => {
const currentFilepathComment = addCommentMarks(
getLastNUriRelativePathParts(workspaceDirs, helper.filepath, 2),
helper,
);
return (
snippets
.map((snippet) => {
switch (snippet.type) {
case AutocompleteSnippetType.Code:
return formatCodeSnippet(snippet, workspaceDirs);
case AutocompleteSnippetType.Diff:
return formatDiffSnippet(snippet);
case AutocompleteSnippetType.Clipboard:
return formatClipboardSnippet(snippet, workspaceDirs);
}
})
.map((item) => {
return commentifySnippet(helper, item).content;
})
.join("\n") + `\n${currentFilepathComment}`
);
};

View file

@ -10,7 +10,7 @@ const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
const PYTHON_ENCODING = "#- coding: utf-8";
const CODE_BLOCK_END = "```";
const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
// const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END];
export function getStopTokens(
@ -25,7 +25,6 @@ export function getStopTokens(
...(model.toLowerCase().includes("starcoder2")
? STARCODER2_T_ARTIFACTS
: []),
...(lang.stopWords ?? []),
// ...lang.topLevelKeywords.map((word) => `\n${word}`),
];

View file

@ -1,61 +1,18 @@
import Handlebars from "handlebars";
import { CompletionOptions } from "../..";
import { getBasename, getLastNPathParts } from "../../util";
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
import { AutocompleteSnippet } from "../context/ranking";
import { HelperVars } from "../util/HelperVars";
import { SnippetPayload } from "../snippets";
import {
AutocompleteTemplate,
getTemplateForModel,
} from "./AutocompleteTemplate";
import { getSnippets } from "./filtering";
import { getUriPathBasename } from "../../util/uri";
import { formatSnippets } from "./formatting";
import { getStopTokens } from "./getStopTokens";
import { countTokens } from "../../llm/countTokens";
const addCommentMarks = (text: string, language: AutocompleteLanguageInfo) => {
const comment = language.singleLineComment;
const lines = [
...text
.trim()
.split("\n")
.map((line) => `${comment} ${line}`),
];
return lines.join("\n");
};
export function formatExternalSnippet(
filepath: string,
snippet: string,
language: AutocompleteLanguageInfo,
) {
const filePathString = `Path: ${getBasename(filepath)}\n`;
return addCommentMarks(`${filePathString}${snippet}`, language);
}
function getContextComments(
snippets: AutocompleteSnippet[],
lang: AutocompleteLanguageInfo,
filepath: string,
) {
if (snippets.length === 0) {
return "";
}
const headerSnipper = `\n\n${lang.singleLineComment} Related code:\n`;
const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`;
const formattedSnippets =
headerSnipper +
snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n") +
fileNameSnippet;
return formattedSnippets;
}
function getTemplate(helper: HelperVars): AutocompleteTemplate {
if (helper.options.template) {
@ -76,7 +33,7 @@ function renderStringTemplate(
filepath: string,
reponame: string,
) {
const filename = getBasename(filepath);
const filename = getUriPathBasename(filepath);
const compiledTemplate = Handlebars.compile(template);
return compiledTemplate({
@ -88,63 +45,14 @@ function renderStringTemplate(
});
}
const formatDiff = (helper: HelperVars, diff?: string) => {
if (!diff) return "";
const tokenCount = countTokens(diff, helper.modelName);
if (tokenCount > helper.maxDiffTokens) {
return "";
}
return `${diff}\n\n`;
};
const MAX_CLIPBOARD_AGE = 5 * 60 * 1000;
const formatClipboardContent = (
helper: HelperVars,
{ text, copiedAt }: { text: string; copiedAt: string },
) => {
const currDate = new Date();
const isTooOld =
currDate.getTime() - new Date(copiedAt).getTime() > MAX_CLIPBOARD_AGE;
if (isTooOld) {
return "";
}
const tokenCount = countTokens(text, helper.modelName);
const isTooLong = tokenCount > helper.maxClipboardTokens;
if (isTooLong) {
return "";
}
return (
addCommentMarks(
`Recently copied by user:${text.includes("\n") ? "\n" : ""} ${text}`,
helper.lang,
) + "\n"
);
};
export function renderPrompt({
snippets,
snippetPayload,
workspaceDirs,
helper,
diff,
clipboardContent,
}: {
snippets: AutocompleteSnippet[];
snippetPayload: SnippetPayload;
workspaceDirs: string[];
helper: HelperVars;
diff?: string;
clipboardContent: {
text: string;
copiedAt: string;
};
}): {
prompt: string;
prefix: string;
@ -154,12 +62,17 @@ export function renderPrompt({
// If prefix is manually passed
let prefix = helper.input.manuallyPassPrefix || helper.prunedPrefix;
let suffix = helper.input.manuallyPassPrefix ? "" : helper.prunedSuffix;
if (suffix === "") {
suffix = "\n";
}
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
const reponame = getUriPathBasename(workspaceDirs[0] ?? "myproject");
const { template, compilePrefixSuffix, completionOptions } =
getTemplate(helper);
const snippets = getSnippets(helper, snippetPayload);
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
// into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint
if (compilePrefixSuffix) {
@ -169,19 +82,11 @@ export function renderPrompt({
helper.filepath,
reponame,
snippets,
helper.workspaceUris,
);
} else {
const contextComments = getContextComments(
snippets,
helper.lang,
helper.filepath,
);
const formattedDiff = formatDiff(helper, diff);
const formattedClipboard = formatClipboardContent(helper, clipboardContent);
prefix = [formattedClipboard, formattedDiff, contextComments, prefix].join(
"",
);
const formattedSnippets = formatSnippets(helper, snippets, workspaceDirs);
prefix = [formattedSnippets, prefix].join("\n");
}
const prompt =
@ -202,6 +107,7 @@ export function renderPrompt({
reponame,
helper.lang.name,
snippets,
helper.workspaceUris,
);
const stopTokens = getStopTokens(

View file

@ -0,0 +1,29 @@
import {
AutocompleteClipboardSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
} from "../snippets/types";
const MAX_CLIPBOARD_AGE = 5 * 60 * 1000;
const isValidClipboardSnippet = (
snippet: AutocompleteClipboardSnippet,
): boolean => {
const currDate = new Date();
const isTooOld =
currDate.getTime() - new Date(snippet.copiedAt).getTime() >
MAX_CLIPBOARD_AGE;
return !isTooOld;
};
export const isValidSnippet = (snippet: AutocompleteSnippet): boolean => {
if (snippet.content.trim() === "") return false;
if (snippet.type === AutocompleteSnippetType.Clipboard) {
return isValidClipboardSnippet(snippet);
}
return true;
};

View file

@ -0,0 +1,20 @@
import { IDE, RangeInFileWithContents } from "../index";
import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo";
import { AutocompleteCodeSnippet } from "./snippets/types";
/**
* @deprecated This type should be removed in the future or renamed.
* We have a new interface called AutocompleteSnippet which is more
* general.
*/
export type AutocompleteSnippetDeprecated = RangeInFileWithContents & {
score?: number;
};
export type GetLspDefinitionsFunction = (
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE,
lang: AutocompleteLanguageInfo,
) => Promise<AutocompleteCodeSnippet[]>;

View file

@ -1,6 +1,7 @@
import { logDevData } from "../../util/devdata";
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
import { Telemetry } from "../../util/posthog";
import { getUriFileExtension } from "../../util/uri";
import { AutocompleteOutcome } from "./types";
@ -105,14 +106,13 @@ export class AutocompleteLoggingService {
completionId: restOfOutcome.completionId,
completionOptions: restOfOutcome.completionOptions,
debounceDelay: restOfOutcome.debounceDelay,
fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0],
fileExtension: getUriFileExtension(restOfOutcome.filepath),
maxPromptTokens: restOfOutcome.maxPromptTokens,
modelName: restOfOutcome.modelName,
modelProvider: restOfOutcome.modelProvider,
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
useRootPathContext: restOfOutcome.useRootPathContext,
},
true,
);

View file

@ -20,6 +20,7 @@ import { AutocompleteInput } from "./types";
export class HelperVars {
lang: AutocompleteLanguageInfo;
treePath: AstPath | undefined;
workspaceUris: string[] = [];
private _fileContents: string | undefined;
private _fileLines: string[] | undefined;
@ -43,6 +44,8 @@ export class HelperVars {
return;
}
this.workspaceUris = await this.ide.getWorkspaceDirs();
this._fileContents =
this.input.manuallyPassFileContents ??
(await this.ide.readFile(this.filepath));
@ -114,17 +117,6 @@ export class HelperVars {
get pos() {
return this.input.pos;
}
get maxSnippetTokens() {
return this.options.maxPromptTokens * this.options.maxSnippetPercentage;
}
get maxDiffTokens() {
return this.options.maxPromptTokens * this.options.maxDiffPercentage;
}
get maxClipboardTokens() {
return this.options.maxPromptTokens * this.options.maxClipboardPercentage;
}
get prunedCaretWindow() {
return this.prunedPrefix + this.prunedSuffix;

View file

@ -13,12 +13,12 @@ export type RecentlyEditedRange = RangeInFile & {
};
export interface AutocompleteInput {
isUntitledFile: boolean;
completionId: string;
filepath: string;
pos: Position;
recentlyEditedFiles: RangeInFileWithContents[];
recentlyEditedRanges: RecentlyEditedRange[];
clipboardText: string;
// Used for notebook files
manuallyPassFileContents?: string;
// Used for VS Code git commit input box

View file

@ -1,6 +1,6 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { renderChatMessage } from "../util/messageContent";
import SlashCommands from "./slash";
@ -29,7 +29,8 @@ export function slashFromCustomCommand(
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
const message = messages[i];
const { role, content } = message;
if (role !== "user") {
continue;
}
@ -41,7 +42,7 @@ export function slashFromCustomCommand(
)
) {
messages[i] = {
...messages[i],
...message,
content: content.map((part) => {
return part.text?.startsWith(`/${customCommand.name}`)
? { ...part, text: promptUserInput }
@ -53,13 +54,16 @@ export function slashFromCustomCommand(
typeof content === "string" &&
content.startsWith(`/${customCommand.name}`)
) {
messages[i] = { ...messages[i], content: promptUserInput };
messages[i] = { ...message, content: promptUserInput };
break;
}
}
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -1,19 +0,0 @@
import { SlashCommand } from "../../";
import EditSlashCommand from "./edit";
const CommentSlashCommand: SlashCommand = {
name: "comment",
description: "Write comments for highlighted code",
run: async function* (sdk) {
for await (const update of EditSlashCommand.run({
...sdk,
input:
"Write comments for this code. Do not change anything about the code itself.",
})) {
yield update;
}
},
};
export default CommentSlashCommand;

View file

@ -1,23 +1,24 @@
import { SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
import { renderChatMessage } from "../../util/messageContent.js";
const CommitMessageCommand: SlashCommand = {
name: "commit",
description: "Generate a commit message for current changes",
run: async function* ({ ide, llm, params }) {
const includeUnstaged = params?.includeUnstaged ?? false;
const includeUnstaged = params?.includeUnstaged ?? true;
const diff = await ide.getDiff(includeUnstaged);
if (!diff || diff.trim() === "") {
if (diff.length === 0) {
yield "No changes detected. Make sure you are in a git repository with current changes.";
return;
}
const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
], new AbortController().signal)) {
yield stripImages(chunk.content);
const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -1,6 +1,6 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { renderChatMessage } from "../../util/messageContent.js";
const PROMPT = (
input: string,
@ -30,7 +30,8 @@ const DraftIssueCommand: SlashCommand = {
return;
}
let title = await llm.complete(
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal,
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
new AbortController().signal,
{ maxTokens: 20 },
);
@ -43,9 +44,12 @@ const DraftIssueCommand: SlashCommand = {
{ role: "user", content: PROMPT(input, title) },
];
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
)) {
body += chunk.content;
yield stripImages(chunk.content);
yield renderChatMessage(chunk);
}
const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(

View file

@ -1,637 +0,0 @@
import {
ContextItemWithId,
ILLM,
RangeInFileWithContents,
SlashCommand,
} from "../../";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
filterEnglishLinesAtStart,
fixCodeLlamaFirstLineIndentation,
stopAtLines,
streamWithNewLines,
} from "../../autocomplete/filtering/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { stripImages } from "../../llm/images";
import {
dedentAndGetCommonWhitespace,
getMarkdownLanguageTagForFile,
} from "../../util/";
import { ctxItemToRifWithContents } from "../util";
const PROMPT = `Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The </modified_code_to_edit> tag should be written to indicate the end of the modified code section. Do not ever use nested tags.
Example:
<file_prefix>
class Database:
def __init__(self):
self._data = {{}}
def get(self, key):
return self._data[key]
</file_prefix>
<code_to_edit>
def set(self, key, value):
self._data[key] = value
</code_to_edit>
<file_suffix>
def clear_all():
self._data = {{}}
</file_suffix>
<user_request>
Raise an error if the key already exists.
</user_request>
<modified_code_to_edit>
def set(self, key, value):
if key in self._data:
raise KeyError(f"Key {{key}} already exists")
self._data[key] = value
</modified_code_to_edit>
Main task:
`;
export async function getPromptParts(
rif: RangeInFileWithContents,
fullFileContents: string,
model: ILLM,
input: string,
tokenLimit: number | undefined,
) {
const maxTokens = Math.floor(model.contextLength / 2);
const BUFFER_FOR_FUNCTIONS = 400;
let totalTokens =
model.countTokens(fullFileContents + PROMPT + input) +
BUFFER_FOR_FUNCTIONS +
maxTokens;
const fullFileContentsList = fullFileContents.split("\n");
const maxStartLine = rif.range.start.line;
const minEndLine = rif.range.end.line;
let curStartLine = 0;
let curEndLine = fullFileContentsList.length - 1;
if (totalTokens > model.contextLength) {
while (curEndLine > minEndLine) {
totalTokens -= model.countTokens(fullFileContentsList[curEndLine]);
curEndLine--;
if (totalTokens < model.contextLength) {
break;
}
}
}
if (totalTokens > model.contextLength) {
while (curStartLine < maxStartLine) {
curStartLine++;
totalTokens -= model.countTokens(fullFileContentsList[curStartLine]);
if (totalTokens < model.contextLength) {
break;
}
}
}
let filePrefix = fullFileContentsList
.slice(curStartLine, maxStartLine - 1)
.join("\n");
let fileSuffix = fullFileContentsList
.slice(minEndLine, curEndLine + 1)
.join("\n");
if (rif.contents.length > 0) {
let lines = rif.contents.split(/\r?\n/);
let firstLine = lines[0] || null;
while (firstLine && firstLine.trim() === "") {
filePrefix += firstLine;
rif.contents = rif.contents.substring(firstLine.length);
lines = rif.contents.split(/\r?\n/);
firstLine = lines[0] || null;
}
let lastLine = lines[lines.length - 1] || null;
while (lastLine && lastLine.trim() === "") {
fileSuffix = lastLine + fileSuffix;
rif.contents = rif.contents.substring(
0,
rif.contents.length - lastLine.length,
);
lines = rif.contents.split(/\r?\n/);
lastLine = lines[lines.length - 1] || null;
}
while (rif.contents.startsWith("\n")) {
filePrefix += "\n";
rif.contents = rif.contents.substring(1);
}
while (rif.contents.endsWith("\n")) {
fileSuffix = `\n${fileSuffix}`;
rif.contents = rif.contents.substring(0, rif.contents.length - 1);
}
}
return { filePrefix, fileSuffix, contents: rif.contents, maxTokens };
}
function compilePrompt(
filePrefix: string,
contents: string,
fileSuffix: string,
input: string,
): string {
if (contents.trim() === "") {
// Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file
return `\
<file_prefix>
${filePrefix}
</file_prefix>
<insertion_code_here>
<file_suffix>
${fileSuffix}
</file_suffix>
<user_request>
${input}
</user_request>
Please output the code to be inserted at the cursor in order to fulfill the user_request. Do NOT preface your answer or write anything other than code. You should not write any tags, just the code. Make sure to correctly indent the code:`;
}
let prompt = PROMPT;
if (filePrefix.trim() !== "") {
prompt += `
<file_prefix>
${filePrefix}
</file_prefix>`;
}
prompt += `
<code_to_edit>
${contents}
</code_to_edit>`;
if (fileSuffix.trim() !== "") {
prompt += `
<file_suffix>
${fileSuffix}
</file_suffix>`;
}
prompt += `
<user_request>
${input}
</user_request>
<modified_code_to_edit>
`;
return prompt;
}
function isEndLine(line: string) {
return (
line.includes("</modified_code_to_edit>") ||
line.includes("</code_to_edit>") ||
line.includes("[/CODE]")
);
}
function lineToBeIgnored(line: string, isFirstLine = false): boolean {
return (
line.includes("```") ||
line.includes("<modified_code_to_edit>") ||
line.includes("<file_prefix>") ||
line.includes("</file_prefix>") ||
line.includes("<file_suffix>") ||
line.includes("</file_suffix>") ||
line.includes("<user_request>") ||
line.includes("</user_request>") ||
line.includes("<code_to_edit>")
);
}
const EditSlashCommand: SlashCommand = {
name: "edit",
description: "Edit selected code",
run: async function* ({ ide, llm, input, history, contextItems, params }) {
let contextItemToEdit = contextItems.find(
(item: ContextItemWithId) =>
item.editing && item.id.providerTitle === "code",
);
if (!contextItemToEdit) {
contextItemToEdit = contextItems.find(
(item: ContextItemWithId) => item.id.providerTitle === "code",
);
}
if (!contextItemToEdit) {
yield "Please highlight the code you want to edit, then press `cmd/ctrl+shift+L` to add it to chat";
return;
}
// Strip unecessary parts of the input (the fact that you have to do this is suboptimal, should be refactored away)
let content = history[history.length - 1].content;
if (typeof content !== "string") {
content.forEach((part) => {
if (part.text?.startsWith("/edit")) {
part.text = part.text.replace("/edit", "").trimStart();
}
});
} else if (input?.startsWith("/edit")) {
content = input.replace("/edit", "").trimStart();
} else if (input?.startsWith("/comment")) {
content = input.replace("/comment", "").trimStart();
}
let userInput = stripImages(content).replace(
`\`\`\`${contextItemToEdit.name}\n${contextItemToEdit.content}\n\`\`\`\n`,
"",
);
// if the above replace fails to find a match, the code will still be present
// in the userInput. Replace it with input if available.
if (userInput.includes("```") && (input !== "" || !input)) {
userInput = input;
}
const rif: RangeInFileWithContents =
ctxItemToRifWithContents(contextItemToEdit);
await ide.saveFile(rif.filepath);
const fullFileContents = await ide.readFile(rif.filepath);
let { filePrefix, contents, fileSuffix, maxTokens } = await getPromptParts(
rif,
fullFileContents,
llm,
userInput,
params?.tokenLimit,
);
const [dedentedContents, commonWhitespace] =
dedentAndGetCommonWhitespace(contents);
contents = dedentedContents;
const prompt = compilePrompt(filePrefix, contents, fileSuffix, userInput);
const fullFileContentsLines = fullFileContents.split("\n");
const fullPrefixLines = fullFileContentsLines.slice(
0,
Math.max(0, rif.range.start.line - 1),
);
const fullSuffixLines = fullFileContentsLines.slice(rif.range.end.line);
let linesToDisplay: string[] = [];
async function sendDiffUpdate(lines: string[], final = false) {
const completion = lines.join("\n");
// Don't do this at the very end, just show the inserted code
if (final) {
linesToDisplay = [];
}
// Only recalculate at every new-line, because this is sort of expensive
else if (completion.endsWith("\n")) {
const contentsLines = rif.contents.split("\n");
let rewrittenLines = 0;
for (const line of lines) {
for (let i = rewrittenLines; i < contentsLines.length; i++) {
if (
// difflib.SequenceMatcher(
// null, line, contentsLines[i]
// ).ratio()
// > 0.7
line.trim() === contentsLines[i].trim() && // Temp replacement for difflib (TODO)
contentsLines[i].trim() !== ""
) {
rewrittenLines = i + 1;
break;
}
}
}
linesToDisplay = contentsLines.slice(rewrittenLines);
}
const newFileContents = `${fullPrefixLines.join("\n")}\n${completion}\n${
linesToDisplay.length > 0 ? `${linesToDisplay.join("\n")}\n` : ""
}${fullSuffixLines.join("\n")}`;
const stepIndex = history.length - 1;
await ide.showDiff(rif.filepath, newFileContents, stepIndex);
}
// Important state variables
// -------------------------
const originalLines = rif.contents === "" ? [] : rif.contents.split("\n");
// In the actual file, taking into account block offset
let currentLineInFile = rif.range.start.line;
let currentBlockLines: string[] = [];
let originalLinesBelowPreviousBlocks = originalLines;
// The start of the current block in file, taking into account block offset
let currentBlockStart = -1;
let offsetFromBlocks = 0;
// Don't end the block until you've matched N simultaneous lines
// This helps avoid many tiny blocks
const LINES_TO_MATCH_BEFORE_ENDING_BLOCK = 2;
// If a line has been matched at the end of the block, this is its index within originalLinesBelowPreviousBlocks
// Except we are keeping track of multiple potentialities, so it's a list
// We always check the lines following each of these leads, but if multiple make it out at the end, we use the first one
// This is a tuple of (index_of_last_matched_line, number_of_lines_matched)
let indicesOfLastMatchedLines: [number, number][] = [];
async function handleGeneratedLine(line: string) {
if (currentBlockLines.length === 0) {
// Set this as the start of the next block
currentBlockStart =
rif.range.start.line +
originalLines.length -
originalLinesBelowPreviousBlocks.length +
offsetFromBlocks;
if (
originalLinesBelowPreviousBlocks.length > 0 &&
line === originalLinesBelowPreviousBlocks[0]
) {
// Line is equal to the next line in file, move past this line
originalLinesBelowPreviousBlocks =
originalLinesBelowPreviousBlocks.slice(1);
return;
}
}
// In a block, and have already matched at least one line
// Check if the next line matches, for each of the candidates
const matchesFound: any[] = [];
let firstValidMatch: any = null;
for (const [
index_of_last_matched_line,
num_lines_matched,
] of indicesOfLastMatchedLines) {
if (
index_of_last_matched_line + 1 <
originalLinesBelowPreviousBlocks.length &&
line ===
originalLinesBelowPreviousBlocks[index_of_last_matched_line + 1]
) {
matchesFound.push([
index_of_last_matched_line + 1,
num_lines_matched + 1,
]);
if (
firstValidMatch === null &&
num_lines_matched + 1 >= LINES_TO_MATCH_BEFORE_ENDING_BLOCK
) {
firstValidMatch = [
index_of_last_matched_line + 1,
num_lines_matched + 1,
];
}
}
}
indicesOfLastMatchedLines = matchesFound;
if (firstValidMatch !== null) {
// We've matched the required number of lines, insert suggestion!
// We added some lines to the block that were matched (including maybe some blank lines)
// So here we will strip all matching lines from the end of currentBlockLines
const linesStripped: string[] = [];
let indexOfLastLineInBlock: number = firstValidMatch[0];
while (
currentBlockLines.length > 0 &&
currentBlockLines[currentBlockLines.length - 1] ===
originalLinesBelowPreviousBlocks[indexOfLastLineInBlock - 1]
) {
linesStripped.push(currentBlockLines.pop() as string);
indexOfLastLineInBlock -= 1;
}
// Reset current block / update variables
currentLineInFile += 1;
offsetFromBlocks += currentBlockLines.length;
originalLinesBelowPreviousBlocks =
originalLinesBelowPreviousBlocks.slice(indexOfLastLineInBlock + 1);
currentBlockLines = [];
currentBlockStart = -1;
indicesOfLastMatchedLines = [];
return;
}
// Always look for new matching candidates
const newMatches: any[] = [];
for (let i = 0; i < originalLinesBelowPreviousBlocks.length; i++) {
const ogLine = originalLinesBelowPreviousBlocks[i];
// TODO: It's a bit sus to be disqualifying empty lines.
// What you ideally do is find ALL matches, and then throw them out as you check the following lines
if (ogLine === line) {
// and og_line.trim() !== "":
newMatches.push([i, 1]);
}
}
indicesOfLastMatchedLines = indicesOfLastMatchedLines.concat(newMatches);
// Make sure they are sorted by index
indicesOfLastMatchedLines = indicesOfLastMatchedLines.sort(
(a, b) => a[0] - b[0],
);
currentBlockLines.push(line);
}
let messages = history;
messages[messages.length - 1] = { role: "user", content: prompt };
let linesOfPrefixCopied = 0;
const lines = [];
let unfinishedLine = "";
let completionLinesCovered = 0;
let repeatingFileSuffix = false;
const lineBelowHighlightedRange = fileSuffix.trim().split("\n")[0];
// Use custom templates defined by the model
const template = llm.promptTemplates?.edit;
let generator: AsyncGenerator<string>;
if (template) {
const rendered = llm.renderPromptTemplate(
template,
// typeof template === 'string' ? template : template.prompt,
messages.slice(0, messages.length - 1),
{
codeToEdit: rif.contents,
userInput,
filePrefix: filePrefix,
fileSuffix: fileSuffix,
// Some built-in templates use these instead of the above
prefix: filePrefix,
suffix: fileSuffix,
language: getMarkdownLanguageTagForFile(rif.filepath),
systemMessage: llm.systemMessage ?? "",
// "contextItems": (await sdk.getContextItemChatMessages()).map(x => x.content || "").join("\n\n"),
},
);
if (typeof rendered === "string") {
messages = [
{
role: "user",
content: rendered,
},
];
} else {
messages = rendered;
}
const completion = llm.streamComplete(
rendered as string,
new AbortController().signal,
{
maxTokens: Math.min(
maxTokens,
Math.floor(llm.contextLength / 2),
4096,
),
raw: true,
},
);
let lineStream = streamLines(completion);
lineStream = filterEnglishLinesAtStart(lineStream);
lineStream = filterEnglishLinesAtEnd(filterCodeBlockLines(lineStream));
lineStream = stopAtLines(lineStream, () => {});
generator = streamWithNewLines(
fixCodeLlamaFirstLineIndentation(lineStream),
);
} else {
async function* gen() {
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
{
temperature: 0.5, // TODO
maxTokens: Math.min(
maxTokens,
Math.floor(llm.contextLength / 2),
4096,
),
},
)) {
yield stripImages(chunk.content);
}
}
generator = gen();
}
for await (const chunk of generator) {
// Stop early if it is repeating the fileSuffix or the step was deleted
if (repeatingFileSuffix) {
break;
}
// Allow stopping breakpoints
yield undefined;
// Accumulate lines
const chunkLines = chunk.split("\n");
chunkLines[0] = unfinishedLine + chunkLines[0];
if (chunk.endsWith("\n")) {
unfinishedLine = "";
chunkLines.pop(); // because this will be an empty string
} else {
unfinishedLine = chunkLines.pop() ?? "";
}
// Deal with newly accumulated lines
for (let i = 0; i < chunkLines.length; i++) {
// Trailing whitespace doesn't matter
chunkLines[i] = chunkLines[i].trimEnd();
chunkLines[i] = commonWhitespace + chunkLines[i];
// Lines that should signify the end of generation
if (isEndLine(chunkLines[i])) {
break;
}
// Lines that should be ignored, like the <> tags
if (lineToBeIgnored(chunkLines[i], completionLinesCovered === 0)) {
continue; // noice
}
// Check if we are currently just copying the prefix
if (
(linesOfPrefixCopied > 0 || completionLinesCovered === 0) &&
linesOfPrefixCopied < filePrefix.split("\n").length &&
chunkLines[i] === fullPrefixLines[linesOfPrefixCopied]
) {
// This is a sketchy way of stopping it from repeating the filePrefix. Is a bug if output happens to have a matching line
linesOfPrefixCopied += 1;
continue; // also nice
}
// Because really short lines might be expected to be repeated, this is only a !heuristic!
// Stop when it starts copying the fileSuffix
if (
chunkLines[i].trim() === lineBelowHighlightedRange.trim() &&
chunkLines[i].trim().length > 4 &&
!(
originalLinesBelowPreviousBlocks.length > 0 &&
chunkLines[i].trim() === originalLinesBelowPreviousBlocks[0].trim()
)
) {
repeatingFileSuffix = true;
break;
}
lines.push(chunkLines[i]);
completionLinesCovered += 1;
currentLineInFile += 1;
}
await sendDiffUpdate(
lines.concat([
unfinishedLine?.startsWith("<")
? commonWhitespace
: commonWhitespace + unfinishedLine,
]),
);
}
// Add the unfinished line
if (
unfinishedLine !== "" &&
!lineToBeIgnored(unfinishedLine, completionLinesCovered === 0) &&
!isEndLine(unfinishedLine)
) {
unfinishedLine = commonWhitespace + unfinishedLine;
lines.push(unfinishedLine);
await handleGeneratedLine(unfinishedLine);
completionLinesCovered += 1;
currentLineInFile += 1;
}
await sendDiffUpdate(lines, true);
if (params?.recap) {
const prompt = `This is the code before editing:
\`\`\`
${contents}
\`\`\`
This is the code after editing:
\`\`\`
${lines.join("\n")}
\`\`\`
Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`;
for await (const update of llm.streamComplete(
prompt,
new AbortController().signal,
)) {
yield update;
}
}
yield `Edited ${contextItemToEdit.name}`;
},
};
export default EditSlashCommand;

View file

@ -0,0 +1,46 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { ChatMessage, SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
export function constructMcpSlashCommand(
client: Client,
name: string,
description?: string,
args?: string[],
): SlashCommand {
return {
name,
description: description ?? "MCP Prompt",
params: {},
run: async function* (context) {
const argsObject: { [key: string]: string } = {};
const userInput = context.input.split(" ").slice(1).join(" ");
if (args) {
args.forEach((arg, i) => {
argsObject[arg] = userInput;
});
}
const result = await client.getPrompt({ name, arguments: argsObject });
const messages: ChatMessage[] = result.messages.map((msg) => {
if (msg.content.type !== "text") {
throw new Error(
"Continue currently only supports text prompts through MCP",
);
}
return {
content: msg.content.text,
role: msg.role,
};
});
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};
}

View file

@ -1,15 +1,18 @@
import * as fs from "fs/promises";
import * as path from "path";
import ignore from "ignore";
import { IDE, SlashCommand } from "../..";
import type { FileType, IDE, SlashCommand } from "../..";
import {
defaultIgnoreDir,
defaultIgnoreFile,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
import { stripImages } from "../../llm/images";
import { renderChatMessage } from "../../util/messageContent";
import {
findUriInDirs,
getUriPathBasename,
joinPathsToUri,
} from "../../util/uri";
const LANGUAGE_DEP_MGMT_FILENAMES = [
"package.json", // JavaScript (Node.js)
@ -45,36 +48,53 @@ const OnboardSlashCommand: SlashCommand = {
const context = await gatherProjectContext(workspaceDir, ide);
const prompt = createOnboardingPrompt(context);
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
], new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
const entries = await fs.readdir(dir, { withFileTypes: true });
const ig = ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(getGlobalContinueIgArray());
const entries = await ide.listDir(dir);
let ig = ignore().add(defaultIgnoreDir).add(defaultIgnoreFile);
const ignoreUri = joinPathsToUri(dir, ".gitignore");
const fileExists = await ide.fileExists(ignoreUri);
const gitIgnorePath = path.join(dir, ".gitignore");
const hasIgnoreFile = await fs
.access(gitIgnorePath)
.then(() => true)
.catch(() => false);
if (hasIgnoreFile) {
const gitIgnore = await ide.readFile(gitIgnorePath);
if (fileExists) {
const gitIgnore = await ide.readFile(ignoreUri);
const igPatterns = gitIgArrayFromFile(gitIgnore);
ig = ig.add(igPatterns);
ig.add(igPatterns);
}
const filteredEntries = entries.filter((entry) => !ig.ignores(entry.name));
const workspaceDirs = await ide.getWorkspaceDirs();
return filteredEntries;
const withRelativePaths = entries
.filter(
(entry) =>
entry[1] === (1 as FileType.File) ||
entry[1] === (2 as FileType.Directory),
)
.map((entry) => {
const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs);
return {
uri: entry[0],
type: entry[1],
basename: getUriPathBasename(entry[0]),
relativePath:
relativePathOrBasename +
(entry[1] === (2 as FileType.Directory) ? "/" : ""),
};
});
return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath));
}
async function gatherProjectContext(
@ -82,7 +102,6 @@ async function gatherProjectContext(
ide: IDE,
): Promise<string> {
let context = "";
async function exploreDirectory(dir: string, currentDepth: number = 0) {
if (currentDepth > MAX_EXPLORE_DEPTH) {
return;
@ -91,19 +110,16 @@ async function gatherProjectContext(
const entries = await getEntriesFilteredByIgnore(dir, ide);
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relativePath = path.relative(workspaceDir, fullPath);
if (entry.isDirectory()) {
context += `\nFolder: ${relativePath}\n`;
await exploreDirectory(fullPath, currentDepth + 1);
if (entry.type === (2 as FileType.Directory)) {
context += `\nFolder: ${entry.relativePath}\n`;
await exploreDirectory(entry.uri, currentDepth + 1);
} else {
if (entry.name.toLowerCase() === "readme.md") {
const content = await fs.readFile(fullPath, "utf-8");
context += `README for ${relativePath}:\n${content}\n\n`;
} else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.name)) {
const content = await fs.readFile(fullPath, "utf-8");
context += `${entry.name} for ${relativePath}:\n${content}\n\n`;
if (entry.basename.toLowerCase() === "readme.md") {
const content = await ide.readFile(entry.uri);
context += `README for ${entry.relativePath}:\n${content}\n\n`;
} else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) {
const content = await ide.readFile(entry.uri);
context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`;
}
}
}
@ -116,7 +132,7 @@ async function gatherProjectContext(
function createOnboardingPrompt(context: string): string {
return `
As a helpful AI assistant, your task is to onboard a new developer to this project.
As a helpful AI assistant, your task is to onboard a new developer to this project.
Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview:
${context}

View file

@ -1,5 +1,5 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
import { renderChatMessage } from "../../util/messageContent.js";
const prompt = `
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
@ -43,10 +43,11 @@ const ReviewMessageCommand: SlashCommand = {
const content = `${prompt} \r\n ${reviewText}`;
for await (const chunk of llm.streamChat([
{ role: "user", content: content },
], new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of llm.streamChat(
[{ role: "user", content: content }],
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -1,10 +1,12 @@
import * as fs from "node:fs";
import fs from "fs";
import { homedir } from "node:os";
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "path";
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { getContinueGlobalPath } from "../../util/paths.js";
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
function getOffsetDatetime(date: Date): Date {
@ -48,7 +50,7 @@ const ShareSlashCommand: SlashCommand = {
// message in the chat history, this will omit it
for (const msg of history.slice(0, history.length - 1)) {
let msgText = msg.content;
msgText = stripImages(msg.content);
msgText = renderChatMessage(msg);
if (msg.role === "user" && msgText.search("```") > -1) {
msgText = reformatCodeBlocks(msgText);
@ -62,10 +64,7 @@ const ShareSlashCommand: SlashCommand = {
}\n\n${msgText}`;
}
let outputDir: string = params?.outputDir;
if (!outputDir) {
outputDir = await ide.getContinueDir();
}
let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
if (outputDir.startsWith("~")) {
outputDir = outputDir.replace(/^~/, homedir);
@ -81,7 +80,7 @@ const ShareSlashCommand: SlashCommand = {
// folders are included. We default to using the first item in the list, if
// it exists.
const workspaceDirectory = workspaceDirs?.[0] || "";
outputDir = outputDir.replace(/^./, workspaceDirectory);
outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
}
if (!fs.existsSync(outputDir)) {
@ -91,8 +90,9 @@ const ShareSlashCommand: SlashCommand = {
const dtString = asBasicISOString(getOffsetDatetime(now));
const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
await ide.writeFile(outPath, content);
await ide.openFile(outPath);
const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
await ide.writeFile(fileUrl, content);
await ide.openFile(fileUrl);
yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
},

149
core/commands/util.test.ts Normal file
View file

@ -0,0 +1,149 @@
import { ctxItemToRifWithContents } from "./util";
import { ContextItemWithId, RangeInFileWithContents } from "../index";
describe("ctxItemToRifWithContents", () => {
it("should parse start and end lines from the item name when format is valid", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "1" },
name: "myFunction(10-20)",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const expected: RangeInFileWithContents = {
filepath: "/path/to/file",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should set startLine and endLine to 0 when name format is invalid", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "2" },
name: "myFunction",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const expected: RangeInFileWithContents = {
filepath: "/path/to/file",
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should handle missing uri by setting filepath to empty string", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "3" },
name: "myFunction(10-20)",
content: "function content",
description: "test description",
};
const expected: RangeInFileWithContents = {
filepath: "",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should handle uri with undefined value by setting filepath to empty string", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "4" },
name: "myFunction(10-20)",
content: "function content",
description: "test description",
};
const expected: RangeInFileWithContents = {
filepath: "",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should handle invalid line numbers gracefully", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "6" },
name: "myFunction(invalid-lines)",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const result = ctxItemToRifWithContents(item);
expect(result.range.start.line).toBeNaN();
expect(result.range.end.line).toBeNaN();
});
it("should handle missing closing parenthesis in name", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "7" },
name: "myFunction(10-20",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const expected: RangeInFileWithContents = {
filepath: "/path/to/file",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should handle name with multiple '-' characters", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "8" },
name: "myFunction(10-20-30)",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const expected: RangeInFileWithContents = {
filepath: "/path/to/file",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
});

View file

@ -1,7 +1,35 @@
import { ContextItemWithId, RangeInFileWithContents } from "../";
import { findUriInDirs, getUriPathBasename } from "../util/uri";
import { v4 as uuidv4 } from "uuid";
export function rifWithContentsToContextItem(
rif: RangeInFileWithContents,
): ContextItemWithId {
const basename = getUriPathBasename(rif.filepath);
const { relativePathOrBasename, foundInDir, uri } = findUriInDirs(
rif.filepath,
window.workspacePaths ?? [],
);
const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1})`;
return {
content: rif.contents,
name: `${basename} ${rangeStr}`,
description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
id: {
providerTitle: "code",
itemId: uuidv4(),
},
uri: {
type: "file",
value: rif.filepath,
},
};
}
export function ctxItemToRifWithContents(
item: ContextItemWithId,
linesOffByOne = false,
): RangeInFileWithContents {
let startLine = 0;
let endLine = 0;
@ -10,8 +38,8 @@ export function ctxItemToRifWithContents(
if (nameSplit.length > 1) {
const lines = nameSplit[1].split(")")[0].split("-");
startLine = Number.parseInt(lines[0], 10);
endLine = Number.parseInt(lines[1], 10);
startLine = Number.parseInt(lines[0], 10) - (linesOffByOne ? 1 : 0);
endLine = Number.parseInt(lines[1], 10) - (linesOffByOne ? 1 : 0);
}
const rif: RangeInFileWithContents = {

View file

@ -1,8 +1,8 @@
import fs from "node:fs";
import path from "node:path";
import { testConfigHandler } from "../test/util/fixtures";
import { TEST_DIR } from "../test/util/testDir";
import { testConfigHandler } from "../test/fixtures";
import { TEST_DIR } from "../test/testDir";
import { getConfigTsPath } from "../util/paths";
import { defaultConfig } from "./default";

View file

@ -224,7 +224,9 @@ export class ConfigHandler {
return { config, errors };
}
getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
getSerializedConfig(): Promise<
ConfigResult<BrowserSerializedContinueConfig>
> {
return this.currentProfile.getSerializedConfig(
this.additionalContextProviders,
);
@ -235,7 +237,9 @@ export class ConfigHandler {
}
async loadConfig(): Promise<ContinueConfig> {
return this.currentProfile.loadConfig(this.additionalContextProviders);
return (
await this.currentProfile.loadConfig(this.additionalContextProviders)
).config!; // <-- TODO
}
async llmFromTitle(title?: string): Promise<ILLM> {

View file

@ -1,5 +1,3 @@
import { config } from "dotenv";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@ -15,9 +13,9 @@ export interface ProfileDescription {
}
export class ProfileLifecycleManager {
private savedConfig: ContinueConfig | undefined;
private savedConfig: ConfigResult<ContinueConfig> | undefined;
private savedBrowserConfig?: BrowserSerializedContinueConfig;
private pendingConfigPromise?: Promise<ContinueConfig>;
private pendingConfigPromise?: Promise<ConfigResult<ContinueConfig>>;
constructor(private readonly profileLoader: IProfileLoader) {}
@ -48,35 +46,37 @@ export class ProfileLifecycleManager {
this.savedBrowserConfig = undefined;
this.pendingConfigPromise = undefined;
return this.profileLoader.doLoadConfig();
return this.loadConfig([], true);
}
async loadConfig(
additionalContextProviders: IContextProvider[],
): Promise<ContinueConfig> {
forceReload: boolean = false,
): Promise<ConfigResult<ContinueConfig>> {
// If we already have a config, return it
if (this.savedConfig) {
return this.savedConfig;
} else if (this.pendingConfigPromise) {
return this.pendingConfigPromise;
if (!forceReload) {
if (this.savedConfig) {
return this.savedConfig;
} else if (this.pendingConfigPromise) {
return this.pendingConfigPromise;
}
}
// Set pending config promise
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
const { config: newConfig, errors } =
await this.profileLoader.doLoadConfig();
const result = await this.profileLoader.doLoadConfig();
if (newConfig) {
if (result.config) {
// Add registered context providers
newConfig.contextProviders = (newConfig.contextProviders ?? []).concat(
additionalContextProviders,
);
result.config.contextProviders = (
result.config.contextProviders ?? []
).concat(additionalContextProviders);
this.savedConfig = newConfig;
resolve(newConfig);
} else if (errors) {
this.savedConfig = result;
resolve(result);
} else if (result.errors) {
reject(
`Error in config.json: ${errors.map((item) => item.message).join(" | ")}`,
`Error in config.json: ${result.errors.map((item) => item.message).join(" | ")}`,
);
}
});
@ -89,11 +89,21 @@ export class ProfileLifecycleManager {
async getSerializedConfig(
additionalContextProviders: IContextProvider[],
): Promise<BrowserSerializedContinueConfig> {
): Promise<ConfigResult<BrowserSerializedContinueConfig>> {
if (!this.savedBrowserConfig) {
const continueConfig = await this.loadConfig(additionalContextProviders);
this.savedBrowserConfig = finalToBrowserConfig(continueConfig);
const result = await this.loadConfig(additionalContextProviders);
if (!result.config) {
return {
...result,
config: undefined,
};
}
this.savedBrowserConfig = finalToBrowserConfig(result.config);
}
return this.savedBrowserConfig;
return {
config: this.savedBrowserConfig,
errors: [],
configLoadInterrupted: false,
};
}
}

View file

@ -95,14 +95,6 @@ export const defaultSlashCommandsJetBrains = [
export const defaultConfig: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
customCommands: [
{
name: "test",
prompt:
"{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
description: "Write unit tests for highlighted code",
},
],
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
};
@ -110,14 +102,6 @@ export const defaultConfig: SerializedContinueConfig = {
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
customCommands: [
{
name: "test",
prompt:
"{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
description: "Write unit tests for highlighted code",
},
],
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
};

View file

@ -1,14 +1,13 @@
import { IDE } from "..";
import { joinPathsToUri } from "../util/uri";
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
export async function getSystemPromptDotFile(ide: IDE): Promise<string | null> {
const dirs = await ide.getWorkspaceDirs();
let prompts: string[] = [];
const pathSep = await ide.pathSep();
for (const dir of dirs) {
const dotFile = `${dir}${pathSep}${SYSTEM_PROMPT_DOT_FILE}`;
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
if (await ide.fileExists(dotFile)) {
try {
const content = await ide.readFile(dotFile);

View file

@ -1,10 +1,12 @@
import { execSync } from "child_process";
import * as JSONC from "comment-json";
import * as fs from "fs";
import os from "os";
import path from "path";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as JSONC from "comment-json";
import * as tar from "tar";
import {
BrowserSerializedContinueConfig,
Config,
@ -18,8 +20,9 @@ import {
IDE,
IdeSettings,
IdeType,
ILLM,
LLMOptions,
ModelDescription,
Reranker,
RerankerDescription,
SerializedContinueConfig,
SlashCommand,
@ -28,36 +31,38 @@ import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index.js";
import { AllRerankers } from "../context/allRerankers";
import { MCPManagerSingleton } from "../context/mcp";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
import { AllRerankers } from "../context/rerankers/index";
import { LLMReranker } from "../context/rerankers/llm";
import { allEmbeddingsProviders } from "../indexing/embeddings";
import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider";
import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
import { BaseLLM } from "../llm";
import { llmFromDescription } from "../llm/llms";
import CustomLLMClass from "../llm/llms/CustomLLM";
import FreeTrial from "../llm/llms/FreeTrial";
import { LLMReranker } from "../llm/llms/llm";
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
import { allTools } from "../tools";
import { copyOf } from "../util";
import { fetchwithRequestOptions } from "../util/fetchWithOptions";
import { GlobalContext } from "../util/GlobalContext";
import mergeJson from "../util/merge";
import {
DEFAULT_CONFIG_TS_CONTENTS,
getConfigJsPath,
getConfigJsPathForRemote,
getConfigJsonPath,
getConfigJsonPathForRemote,
getConfigJsPath,
getConfigJsPathForRemote,
getConfigTsPath,
getContinueDotEnv,
getEsbuildBinaryPath,
readAllGlobalPromptFiles,
} from "../util/paths";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -65,11 +70,6 @@ import {
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import {
DEFAULT_PROMPTS_FOLDER,
getPromptFiles,
slashCommandFromPromptFile,
} from "./promptFile.js";
import { ConfigValidationError, validateConfig } from "./validation.js";
export interface ConfigResult<T> {
@ -180,8 +180,8 @@ function loadSerializedConfig(
async function serializedToIntermediateConfig(
initial: SerializedContinueConfig,
ide: IDE,
loadPromptFiles: boolean = true,
): Promise<Config> {
// DEPRECATED - load custom slash commands
const slashCommands: SlashCommand[] = [];
for (const command of initial.slashCommands || []) {
const newCommand = slashCommandFromDescription(command);
@ -193,33 +193,18 @@ async function serializedToIntermediateConfig(
slashCommands.push(slashFromCustomCommand(command));
}
const workspaceDirs = await ide.getWorkspaceDirs();
const promptFolder = initial.experimental?.promptPath;
// DEPRECATED - load slash commands from v1 prompt files
// NOTE: still checking the v1 default .prompts folder for slash commands
const promptFiles = await getAllPromptFiles(
ide,
initial.experimental?.promptPath,
true,
);
if (loadPromptFiles) {
// v1 prompt files
let promptFiles: { path: string; content: string }[] = [];
promptFiles = (
await Promise.all(
workspaceDirs.map((dir) =>
getPromptFiles(
ide,
path.join(dir, promptFolder ?? DEFAULT_PROMPTS_FOLDER),
),
),
)
)
.flat()
.filter(({ path }) => path.endsWith(".prompt"));
// Also read from ~/.continue/.prompts
promptFiles.push(...readAllGlobalPromptFiles());
for (const file of promptFiles) {
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
if (slashCommand) {
slashCommands.push(slashCommand);
}
for (const file of promptFiles) {
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
if (slashCommand) {
slashCommands.push(slashCommand);
}
}
@ -254,7 +239,9 @@ async function intermediateToFinalConfig(
workOsAccessToken: string | undefined,
loadPromptFiles: boolean = true,
allowFreeTrial: boolean = true,
): Promise<ContinueConfig> {
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
// Auto-detect models
let models: BaseLLM[] = [];
for (const desc of config.models) {
@ -451,8 +438,12 @@ async function intermediateToFinalConfig(
) {
config.embeddingsProvider = new embeddingsProviderClass();
} else {
const llmOptions: LLMOptions = {
model: options.model ?? "UNSPECIFIED",
...options,
};
config.embeddingsProvider = new embeddingsProviderClass(
options,
llmOptions,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...config.requestOptions,
@ -468,7 +459,7 @@ async function intermediateToFinalConfig(
}
// Reranker
if (config.reranker && !(config.reranker as Reranker | undefined)?.rerank) {
if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) {
const { name, params } = config.reranker as RerankerDescription;
const rerankerClass = AllRerankers[name];
@ -480,18 +471,62 @@ async function intermediateToFinalConfig(
config.reranker = new LLMReranker(llm);
}
} else if (rerankerClass) {
config.reranker = new rerankerClass(params);
const llmOptions: LLMOptions = {
model: "rerank-2",
...params,
};
config.reranker = new rerankerClass(llmOptions);
}
}
return {
let continueConfig: ContinueConfig = {
...config,
contextProviders,
models,
embeddingsProvider: config.embeddingsProvider as any,
tabAutocompleteModels,
reranker: config.reranker as any,
tools: allTools,
};
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
if (config.experimental?.modelContextProtocolServers) {
await Promise.all(
config.experimental.modelContextProtocolServers?.map(
async (server, index) => {
const mcpId = index.toString();
const mcpConnection = mcpManager.createConnection(mcpId, server);
if (!mcpConnection) {
return;
}
const abortController = new AbortController();
try {
const mcpError = await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
);
if (mcpError) {
errors.push(mcpError);
}
} catch (e: any) {
errors.push({
fatal: false,
message: `Failed to load MCP server: ${e.message}`,
});
if (e.name !== "AbortError") {
throw e;
}
}
},
) || [],
);
}
return { config: continueConfig, errors };
}
function finalToBrowserConfig(
@ -524,9 +559,11 @@ function finalToBrowserConfig(
disableIndexing: final.disableIndexing,
disableSessionTitles: final.disableSessionTitles,
userToken: final.userToken,
embeddingsProvider: final.embeddingsProvider?.id,
embeddingsProvider: final.embeddingsProvider?.embeddingId,
ui: final.ui,
experimental: final.experimental,
docs: final.docs,
tools: final.tools,
};
}
@ -800,21 +837,25 @@ async function loadFullConfigNode(
}
// Convert to final config format
const finalConfig = await intermediateToFinalConfig(
intermediate,
ide,
ideSettings,
uniqueId,
writeLog,
workOsAccessToken,
);
return { config: finalConfig, errors, configLoadInterrupted: false };
const { config: finalConfig, errors: finalErrors } =
await intermediateToFinalConfig(
intermediate,
ide,
ideSettings,
uniqueId,
writeLog,
workOsAccessToken,
);
return {
config: finalConfig,
errors: [...(errors ?? []), ...finalErrors],
configLoadInterrupted: false,
};
}
export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadFullConfigNode,
serializedToIntermediateConfig,
type BrowserSerializedContinueConfig,
};

View file

@ -4,7 +4,7 @@ import { FREE_TRIAL_MODELS } from "./default";
export const TRIAL_FIM_MODEL = "codestral-latest";
export const ONBOARDING_LOCAL_MODEL_TITLE = "Ollama";
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b";
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b-base";
export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b";
export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";

View file

@ -1,3 +1,5 @@
import fs from "fs";
import {
ContinueConfig,
ContinueRcJson,
@ -5,16 +7,17 @@ import {
IdeSettings,
SerializedContinueConfig,
} from "../../";
import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { controlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { getConfigYamlPath } from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { ConfigResult, loadFullConfigNode } from "../load";
import { ConfigValidationError } from "../validation";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
export default async function doLoadConfig(
ide: IDE,
@ -30,20 +33,42 @@ export default async function doLoadConfig(
const ideSettings = await ideSettingsPromise;
const workOsAccessToken = await controlPlaneClient.getAccessToken();
let {
config: newConfig,
errors,
configLoadInterrupted,
} = await loadFullConfigNode(
ide,
workspaceConfigs,
ideSettings,
ideInfo.ideType,
uniqueId,
writeLog,
workOsAccessToken,
overrideConfigJson,
);
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
let newConfig: ContinueConfig | undefined;
let errors: ConfigValidationError[] | undefined;
let configLoadInterrupted = false;
if (fs.existsSync(configYamlPath)) {
const result = await loadContinueConfigFromYaml(
ide,
workspaceConfigs.map((c) => JSON.stringify(c)),
ideSettings,
ideInfo.ideType,
uniqueId,
writeLog,
workOsAccessToken,
undefined,
// overrideConfigYaml, TODO
);
newConfig = result.config;
errors = result.errors;
configLoadInterrupted = result.configLoadInterrupted;
} else {
const result = await loadFullConfigNode(
ide,
workspaceConfigs,
ideSettings,
ideInfo.ideType,
uniqueId,
writeLog,
workOsAccessToken,
overrideConfigJson,
);
newConfig = result.config;
errors = result.errors;
configLoadInterrupted = result.configLoadInterrupted;
}
if (configLoadInterrupted || !newConfig) {
return { errors, config: newConfig, configLoadInterrupted: true };
@ -111,13 +136,11 @@ async function injectControlPlaneProxyInfo(
);
if (config.embeddingsProvider?.providerName === "continue-proxy") {
(
config.embeddingsProvider as ContinueProxyEmbeddingsProvider
).controlPlaneProxyInfo = info;
(config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info;
}
if (config.reranker?.name === "continue-proxy") {
(config.reranker as ContinueProxyReranker).controlPlaneProxyInfo = info;
if (config.reranker?.providerName === "continue-proxy") {
(config.reranker as ContinueProxy).controlPlaneProxyInfo = info;
}
return config;

View file

@ -1,281 +0,0 @@
import path from "path";
import Handlebars from "handlebars";
import * as YAML from "yaml";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { getBasename } from "../util/index";
import type {
ChatMessage,
ContextItem,
ContinueSDK,
IContextProvider,
IDE,
SlashCommand,
} from "..";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
export async function getPromptFiles(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
const paths = await walkDir(dir, ide, { ignoreFiles: [] });
const results = paths.map(async (path) => {
const content = await ide.readFile(path);
return { path, content };
});
return Promise.all(results);
} catch (e) {
console.error(e);
return [];
}
}
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
# It is used to define and reuse prompts within Continue
# Continue will automatically create a slash command for each prompt in the .prompts folder
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
temperature: 0.0
---
{{{ diff }}}
Give me feedback on the above changes. For each file, you should output a markdown section including the following:
- If you found any problems, an h3 like "❌ <filename>"
- If you didn't find any problems, an h3 like "✅ <filename>"
- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it
- If you didn't find any problems, you don't need to add anything else
Here is an example. The example is surrounded in backticks, but your response should not be:
\`\`\`
### ✅ <Filename1>
### ❌ <Filename2>
<Description>
\`\`\`
You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
- console.logs that have been left after debugging
- repeated code
- algorithmic errors that could fail under edge cases
- something that could be refactored
Make sure to review ALL files that were changed, do not skip any.
`;
export async function createNewPromptFile(
ide: IDE,
promptPath: string | undefined,
): Promise<void> {
const workspaceDirs = await ide.getWorkspaceDirs();
if (workspaceDirs.length === 0) {
throw new Error(
"No workspace directories found. Make sure you've opened a folder in your IDE.",
);
}
const promptFilePath = path.join(
workspaceDirs[0],
promptPath ?? DEFAULT_PROMPTS_FOLDER,
"new-prompt-file.prompt",
);
await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE);
await ide.openFile(promptFilePath);
}
export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommand | null {
const { name, description, systemMessage, prompt, version } = parsePromptFile(
path,
content,
);
if (version !== 1) {
return null;
}
return {
name,
description,
run: async function* (context) {
const originalSystemMessage = context.llm.systemMessage;
context.llm.systemMessage = systemMessage;
const userInput = extractUserInput(context.input, name);
const renderedPrompt = await renderPrompt(prompt, context, userInput);
const messages = updateChatHistory(
context.history,
name,
renderedPrompt,
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
}
context.llm.systemMessage = originalSystemMessage;
},
};
}
function parsePromptFile(path: string, content: string) {
let [preambleRaw, prompt] = content.split("\n---\n");
if (prompt === undefined) {
prompt = preambleRaw;
preambleRaw = "";
}
const preamble = YAML.parse(preambleRaw) ?? {};
const name = preamble.name ?? getBasename(path).split(".prompt")[0];
const description = preamble.description ?? name;
const version = preamble.version ?? 2;
let systemMessage: string | undefined = undefined;
if (prompt.includes("<system>")) {
systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
prompt = prompt.split("</system>")[1].trim();
}
return { name, description, systemMessage, prompt, version };
}
function extractUserInput(input: string, commandName: string): string {
if (input.startsWith(`/${commandName}`)) {
return input.slice(commandName.length + 1).trimStart();
}
return input;
}
async function renderPrompt(
prompt: string,
context: ContinueSDK,
userInput: string,
) {
const helpers = getContextProviderHelpers(context);
// A few context providers that don't need to be in config.json to work in .prompt files
const diff = await context.ide.getDiff(false);
const currentFile = await context.ide.getCurrentFile();
const inputData: Record<string, string> = {
diff,
input: userInput,
};
if (currentFile) {
inputData.currentFile = currentFile.path;
}
return renderTemplatedString(
prompt,
context.ide.readFile.bind(context.ide),
inputData,
helpers,
);
}
function getContextProviderHelpers(
context: ContinueSDK,
): Array<[string, Handlebars.HelperDelegate]> | undefined {
return context.config.contextProviders?.map((provider: IContextProvider) => [
provider.description.title,
async (helperContext: any) => {
const items = await provider.getContextItems(helperContext, {
config: context.config,
embeddingsProvider: context.config.embeddingsProvider,
fetch: context.fetch,
fullInput: context.input,
ide: context.ide,
llm: context.llm,
reranker: context.config.reranker,
selectedCode: context.selectedCode,
});
items.forEach((item) =>
context.addContextItem(createContextItem(item, provider)),
);
return items.map((item) => item.content).join("\n\n");
},
]);
}
function createContextItem(item: ContextItem, provider: IContextProvider) {
return {
...item,
id: {
itemId: item.description,
providerTitle: provider.description.title,
},
};
}
function updateChatHistory(
history: ChatMessage[],
commandName: string,
renderedPrompt: string,
systemMessage?: string,
) {
const messages = [...history];
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
if (Array.isArray(content)) {
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
messages[i] = updateArrayContent(
messages[i],
commandName,
renderedPrompt,
);
break;
}
} else if (
typeof content === "string" &&
content.startsWith(`/${commandName}`)
) {
messages[i] = { ...messages[i], content: renderedPrompt };
break;
}
}
if (systemMessage) {
messages[0]?.role === "system"
? (messages[0].content = systemMessage)
: messages.unshift({ role: "system", content: systemMessage });
}
return messages;
}
function updateArrayContent(
message: any,
commandName: string,
renderedPrompt: string,
) {
return {
...message,
content: message.content.map((part: any) =>
part.text?.startsWith(`/${commandName}`)
? { ...part, text: renderedPrompt }
: part,
),
};
}

File diff suppressed because it is too large Load diff

View file

@ -63,7 +63,8 @@ export function validateConfig(config: SerializedContinueConfig) {
if (
nonAutocompleteModels.some((m) => modelName.includes(m)) &&
!modelName.includes("deepseek") &&
!modelName.includes("codestral")
!modelName.includes("codestral") &&
!modelName.toLowerCase().includes("coder")
) {
errors.push({
fatal: false,

View file

@ -0,0 +1,30 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas";
import { SerializedContinueConfig } from "../..";
export function convertConfigJsonToConfigYaml(
configJson: SerializedContinueConfig,
): ConfigYaml {
return {
name: "Local Config",
models: [
...configJson.models.map(
(model): ModelConfig => ({
model: model.model,
name: model.title,
// defaultCompletionOptions: model.completionOptions,
provider: model.provider,
roles: ["chat"],
}),
),
// ... tabAutocompleteModels
// embeddingsModels
// rerankModels
],
context: configJson.contextProviders?.map((provider) => ({
uses: provider.name,
with: provider.params,
})),
};
}

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