Merge branch 'main' into ovhcloud/add-ai-endpoints-llms
This commit is contained in:
commit
075e7cca2a
648 changed files with 32951 additions and 10668 deletions
1
.github/pull_request_template.md
vendored
1
.github/pull_request_template.md
vendored
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
## Checklist
|
||||
|
||||
- [] I've read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md)
|
||||
- [] The relevant docs, if any, have been updated or created
|
||||
- [] The relevant tests, if any, have been updated or created
|
||||
|
||||
|
|
|
|||
70
.github/workflows/auto-release.yml
vendored
Normal file
70
.github/workflows/auto-release.yml
vendored
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
name: Create Automatic Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- nate/auto-main-release-draft
|
||||
schedule:
|
||||
- cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday
|
||||
workflow_dispatch: # Keep manual trigger option
|
||||
|
||||
jobs:
|
||||
create-vscode-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # Needed for creating releases
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Get version from package.json
|
||||
id: get_version
|
||||
run: |
|
||||
# Read version from package.json and add -vscode suffix
|
||||
version=$(node -p "require('./extensions/vscode/package.json').version")
|
||||
new_version="v${version}-vscode"
|
||||
echo "New version will be: $new_version"
|
||||
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Create a new draft release with auto-generated release notes
|
||||
gh release create "$NEW_VERSION" \
|
||||
--generate-notes \
|
||||
--title "$NEW_VERSION" \
|
||||
--draft \
|
||||
--latest \
|
||||
--prerelease
|
||||
|
||||
create-jetbrains-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # Needed for creating releases
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get version from gradle.properties
|
||||
id: get_version
|
||||
run: |
|
||||
# Read version from gradle.properties and add -jetbrains suffix
|
||||
version=$(grep '^pluginVersion=' extensions/intellij/gradle.properties | cut -d'=' -f2)
|
||||
new_version="v${version}-jetbrains"
|
||||
echo "New version will be: $new_version"
|
||||
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Create a new draft release with auto-generated release notes
|
||||
gh release create "$NEW_VERSION" \
|
||||
--generate-notes \
|
||||
--title "$NEW_VERSION" \
|
||||
--draft \
|
||||
--latest \
|
||||
--prerelease
|
||||
63
.github/workflows/jetbrains-release.yaml
vendored
63
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -37,6 +37,52 @@ jobs:
|
|||
echo "should_run=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
bump-version:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- check_release_name
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
# 0. Setup git
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
git config --local user.email "action@github.com"
|
||||
git config --local user.name "GitHub Action"
|
||||
|
||||
- name: Create PR branch
|
||||
run: |
|
||||
BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)"
|
||||
git checkout -b $BRANCH_NAME
|
||||
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
|
||||
|
||||
- name: Bump version in gradle.properties
|
||||
run: |
|
||||
cd extensions/intelllij
|
||||
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
|
||||
rm -rf tmp
|
||||
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
|
||||
echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@v7
|
||||
with:
|
||||
token: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
|
||||
title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
|
||||
body: |
|
||||
Automated PR to bump the JetBrains extension version after successful pre-release publication.
|
||||
|
||||
- Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }}
|
||||
branch: ${{ env.BRANCH_NAME }}
|
||||
base: main
|
||||
delete-branch: true
|
||||
|
||||
# Prepare and publish the plugin to JetBrains Marketplace repository
|
||||
build:
|
||||
needs: check_release_name
|
||||
|
|
@ -121,6 +167,21 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build and check config-yaml
|
||||
run: |
|
||||
cd ../../packages/config-yaml
|
||||
npm i
|
||||
npx tsc --noEmit
|
||||
# Tests are currently failing, commenting out for now
|
||||
# npm test
|
||||
npm run build
|
||||
|
||||
# npm install core
|
||||
- name: Install core node_modules
|
||||
run: |
|
||||
|
|
@ -420,7 +481,7 @@ jobs:
|
|||
|
||||
# Run Qodana inspections
|
||||
- name: Qodana - Code Inspection
|
||||
uses: JetBrains/qodana-action@v2024.3.2
|
||||
uses: JetBrains/qodana-action@v2025.1.0
|
||||
with:
|
||||
cache-default-branch-only: true
|
||||
|
||||
|
|
|
|||
276
.github/workflows/pr_checks.yaml
vendored
276
.github/workflows/pr_checks.yaml
vendored
|
|
@ -1,15 +1,14 @@
|
|||
name: PR checks
|
||||
|
||||
# PR Checks run on all PRs to the main branch and must pass before merging.
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- staging
|
||||
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- staging
|
||||
|
||||
jobs:
|
||||
install-root:
|
||||
|
|
@ -31,6 +30,62 @@ jobs:
|
|||
if: steps.root-cache.outputs.cache-hit != 'true'
|
||||
run: npm ci
|
||||
|
||||
install-config-yaml:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Install config-yaml dependencies
|
||||
if: steps.config-yaml-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
config-yaml-checks:
|
||||
needs: install-config-yaml
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build and check config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npx tsc --noEmit
|
||||
# Tests are currently failing, commenting out for now
|
||||
# npm test
|
||||
npm run build
|
||||
|
||||
install-core:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -60,7 +115,7 @@ jobs:
|
|||
npm ci
|
||||
|
||||
core-checks:
|
||||
needs: install-core
|
||||
needs: [install-core, install-config-yaml]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -81,6 +136,17 @@ jobs:
|
|||
path: core/node_modules
|
||||
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd core
|
||||
|
|
@ -90,7 +156,7 @@ jobs:
|
|||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
|
||||
install-gui:
|
||||
needs: [install-root, install-core]
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -115,6 +181,17 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Install gui dependencies
|
||||
if: steps.gui-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -147,13 +224,24 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Type check
|
||||
run: |
|
||||
cd gui
|
||||
npx tsc --noEmit
|
||||
|
||||
binary-checks:
|
||||
needs: [install-root, install-core]
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -178,6 +266,17 @@ jobs:
|
|||
path: binary/node_modules
|
||||
key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Install binary dependencies
|
||||
if: steps.binary-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -190,7 +289,7 @@ jobs:
|
|||
npx tsc --noEmit
|
||||
|
||||
install-vscode:
|
||||
needs: [install-root, install-core]
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -215,6 +314,17 @@ jobs:
|
|||
path: extensions/vscode/node_modules
|
||||
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Install vscode dependencies
|
||||
if: steps.vscode-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -249,14 +359,26 @@ jobs:
|
|||
path: extensions/vscode/node_modules
|
||||
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npm run write-build-timestamp
|
||||
npx tsc --noEmit
|
||||
npm run lint
|
||||
|
||||
core-tests:
|
||||
needs: install-core
|
||||
needs: [install-core, install-config-yaml]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -270,6 +392,17 @@ jobs:
|
|||
path: core/node_modules
|
||||
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Run core tests
|
||||
run: |
|
||||
cd core
|
||||
|
|
@ -283,9 +416,33 @@ jobs:
|
|||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
|
||||
|
||||
package-tests:
|
||||
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 }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
- name: Run config-yaml tests
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm test
|
||||
|
||||
vscode-get-test-file-matrix:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-root, install-vscode]
|
||||
needs: [install-root, install-vscode, install-config-yaml]
|
||||
outputs:
|
||||
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
|
||||
steps:
|
||||
|
|
@ -297,6 +454,17 @@ jobs:
|
|||
path: extensions/vscode/node_modules
|
||||
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Get test files
|
||||
id: vscode-get-test-file-matrix
|
||||
run: |
|
||||
|
|
@ -320,7 +488,7 @@ jobs:
|
|||
|
||||
vscode-package-extension:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-vscode, install-core]
|
||||
needs: [install-vscode, install-core, install-config-yaml]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -340,6 +508,17 @@ jobs:
|
|||
path: core/node_modules
|
||||
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Package extension
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
|
|
@ -353,7 +532,7 @@ jobs:
|
|||
|
||||
vscode-download-e2e-dependencies:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-vscode, install-core]
|
||||
needs: [install-vscode, install-core, install-config-yaml]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -373,6 +552,17 @@ jobs:
|
|||
path: extensions/vscode/e2e/storage
|
||||
key: ${{ runner.os }}-vscode-storage-${{ hashFiles('extensions/vscode/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Download Dependencies
|
||||
if: steps.storage-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -386,7 +576,7 @@ jobs:
|
|||
path: extensions/vscode/e2e/storage
|
||||
|
||||
vscode-e2e-tests:
|
||||
name: ${{ matrix.test_file }} (${{ matrix.command }})
|
||||
name: ${{ matrix.test_file || 'unknown' }} (${{ matrix.command }})
|
||||
needs:
|
||||
[
|
||||
vscode-download-e2e-dependencies,
|
||||
|
|
@ -394,6 +584,7 @@ jobs:
|
|||
vscode-package-extension,
|
||||
install-vscode,
|
||||
install-core,
|
||||
install-config-yaml,
|
||||
]
|
||||
runs-on: ubuntu-latest
|
||||
# Tests requiring secrets need approval from maintainers
|
||||
|
|
@ -434,6 +625,17 @@ jobs:
|
|||
name: vscode-e2e-dependencies
|
||||
path: extensions/vscode/e2e/storage
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Fix VSCode binary permissions
|
||||
run: |
|
||||
chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code
|
||||
|
|
@ -475,8 +677,29 @@ jobs:
|
|||
name: e2e-failure-screenshots
|
||||
path: extensions/vscode/e2e/storage/screenshots
|
||||
|
||||
- name: Sanitize test file name
|
||||
id: sanitize_filename
|
||||
if: always()
|
||||
run: |
|
||||
FILENAME="${{ matrix.test_file }}"
|
||||
SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion
|
||||
echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Find e2e log file
|
||||
if: always()
|
||||
run: |
|
||||
echo "Searching for e2e.log file..."
|
||||
find $GITHUB_WORKSPACE -name "e2e.log" -type f
|
||||
|
||||
- name: Upload e2e logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
|
||||
path: extensions/vscode/e2e.log
|
||||
|
||||
gui-tests:
|
||||
needs: [install-gui, install-core]
|
||||
needs: [install-gui, install-core, install-config-yaml]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -496,6 +719,17 @@ jobs:
|
|||
path: core/node_modules
|
||||
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Install GUI dependencies
|
||||
if: steps.gui-cache.outputs.cache-hit != 'true'
|
||||
run: cd gui && npm ci
|
||||
|
|
@ -508,7 +742,7 @@ jobs:
|
|||
npm test
|
||||
|
||||
jetbrains-tests:
|
||||
needs: [install-root, core-checks]
|
||||
needs: [install-root, core-checks, install-config-yaml]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -517,6 +751,17 @@ jobs:
|
|||
path: core/node_modules
|
||||
key: ${{ runner.os }}-core-node-modules-${{ hashFiles('core/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4.5.0
|
||||
with:
|
||||
|
|
@ -621,17 +866,18 @@ jobs:
|
|||
- install-vscode
|
||||
- vscode-checks
|
||||
- core-tests
|
||||
- package-tests
|
||||
- vscode-get-test-file-matrix
|
||||
- vscode-package-extension
|
||||
- vscode-download-e2e-dependencies
|
||||
- vscode-e2e-tests
|
||||
- gui-tests
|
||||
- jetbrains-tests
|
||||
- config-yaml-checks
|
||||
- install-config-yaml
|
||||
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
uses: re-actors/alls-green@release/v1
|
||||
with:
|
||||
allowed-failures:
|
||||
allowed-skips:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
|
|
|
|||
39
.github/workflows/preview.yaml
vendored
39
.github/workflows/preview.yaml
vendored
|
|
@ -1,4 +1,4 @@
|
|||
name: Publish Preview Extension
|
||||
name: Publish Pre-release Extension
|
||||
|
||||
on:
|
||||
release:
|
||||
|
|
@ -207,6 +207,7 @@ jobs:
|
|||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
# 0. Setup git
|
||||
- name: Checkout
|
||||
|
|
@ -242,12 +243,44 @@ jobs:
|
|||
cd extensions/vscode
|
||||
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
|
||||
|
||||
# 4. Update the package.json version and push changes
|
||||
# 4. Create PR with version bump
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Create PR branch
|
||||
run: |
|
||||
BRANCH_NAME="chore/bump-vscode-version-$(date +%Y%m%d-%H%M%S)"
|
||||
git checkout -b $BRANCH_NAME
|
||||
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
|
||||
|
||||
- name: Bump version in package.json
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npm version patch --no-git-tag-version
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@v7
|
||||
with:
|
||||
token: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
|
||||
title: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
|
||||
body: |
|
||||
Automated PR to bump the VS Code extension version after successful pre-release publication.
|
||||
|
||||
- Bumped version in extensions/vscode/package.json to ${{ env.NEW_VERSION }}
|
||||
branch: ${{ env.BRANCH_NAME }}
|
||||
base: main
|
||||
delete-branch: true
|
||||
|
||||
# 5. Update version in package.json
|
||||
# - name: Update version in package.json
|
||||
# run: |
|
||||
# cd extensions/vscode
|
||||
# npm version patch
|
||||
|
||||
# - name: Commit changes
|
||||
# run: |
|
||||
# git config --local user.email "action@github.com"
|
||||
|
|
|
|||
46
.github/workflows/release-config-yaml.yml
vendored
Normal file
46
.github/workflows/release-config-yaml.yml
vendored
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
name: Release @continuedev/config-yaml
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "packages/config-yaml/**"
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm test
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npx semantic-release
|
||||
124
.github/workflows/vscode-version-bump.yml
vendored
Normal file
124
.github/workflows/vscode-version-bump.yml
vendored
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
name: Create VS Code main release draft
|
||||
on:
|
||||
schedule:
|
||||
# Runs at 7 AM PST (15:00 UTC) every Friday
|
||||
- cron: "0 15 * * 5"
|
||||
workflow_dispatch:
|
||||
# Allows manual triggering
|
||||
|
||||
jobs:
|
||||
version-bump:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history and tags
|
||||
|
||||
- name: Setup GitHub CLI
|
||||
run: |
|
||||
gh auth login --with-token <<< "${{ github.token }}"
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Find and process version tags
|
||||
run: |
|
||||
echo "Starting version bump process..."
|
||||
|
||||
# Find last v1.1.x-vscode tag that's at least 6 days old
|
||||
CURRENT_TIMESTAMP=$(date +%s)
|
||||
SIX_DAYS_AGO=$((CURRENT_TIMESTAMP - 6*24*60*60))
|
||||
echo "Current timestamp: $(date -d @${CURRENT_TIMESTAMP})"
|
||||
echo "Six days ago: $(date -d @${SIX_DAYS_AGO})"
|
||||
|
||||
echo "Looking for v1.1.x-vscode tags..."
|
||||
git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:iso)' refs/tags | grep 'v1\.1\.[0-9]\+-vscode' || echo "No matching tags found"
|
||||
|
||||
LAST_1_1_TAG=$(git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:unix)' refs/tags \
|
||||
| grep 'v1\.1\.[0-9]\+-vscode' \
|
||||
| while read tag timestamp; do
|
||||
if [ $timestamp -le $SIX_DAYS_AGO ]; then
|
||||
echo ${tag% *}
|
||||
break
|
||||
fi
|
||||
done)
|
||||
|
||||
echo "Selected v1.1.x tag: $LAST_1_1_TAG"
|
||||
if [ -z "$LAST_1_1_TAG" ]; then
|
||||
echo "::error::No suitable v1.1.x-vscode tag found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Find last v1.0.y-vscode tag
|
||||
echo "Looking for v1.0.y-vscode tags..."
|
||||
git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' || echo "No matching tags found"
|
||||
|
||||
LAST_1_0_TAG=$(git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' | head -n1)
|
||||
echo "Selected v1.0.y tag: $LAST_1_0_TAG"
|
||||
if [ -z "$LAST_1_0_TAG" ]; then
|
||||
echo "::error::No v1.0.y-vscode tag found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract the y number and increment it
|
||||
Y_NUMBER=$(echo $LAST_1_0_TAG | sed 's/v1\.0\.\([0-9]\+\)-vscode/\1/')
|
||||
NEXT_Y=$((Y_NUMBER + 1))
|
||||
NEW_BRANCH="v1.0.${NEXT_Y}-vscode"
|
||||
NEW_VERSION="1.0.${NEXT_Y}"
|
||||
echo "Current Y number: $Y_NUMBER"
|
||||
echo "Next Y number: $NEXT_Y"
|
||||
echo "New branch name: $NEW_BRANCH"
|
||||
echo "New version: $NEW_VERSION"
|
||||
|
||||
# Create new branch from the v1.1.x tag
|
||||
echo "Creating new branch from $LAST_1_1_TAG..."
|
||||
git checkout $LAST_1_1_TAG
|
||||
git checkout -b $NEW_BRANCH
|
||||
|
||||
# Update the version in package.json
|
||||
echo "Current package.json version:"
|
||||
cat extensions/vscode/package.json | grep version
|
||||
|
||||
echo "Updating version in package.json..."
|
||||
jq ".version = \"$NEW_VERSION\"" extensions/vscode/package.json > temp.json && mv temp.json extensions/vscode/package.json
|
||||
|
||||
echo "New package.json version:"
|
||||
cat extensions/vscode/package.json | grep version
|
||||
|
||||
# Configure git
|
||||
echo "Configuring git..."
|
||||
git config user.name "GitHub Actions Bot"
|
||||
git config user.email "actions@github.com"
|
||||
|
||||
# Commit and push changes
|
||||
echo "Committing changes..."
|
||||
git add extensions/vscode/package.json
|
||||
git commit -m "Bump VS Code extension to ${NEW_VERSION}"
|
||||
|
||||
echo "Pushing branch to origin..."
|
||||
git push origin $NEW_BRANCH
|
||||
|
||||
# Add release creation
|
||||
echo "Creating draft release..."
|
||||
gh release create "${NEW_BRANCH}" \
|
||||
--title "${NEW_BRANCH}" \
|
||||
--generate-notes \
|
||||
--draft \
|
||||
--latest \
|
||||
--notes-start-tag "${LAST_1_0_TAG}"
|
||||
|
||||
echo "Version bump process completed successfully!"
|
||||
|
||||
- name: Check for errors
|
||||
if: failure()
|
||||
run: |
|
||||
echo "::error::Failed to process version tags and create new branch"
|
||||
echo "Last few lines of git log:"
|
||||
git log -n 5 --oneline
|
||||
echo "Current git status:"
|
||||
git status
|
||||
echo "Current branches:"
|
||||
git branch -a
|
||||
10
.gitignore
vendored
10
.gitignore
vendored
|
|
@ -83,16 +83,6 @@ ipython_config.py
|
|||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
|
|
|||
3
.idea/compiler.xml
generated
3
.idea/compiler.xml
generated
|
|
@ -3,4 +3,7 @@
|
|||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="17" />
|
||||
</component>
|
||||
<component name="TypeScriptCompiler">
|
||||
<option name="useTypesFromServer" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
1
.idea/gradle.xml
generated
1
.idea/gradle.xml
generated
|
|
@ -5,6 +5,7 @@
|
|||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
|
||||
<option name="gradleJvm" value="homebrew-17" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$/extensions/intellij" />
|
||||
|
|
|
|||
2
.idea/scopes/Continue.xml
generated
2
.idea/scopes/Continue.xml
generated
|
|
@ -1,3 +1,3 @@
|
|||
<component name="DependencyValidationManager">
|
||||
<scope name="Continue" pattern="file[continue-intellij-extension]:*/&&!file[continue-intellij-extension]:binary/bin//*&&!file[continue-intellij-extension]:binary/build//*&&!file[continue-intellij-extension]:binary/out//*&&!file[continue-intellij-extension]:gui/dist//*&&!file[continue-intellij-extension]:extensions/intellij/build//*&&!file[continue-intellij-extension]:extensions/vscode/bin//*&&!file[continue-intellij-extension]:extensions/vscode/build//*&&!file[continue-intellij-extension]:extensions/vscode/out//*" />
|
||||
<scope name="Continue" pattern="file:*/&&!file:binary/bin//*&&!file:binary/build//*&&!file:binary/out//*&&!file:gui/dist//*&&!file:extensions/intellij/build//*&&!file:extensions/vscode/bin//*&&!file:extensions/vscode/build//*&&!file:extensions/vscode/out//*&&!file:**/*.coverage&&!file:**/*.coveragedata&&!file:**/coverage//*&&!file:**/.coverage//*&&!file:**/assets//**" />
|
||||
</component>
|
||||
1
.node-version
Normal file
1
.node-version
Normal file
|
|
@ -0,0 +1 @@
|
|||
20.19.0
|
||||
2
.nvmrc
2
.nvmrc
|
|
@ -1 +1 @@
|
|||
v20.11.0
|
||||
v20.19.0
|
||||
|
|
@ -20,10 +20,12 @@
|
|||
- [Debugging](#debugging)
|
||||
- [JetBrains](#jetbrains)
|
||||
- [Our Git Workflow](#our-git-workflow)
|
||||
- [Testing](#testing)
|
||||
- [Development workflow](#development-workflow)
|
||||
- [Formatting](#formatting)
|
||||
- [Writing Slash Commands](#writing-slash-commands)
|
||||
- [Writing Context Providers](#writing-context-providers)
|
||||
- [Testing](#testing)
|
||||
- [Review Process](#review-process)
|
||||
- [Getting help](#getting-help)
|
||||
- [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
|
||||
- [Adding an LLM Provider](#adding-an-llm-provider)
|
||||
- [Adding Models](#adding-models)
|
||||
- [📐 Continue Architecture](#-continue-architecture)
|
||||
|
|
@ -94,11 +96,13 @@ This will start a local server and you can see the documentation rendered in you
|
|||
|
||||
## 🧑💻 Contributing Code
|
||||
|
||||
We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the process as welcoming and straightforward as possible.
|
||||
|
||||
### Environment Setup
|
||||
|
||||
#### Pre-requisites
|
||||
|
||||
You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
|
||||
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
|
||||
|
||||
```bash
|
||||
nvm use
|
||||
|
|
@ -145,45 +149,35 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
|
|||
|
||||
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>.
|
||||
|
||||
### Development workflow
|
||||
|
||||
- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned with the project direction.
|
||||
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
|
||||
- Write or update tests for new functionality
|
||||
- Update relevant documentation in the `docs` folder
|
||||
- Open a PR against the `main` branch. Make sure to fill in the PR template
|
||||
|
||||
### Formatting
|
||||
|
||||
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
|
||||
|
||||
### 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 to resolve the issue before we merge.
|
||||
|
||||
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
|
||||
|
||||
### Formatting
|
||||
### Review Process
|
||||
|
||||
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
|
||||
- **Initial Review** - A maintainer will be assigned as primary reviewer
|
||||
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is maintainable and follows our patterns.
|
||||
- **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
|
||||
|
||||
### Writing Slash Commands
|
||||
### Getting help
|
||||
|
||||
The slash command interface, defined in [core/index.d.ts](./core/index.d.ts), requires you to define a `name` (the text that will be typed to invoke the command), a `description` (the text that will be shown in the slash command menu), and a `run` function that will be called when the command is invoked. The `run` function is an async generator that yields the content to be displayed in the chat. The `run` function is passed a `ContinueSDK` object that can be used to interact with the IDE, call the LLM, and see the chat history, among a few other utilities.
|
||||
Join [#contribute on Discord](https://discord.gg/vapESyrFmJ) to engage with maintainers and other contributors.
|
||||
|
||||
```ts
|
||||
export interface SlashCommand {
|
||||
name: string;
|
||||
description: string;
|
||||
params?: { [key: string]: any };
|
||||
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
|
||||
}
|
||||
```
|
||||
|
||||
There are many example of slash commands in [core/commands/slash](./core/commands/slash) that we recommend borrowing from. Once you've created your new `SlashCommand` in this folder, also be sure to complete the following:
|
||||
|
||||
- Add your command to the array in [core/commands/slash/index.ts](./core/commands/slash/index.ts)
|
||||
- Add your command to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what commands are available for your provider when they are editing `config.json`. If there are any parameters that your command accepts, you should also follow existing examples in adding them to the JSON Schema.
|
||||
|
||||
### Writing Context Providers
|
||||
|
||||
A `ContextProvider` is a Continue plugin that lets type '@' to quickly select documents as context for the language model. The `IContextProvider` interface is defined in [`core/index.d.ts`](./core/index.d.ts), but all built-in context providers extend [`BaseContextProvider`](./core/context/index.ts).
|
||||
|
||||
Before defining your context provider, determine which "type" you want to create. The `"query"` type will show a small text input when selected, giving the user the chance to enter something like a Google search query for the [`GoogleContextProvider`](./core/context/providers/GoogleContextProvider.ts). The `"submenu"` type will open up a submenu of items that can be searched through and selected. Examples are the [`GitHubIssuesContextProvider`](./core/context/providers/GitHubIssuesContextProvider.ts) and the [`DocsContextProvider`](./core/context/providers/DocsContextProvider.ts). The `"normal"` type will just immediately add the context item. Examples include the [`DiffContextProvider`](./core/context/providers/DiffContextProvider.ts) and the [`OpenFilesContextProvider`](./core/context/providers/OpenFilesContextProvider.ts).
|
||||
|
||||
After you've written your context provider, make sure to complete the following:
|
||||
|
||||
- Add it to the array of context providers in [core/context/providers/index.ts](./core/context/providers/index.ts)
|
||||
- Add it to the `ContextProviderName` type in [core/index.d.ts](./core/index.d.ts)
|
||||
- Add it to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). If there are any parameters that your context provider accepts, you should also follow existing examples in adding them to the JSON Schema.
|
||||
## Contribtuing new LLM Providers/Models
|
||||
|
||||
### Adding an LLM Provider
|
||||
|
||||
|
|
|
|||
|
|
@ -44,11 +44,11 @@
|
|||
|
||||

|
||||
|
||||
## Actions
|
||||
## Agent
|
||||
|
||||
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
@ -58,7 +58,7 @@ Learn about how to install and use Continue in the docs [here](https://continue.
|
|||
|
||||
## Contributing
|
||||
|
||||
Check out the [contribution ideas board](https://github.com/orgs/continuedev/projects/2), read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ)
|
||||
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
|
||||
|
||||
## License
|
||||
|
||||
|
|
|
|||
|
|
@ -9,17 +9,20 @@ const {
|
|||
autodetectPlatformAndArch,
|
||||
} = require("../scripts/util");
|
||||
|
||||
// Clean slate
|
||||
const bin = path.join(__dirname, "bin");
|
||||
const out = path.join(__dirname, "out");
|
||||
const build = path.join(__dirname, "build");
|
||||
rimrafSync(bin);
|
||||
rimrafSync(out);
|
||||
rimrafSync(build);
|
||||
rimrafSync(path.join(__dirname, "tmp"));
|
||||
fs.mkdirSync(bin);
|
||||
fs.mkdirSync(out);
|
||||
fs.mkdirSync(build);
|
||||
|
||||
function cleanSlate() {
|
||||
// Clean slate
|
||||
rimrafSync(bin);
|
||||
rimrafSync(out);
|
||||
rimrafSync(build);
|
||||
rimrafSync(path.join(__dirname, "tmp"));
|
||||
fs.mkdirSync(bin);
|
||||
fs.mkdirSync(out);
|
||||
fs.mkdirSync(build);
|
||||
}
|
||||
|
||||
const esbuildOutputFile = "out/index.js";
|
||||
let targets = [
|
||||
|
|
@ -56,6 +59,39 @@ const targetToLanceDb = {
|
|||
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
|
||||
};
|
||||
|
||||
// Bundles the extension into one file
|
||||
async function buildWithEsbuild() {
|
||||
console.log("[info] Building with esbuild...");
|
||||
await esbuild.build({
|
||||
entryPoints: ["src/index.ts"],
|
||||
bundle: true,
|
||||
outfile: esbuildOutputFile,
|
||||
external: [
|
||||
"esbuild",
|
||||
"./xhr-sync-worker.js",
|
||||
"llamaTokenizerWorkerPool.mjs",
|
||||
"tiktokenWorkerPool.mjs",
|
||||
"vscode",
|
||||
"./index.node",
|
||||
],
|
||||
format: "cjs",
|
||||
platform: "node",
|
||||
sourcemap: true,
|
||||
minify: true,
|
||||
treeShaking: true,
|
||||
loader: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
".node": "file",
|
||||
},
|
||||
|
||||
// To allow import.meta.path for transformers.js
|
||||
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
|
||||
inject: ["./importMetaUrl.js"],
|
||||
define: { "import.meta.url": "importMetaUrl" },
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
||||
console.log(`Copying ${packageName} to ${toCopy}`);
|
||||
// This is a way to install only one package without npm trying to install all the dependencies
|
||||
|
|
@ -118,6 +154,13 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
}
|
||||
|
||||
(async () => {
|
||||
if (esbuildOnly) {
|
||||
await buildWithEsbuild();
|
||||
return;
|
||||
}
|
||||
|
||||
cleanSlate()
|
||||
|
||||
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
|
||||
// This is only needed for our `pkg` command at build time
|
||||
fs.writeFileSync(
|
||||
|
|
@ -192,35 +235,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
fs.rmSync(assetPath, { force: true });
|
||||
}
|
||||
|
||||
// Bundles the extension into one file
|
||||
console.log("[info] Building with esbuild...");
|
||||
await esbuild.build({
|
||||
entryPoints: ["src/index.ts"],
|
||||
bundle: true,
|
||||
outfile: esbuildOutputFile,
|
||||
external: [
|
||||
"esbuild",
|
||||
"./xhr-sync-worker.js",
|
||||
"llamaTokenizerWorkerPool.mjs",
|
||||
"tiktokenWorkerPool.mjs",
|
||||
"vscode",
|
||||
"./index.node",
|
||||
],
|
||||
format: "cjs",
|
||||
platform: "node",
|
||||
sourcemap: true,
|
||||
minify: true,
|
||||
treeShaking: true,
|
||||
loader: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
".node": "file",
|
||||
},
|
||||
|
||||
// To allow import.meta.path for transformers.js
|
||||
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
|
||||
inject: ["./importMetaUrl.js"],
|
||||
define: { "import.meta.url": "importMetaUrl" },
|
||||
});
|
||||
await buildWithEsbuild();
|
||||
|
||||
// Copy over any worker files
|
||||
fs.cpSync(
|
||||
|
|
@ -233,10 +248,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
"out/llamaTokenizerWorkerPool.mjs",
|
||||
);
|
||||
|
||||
if (esbuildOnly) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[info] Building binaries with pkg...");
|
||||
for (const target of targets) {
|
||||
const targetDir = `bin/${target}`;
|
||||
|
|
|
|||
39
binary/package-lock.json
generated
39
binary/package-lock.json
generated
|
|
@ -44,14 +44,14 @@
|
|||
"version": "1.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
|
||||
"@aws-sdk/credential-providers": "^3.758.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.67",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
"@continuedev/openai-adapters": "^1.0.19",
|
||||
"@modelcontextprotocol/sdk": "^1.5.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -67,6 +67,7 @@
|
|||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
@ -105,6 +106,7 @@
|
|||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"wink-nlp-utils": "^2.1.0",
|
||||
"winston": "^3.17.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.24.2"
|
||||
|
|
@ -139,7 +141,7 @@
|
|||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
|
|
@ -2085,9 +2087,10 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@octokit/endpoint": {
|
||||
"version": "9.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.5.tgz",
|
||||
"integrity": "sha512-ekqR4/+PCLkEBF6qgj8WqJfvDq65RH85OAgrtnVp1mSxaXF03u2xW/hUdweGS5654IlC0wkNYC18Z50tSYTAFw==",
|
||||
"version": "9.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz",
|
||||
"integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/types": "^13.1.0",
|
||||
"universal-user-agent": "^6.0.0"
|
||||
|
|
@ -2154,12 +2157,13 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@octokit/request": {
|
||||
"version": "8.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.0.tgz",
|
||||
"integrity": "sha512-9Bb014e+m2TgBeEJGEbdplMVWwPmL1FPtggHQRkV+WVsMggPtEkLKPlcVYm/o8xKLkpJ7B+6N8WfQMtDLX2Dpw==",
|
||||
"version": "8.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz",
|
||||
"integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/endpoint": "^9.0.1",
|
||||
"@octokit/request-error": "^5.1.0",
|
||||
"@octokit/endpoint": "^9.0.6",
|
||||
"@octokit/request-error": "^5.1.1",
|
||||
"@octokit/types": "^13.1.0",
|
||||
"universal-user-agent": "^6.0.0"
|
||||
},
|
||||
|
|
@ -2168,9 +2172,10 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@octokit/request-error": {
|
||||
"version": "5.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.0.tgz",
|
||||
"integrity": "sha512-GETXfE05J0+7H2STzekpKObFe765O5dlAKUTLNGeH+x47z7JjXHfsHKo5z21D/o/IOZTUEI6nyWyR+bZVP/n5Q==",
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz",
|
||||
"integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@octokit/types": "^13.1.0",
|
||||
"deprecation": "^2.0.0",
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@
|
|||
"scripts": {
|
||||
"test": "jest",
|
||||
"build": "node build.js",
|
||||
"rebuild": "node build.js --esbuild-only",
|
||||
"build:darwin-x64": "node build.js --os darwin-x64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
process.env.IS_BINARY = "true";
|
||||
import { Command } from "commander";
|
||||
import { Core } from "core/core";
|
||||
import { LLMLogFormatter } from "core/llm/logFormatter";
|
||||
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
|
||||
import { IMessenger } from "core/protocol/messenger";
|
||||
import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths";
|
||||
|
|
@ -33,9 +34,8 @@ program.action(async () => {
|
|||
const ide = new IpcIde(messenger);
|
||||
const promptLogsPath = getPromptLogsPath();
|
||||
|
||||
new Core(messenger, ide, async (text) => {
|
||||
fs.appendFileSync(promptLogsPath, text + "\n\n");
|
||||
});
|
||||
const core = new Core(messenger, ide);
|
||||
new LLMLogFormatter(core.llmLogger, fs.createWriteStream(promptLogsPath));
|
||||
|
||||
console.log("[binary] Core started");
|
||||
} catch (e) {
|
||||
|
|
|
|||
|
|
@ -234,15 +234,17 @@ describe("Test Suite", () => {
|
|||
result: { config },
|
||||
} = await messenger.request("config/getSerializedProfileInfo", undefined);
|
||||
|
||||
expect(config!.models.some((m) => m.title === model.title)).toBe(true);
|
||||
expect(config!.modelsByRole.chat.some((m) => m.title === model.title)).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
await messenger.request("config/deleteModel", { title: model.title });
|
||||
const {
|
||||
result: { config: configAfterDelete },
|
||||
} = await messenger.request("config/getSerializedProfileInfo", undefined);
|
||||
expect(configAfterDelete!.models.some((m) => m.title === model.title)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
configAfterDelete!.modelsByRole.chat.some((m) => m.title === model.title),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should make an LLM completion", async () => {
|
||||
|
|
|
|||
|
|
@ -12,11 +12,11 @@
|
|||
"curly": "off",
|
||||
"@typescript-eslint/semi": "off",
|
||||
"eqeqeq": "error",
|
||||
"complexity": ["error", { "max": 38 }],
|
||||
"max-lines-per-function": ["error", { "max": 996 }],
|
||||
"max-statements": ["error", { "max": 114 }],
|
||||
"complexity": ["error", { "max": 36 }],
|
||||
"max-lines-per-function": ["error", { "max": 500 }],
|
||||
"max-statements": ["error", { "max": 108 }],
|
||||
"max-depth": ["error", { "max": 6 }],
|
||||
"max-nested-callbacks": ["error", { "max": 4 }],
|
||||
"max-params": ["error", { "max": 11 }]
|
||||
"max-params": ["error", { "max": 8 }]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -154,6 +154,10 @@ export class CompletionProvider {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
if (llm.promptTemplates?.autocomplete) {
|
||||
options.template = llm.promptTemplates.autocomplete as string;
|
||||
}
|
||||
|
||||
const helper = await HelperVars.create(
|
||||
input,
|
||||
options,
|
||||
|
|
|
|||
|
|
@ -88,7 +88,6 @@ export class RootPathContextService {
|
|||
default:
|
||||
// const type = node.type;
|
||||
// console.log(getSyntaxTreeString(node));
|
||||
// debugger;
|
||||
|
||||
query = await getQueryForFile(
|
||||
filepath,
|
||||
|
|
@ -165,7 +164,6 @@ export class RootPathContextService {
|
|||
)) {
|
||||
const key = RootPathContextService.keyFromNode(parentKey, astNode);
|
||||
// const type = astNode.type;
|
||||
// debugger;
|
||||
|
||||
const foundInCache = this.cache.get(key);
|
||||
const newSnippets =
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ export function postprocessCompletion({
|
|||
}
|
||||
}
|
||||
|
||||
if (llm.model.includes("granite")) {
|
||||
if (llm.model.includes("mercury") || llm.model.includes("granite")) {
|
||||
// Granite tends to repeat the start of the line in the completion output
|
||||
let prefixEnd = prefix.split("\n").pop();
|
||||
if (prefixEnd) {
|
||||
|
|
@ -123,13 +123,14 @@ export function postprocessCompletion({
|
|||
|
||||
// // If completion starts with multiple whitespaces, but the cursor is at the end of the line
|
||||
// // then it should probably be on a new line
|
||||
// if (
|
||||
// (completion.startsWith(" ") || completion.startsWith("\t")) &&
|
||||
// !prefix.endsWith("\n") &&
|
||||
// (suffix.startsWith("\n") || suffix.trim().length === 0)
|
||||
// ) {
|
||||
// completion = "\n" + completion;
|
||||
// }
|
||||
if (
|
||||
llm.model.includes("mercury") &&
|
||||
(completion.startsWith(" ") || completion.startsWith("\t")) &&
|
||||
!prefix.endsWith("\n") &&
|
||||
(suffix.startsWith("\n") || suffix.trim().length === 0)
|
||||
) {
|
||||
completion = "\n" + completion;
|
||||
}
|
||||
|
||||
// If prefix ends with space and so does completion, then remove the space from completion
|
||||
|
||||
|
|
|
|||
|
|
@ -87,9 +87,10 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
|
|||
snippets,
|
||||
workspaceUris,
|
||||
): [string, string] => {
|
||||
|
||||
function getFileName(snippet: { uri: string, uniquePath: string }) {
|
||||
return snippet.uri.startsWith("file://") ? snippet.uniquePath : snippet.uri
|
||||
function getFileName(snippet: { uri: string; uniquePath: string }) {
|
||||
return snippet.uri.startsWith("file://")
|
||||
? snippet.uniquePath
|
||||
: snippet.uri;
|
||||
}
|
||||
|
||||
if (snippets.length === 0) {
|
||||
|
|
@ -135,6 +136,64 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
|
|||
},
|
||||
};
|
||||
|
||||
const mercuryMultifileFimTemplate: AutocompleteTemplate = {
|
||||
compilePrefixSuffix: (
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
snippets,
|
||||
workspaceUris,
|
||||
): [string, string] => {
|
||||
function getFileName(snippet: { uri: string; uniquePath: string }) {
|
||||
return snippet.uri.startsWith("file://")
|
||||
? snippet.uniquePath
|
||||
: snippet.uri;
|
||||
}
|
||||
|
||||
// Our current snippet format doesn't work well with mercury. We need to clean this up
|
||||
snippets = [];
|
||||
|
||||
if (snippets.length === 0) {
|
||||
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
|
||||
return [
|
||||
`<|file_sep|>${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n${prefix}`,
|
||||
suffix,
|
||||
];
|
||||
}
|
||||
return [prefix, suffix];
|
||||
}
|
||||
|
||||
const relativePaths = getShortestUniqueRelativeUriPaths(
|
||||
[
|
||||
...snippets.map((snippet) =>
|
||||
"filepath" in snippet ? snippet.filepath : "file:///Untitled.txt",
|
||||
),
|
||||
filepath,
|
||||
],
|
||||
workspaceUris,
|
||||
);
|
||||
|
||||
const otherFiles = snippets
|
||||
.map((snippet, i) => {
|
||||
if (snippet.type === AutocompleteSnippetType.Diff) {
|
||||
return snippet.content;
|
||||
}
|
||||
|
||||
return `<|file_sep|>${getFileName(relativePaths[i])} \n${snippet.content}`;
|
||||
})
|
||||
.join("\n\n");
|
||||
|
||||
return [
|
||||
`${otherFiles}${otherFiles ? "\n\n" : ""}<|file_sep|>${getFileName(relativePaths[relativePaths.length - 1])}\n<|fim_prefix|>${prefix}`,
|
||||
suffix,
|
||||
];
|
||||
},
|
||||
template: (prefix: string, suffix: string): string => {
|
||||
return `${prefix}<|fim_suffix|>${suffix}<|fim_middle|>`;
|
||||
},
|
||||
};
|
||||
|
||||
const codegemmaFimTemplate: AutocompleteTemplate = {
|
||||
template:
|
||||
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
|
||||
|
|
@ -223,8 +282,9 @@ const codegeexFimTemplate: AutocompleteTemplate = {
|
|||
[...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|>`;
|
||||
const baseTemplate = `###PATH:${
|
||||
relativePaths[relativePaths.length - 1]
|
||||
}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
|
||||
if (snippets.length === 0) {
|
||||
return `<|user|>\n${baseTemplate}<|assistant|>\n`;
|
||||
}
|
||||
|
|
@ -358,6 +418,9 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
|
|||
// if (lowerCaseModel.includes("starcoder2")) {
|
||||
// return starcoder2FimTemplate;
|
||||
// }
|
||||
if (lowerCaseModel.includes("mercury")) {
|
||||
return mercuryMultifileFimTemplate;
|
||||
}
|
||||
|
||||
if (lowerCaseModel.includes("qwen") && lowerCaseModel.includes("coder")) {
|
||||
return qwenCoderFimTemplate;
|
||||
|
|
|
|||
|
|
@ -39,20 +39,28 @@ export class AutocompleteLruCache {
|
|||
// If the query is "co" and we have "c" -> "ontinue" in the cache,
|
||||
// we should return "ntinue" as the completion.
|
||||
// Have to make sure we take the key with shortest length
|
||||
const result = await this.db.get(
|
||||
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
|
||||
truncateSqliteLikePattern(prefix),
|
||||
);
|
||||
|
||||
// Validate that the cached compeltion is a valid completion for the prefix
|
||||
if (result && result.value.startsWith(prefix.slice(result.key.length))) {
|
||||
await this.db.run(
|
||||
"UPDATE cache SET timestamp = ? WHERE key = ?",
|
||||
Date.now(),
|
||||
prefix,
|
||||
const truncatedPrefix = truncateSqliteLikePattern(prefix);
|
||||
try {
|
||||
const result = await this.db.get(
|
||||
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
|
||||
truncatedPrefix,
|
||||
);
|
||||
// And then truncate so we aren't writing something that's already there
|
||||
return result.value.slice(prefix.length - result.key.length);
|
||||
// Validate that the cached completion is a valid completion for the prefix
|
||||
if (
|
||||
result &&
|
||||
result.value.startsWith(truncatedPrefix.slice(result.key.length))
|
||||
) {
|
||||
await this.db.run(
|
||||
"UPDATE cache SET timestamp = ? WHERE key = ?",
|
||||
Date.now(),
|
||||
truncatedPrefix,
|
||||
);
|
||||
// And then truncate so we aren't writing something that's already there
|
||||
return result.value.slice(truncatedPrefix.length - result.key.length);
|
||||
}
|
||||
} catch (e) {
|
||||
// catches e.g. old SQLITE LIKE OR GLOB PATTERN TOO COMPLEX
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
@ -60,13 +68,15 @@ export class AutocompleteLruCache {
|
|||
|
||||
async put(prefix: string, completion: string) {
|
||||
const release = await this.mutex.acquire();
|
||||
|
||||
const truncatedPrefix = truncateSqliteLikePattern(prefix);
|
||||
try {
|
||||
await this.db.run("BEGIN TRANSACTION");
|
||||
|
||||
try {
|
||||
const result = await this.db.get(
|
||||
"SELECT key FROM cache WHERE key = ?",
|
||||
prefix,
|
||||
truncatedPrefix,
|
||||
);
|
||||
|
||||
if (result) {
|
||||
|
|
@ -74,7 +84,7 @@ export class AutocompleteLruCache {
|
|||
"UPDATE cache SET value = ?, timestamp = ? WHERE key = ?",
|
||||
completion,
|
||||
Date.now(),
|
||||
prefix,
|
||||
truncatedPrefix,
|
||||
);
|
||||
} else {
|
||||
const count = await this.db.get(
|
||||
|
|
@ -89,7 +99,7 @@ export class AutocompleteLruCache {
|
|||
|
||||
await this.db.run(
|
||||
"INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)",
|
||||
prefix,
|
||||
truncatedPrefix,
|
||||
completion,
|
||||
Date.now(),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
|
||||
import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
|
||||
import { renderChatMessage } from "../util/messageContent";
|
||||
|
||||
import SlashCommands from "./slash";
|
||||
|
|
@ -15,7 +16,16 @@ export function slashFromCustomCommand(
|
|||
name: commandName,
|
||||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
run: async function* ({ input, llm, history, ide, completionOptions }) {
|
||||
run: async function* ({
|
||||
input,
|
||||
llm,
|
||||
history,
|
||||
ide,
|
||||
completionOptions,
|
||||
config,
|
||||
selectedCode,
|
||||
fetch,
|
||||
}) {
|
||||
// Render prompt template
|
||||
let renderedPrompt: string;
|
||||
if (customCommand.prompt.includes("{{{ input }}}")) {
|
||||
|
|
@ -25,7 +35,21 @@ export function slashFromCustomCommand(
|
|||
{ input },
|
||||
);
|
||||
} else {
|
||||
renderedPrompt = customCommand.prompt + "\n\n" + input;
|
||||
const renderedPromptFile = await renderPromptFileV2(
|
||||
customCommand.prompt,
|
||||
{
|
||||
config,
|
||||
llm,
|
||||
ide,
|
||||
selectedCode,
|
||||
fetch,
|
||||
fullInput: input,
|
||||
embeddingsProvider: config.modelsByRole.embed[0],
|
||||
reranker: config.modelsByRole.rerank[0],
|
||||
},
|
||||
);
|
||||
|
||||
renderedPrompt = renderedPromptFile[1];
|
||||
}
|
||||
|
||||
// Replaces slash command messages with the rendered prompt
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ const DraftIssueCommand: SlashCommand = {
|
|||
let title = await llm.complete(
|
||||
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
|
||||
new AbortController().signal,
|
||||
{ maxTokens: 20 },
|
||||
{ maxTokens: 30 },
|
||||
);
|
||||
|
||||
title = `${removeQuotesAndEscapes(title.trim())}\n\n`;
|
||||
|
|
@ -40,7 +40,7 @@ const DraftIssueCommand: SlashCommand = {
|
|||
|
||||
let body = "";
|
||||
const messages: ChatMessage[] = [
|
||||
...history,
|
||||
...history.filter((msg) => msg.role !== "system"),
|
||||
{ role: "user", content: PROMPT(input, title) },
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
export function constructMcpSlashCommand(
|
||||
|
|
@ -22,8 +23,8 @@ export function constructMcpSlashCommand(
|
|||
}
|
||||
|
||||
const result = await client.getPrompt({ name, arguments: argsObject });
|
||||
|
||||
const messages: ChatMessage[] = result.messages.map((msg) => {
|
||||
const mcpMessages: PromptMessage[] = result.messages;
|
||||
const messages: ChatMessage[] = mcpMessages.map((msg) => {
|
||||
if (msg.content.type !== "text") {
|
||||
throw new Error(
|
||||
"Continue currently only supports text prompts through MCP",
|
||||
|
|
@ -40,12 +41,22 @@ export function constructMcpSlashCommand(
|
|||
return;
|
||||
}
|
||||
|
||||
const reversedMessages = [...messages].reverse();
|
||||
const messageToAppendInput =
|
||||
reversedMessages.find((m) => m.role === "user") ??
|
||||
reversedMessages.find((m) => m.role === "assistant") ??
|
||||
reversedMessages[0];
|
||||
messageToAppendInput.content += ` ${userInput}`;
|
||||
if (userInput) {
|
||||
const lastMessage = messages.at(-1);
|
||||
if (!lastMessage || lastMessage.role !== "user") {
|
||||
messages.push({
|
||||
role: "user",
|
||||
content: userInput,
|
||||
});
|
||||
} else {
|
||||
let newContent = renderChatMessage(lastMessage);
|
||||
if (newContent) {
|
||||
newContent += "\n\n";
|
||||
}
|
||||
newContent += userInput;
|
||||
lastMessage.content = newContent;
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
|
|
|
|||
|
|
@ -34,13 +34,18 @@ export function ctxItemToRifWithContents(
|
|||
): RangeInFileWithContents {
|
||||
let startLine = 0;
|
||||
let endLine = 0;
|
||||
let adjustLines = linesOffByOne ? 1 : 0;
|
||||
|
||||
const nameSplit = item.name.split("(");
|
||||
|
||||
if (nameSplit.length > 1) {
|
||||
const lines = nameSplit[1].split(")")[0].split("-");
|
||||
startLine = Number.parseInt(lines[0], 10) - (linesOffByOne ? 1 : 0);
|
||||
endLine = Number.parseInt(lines[1], 10) - (linesOffByOne ? 1 : 0);
|
||||
startLine = Number.parseInt(lines[0], 10);
|
||||
if (startLine === 0) {
|
||||
adjustLines = 0; // safety to make sure doesn't go negative
|
||||
}
|
||||
startLine -= adjustLines;
|
||||
endLine = Number.parseInt(lines[1], 10) - adjustLines;
|
||||
}
|
||||
|
||||
const rif: RangeInFileWithContents = {
|
||||
|
|
|
|||
|
|
@ -9,9 +9,9 @@ import { defaultConfig } from "./default";
|
|||
|
||||
describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
||||
test("should show only local profile", () => {
|
||||
const profiles = testConfigHandler.listProfiles();
|
||||
const profiles = testConfigHandler.currentOrg.profiles;
|
||||
expect(profiles?.length).toBe(1);
|
||||
expect(profiles?.[0].id).toBe("local");
|
||||
expect(profiles?.[0].profileDescription.id).toBe("local");
|
||||
|
||||
const currentProfile = testConfigHandler.currentProfile;
|
||||
expect(currentProfile?.profileDescription.id).toBe("local");
|
||||
|
|
@ -19,7 +19,9 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
|||
|
||||
test("should load the default config successfully", async () => {
|
||||
const result = await testConfigHandler.loadConfig();
|
||||
expect(result.config!.models.length).toBe(defaultConfig.models?.length);
|
||||
expect(result.config!.modelsByRole.chat.length).toBe(
|
||||
defaultConfig.models?.length,
|
||||
);
|
||||
});
|
||||
|
||||
test.skip("should add a system message from config.ts", async () => {
|
||||
|
|
|
|||
|
|
@ -1,384 +1,323 @@
|
|||
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
import {
|
||||
ControlPlaneClient,
|
||||
ControlPlaneSessionInfo,
|
||||
} from "../control-plane/client.js";
|
||||
import { getControlPlaneEnv, useHub } from "../control-plane/env.js";
|
||||
import { getControlPlaneEnv } from "../control-plane/env.js";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContinueConfig,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
} from "../index.js";
|
||||
import Ollama from "../llm/llms/Ollama.js";
|
||||
import { GlobalContext } from "../util/GlobalContext.js";
|
||||
|
||||
import { getAllAssistantFiles } from "./loadLocalAssistants.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
import {
|
||||
LOCAL_ONBOARDING_CHAT_MODEL,
|
||||
LOCAL_ONBOARDING_PROVIDER_TITLE,
|
||||
} from "./onboarding.js";
|
||||
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
|
||||
ASSISTANTS,
|
||||
getAllDotContinueYamlFiles,
|
||||
LoadAssistantFilesOptions,
|
||||
} from "./loadLocalAssistants.js";
|
||||
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
|
||||
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
|
||||
import {
|
||||
OrganizationDescription,
|
||||
OrgWithProfiles,
|
||||
ProfileDescription,
|
||||
ProfileLifecycleManager,
|
||||
SerializedOrgWithProfiles,
|
||||
} from "./ProfileLifecycleManager.js";
|
||||
|
||||
export type { ProfileDescription };
|
||||
|
||||
type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
|
||||
|
||||
// Separately manages saving/reloading each profile
|
||||
|
||||
export class ConfigHandler {
|
||||
private readonly globalContext = new GlobalContext();
|
||||
private additionalContextProviders: IContextProvider[] = [];
|
||||
private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded
|
||||
private selectedProfileId: string | null = null;
|
||||
private localProfileManager: ProfileLifecycleManager;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
private readonly globalContext = new GlobalContext();
|
||||
private globalLocalProfileManager: ProfileLifecycleManager;
|
||||
|
||||
initializedPromise: Promise<void>;
|
||||
private organizations: OrgWithProfiles[] = [];
|
||||
currentProfile: ProfileLifecycleManager | null;
|
||||
currentOrg: OrgWithProfiles;
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly writeLog: (text: string) => Promise<void>,
|
||||
private llmLogger: ILLMLogger,
|
||||
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
|
||||
private readonly didSelectOrganization?: (orgId: string | null) => void,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
this.writeLog = writeLog;
|
||||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
sessionInfoPromise,
|
||||
ideSettingsPromise,
|
||||
);
|
||||
|
||||
// Set local profile as default
|
||||
const localProfileLoader = new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
writeLog,
|
||||
);
|
||||
this.localProfileManager = new ProfileLifecycleManager(
|
||||
localProfileLoader,
|
||||
// This profile manager will always be available
|
||||
this.globalLocalProfileManager = new ProfileLifecycleManager(
|
||||
new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.llmLogger,
|
||||
),
|
||||
this.ide,
|
||||
);
|
||||
|
||||
// Profiles are loaded asynchronously
|
||||
this.initializedPromise = new Promise((resolve, reject) => {
|
||||
this.init()
|
||||
.then(() => {
|
||||
resolve();
|
||||
})
|
||||
.catch((e) => {
|
||||
reject(e);
|
||||
});
|
||||
});
|
||||
// Just to be safe, always force a default personal org with local profile manager
|
||||
this.currentProfile = this.globalLocalProfileManager;
|
||||
const personalOrg: OrgWithProfiles = {
|
||||
currentProfile: this.globalLocalProfileManager,
|
||||
profiles: [this.globalLocalProfileManager],
|
||||
...this.PERSONAL_ORG_DESC,
|
||||
};
|
||||
|
||||
this.currentOrg = personalOrg;
|
||||
this.organizations = [personalOrg];
|
||||
|
||||
void this.cascadeInit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
private async getLocalAssistantProfiles() {
|
||||
const assistantFiles = await getAllAssistantFiles(this.ide);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
assistant,
|
||||
);
|
||||
});
|
||||
return profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the titles of additional context providers that are of type "submenu".
|
||||
*
|
||||
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
|
||||
*/
|
||||
getAdditionalSubmenuContextProviders(): string[] {
|
||||
return this.additionalContextProviders
|
||||
.filter((provider) => provider.description.type === "submenu")
|
||||
.map((provider) => provider.description.title);
|
||||
}
|
||||
|
||||
private async init() {
|
||||
try {
|
||||
await this.fetchControlPlaneProfiles();
|
||||
} catch (e) {
|
||||
// If this fails, make sure at least local profile is loaded
|
||||
console.error("Failed to fetch control plane profiles in init: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
|
||||
try {
|
||||
const configResult = await this.loadConfig();
|
||||
this.notifyConfigListeners(configResult);
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
private workspaceDirs: string[] | null = null;
|
||||
async getWorkspaceId() {
|
||||
if (!this.workspaceDirs) {
|
||||
this.workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
}
|
||||
return this.workspaceDirs.join("&");
|
||||
}
|
||||
|
||||
get currentProfile() {
|
||||
if (!this.selectedProfileId) {
|
||||
return null;
|
||||
}
|
||||
// IMPORTANT
|
||||
// We must fall back to null, not the first or local profiles
|
||||
// Because GUI must be the source of truth for selected profile
|
||||
return (
|
||||
this.profiles?.find(
|
||||
(p) => p.profileDescription.id === this.selectedProfileId,
|
||||
) ?? null
|
||||
);
|
||||
async getProfileKey(orgId: string) {
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return `${workspaceId}:::${orgId}`;
|
||||
}
|
||||
|
||||
get inactiveProfiles() {
|
||||
return (this.profiles ?? []).filter(
|
||||
(p) => p.profileDescription.id !== this.selectedProfileId,
|
||||
);
|
||||
}
|
||||
private async cascadeInit() {
|
||||
this.workspaceDirs = null; // forces workspace dirs reload
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.selectedProfileId;
|
||||
const profile = this.profiles?.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
const orgs = await this.getOrgs();
|
||||
|
||||
// Figure out selected org
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const currentSelection = selectedOrgs[workspaceId];
|
||||
|
||||
const firstNonPersonal = orgs.find(
|
||||
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
|
||||
);
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
const fallback = firstNonPersonal ?? orgs[0];
|
||||
// note, ignoring case of zero orgs since should never happen
|
||||
|
||||
let selectedOrg: OrgWithProfiles;
|
||||
if (!currentSelection) {
|
||||
selectedOrg = fallback;
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async listOrganizations() {
|
||||
return await this.controlPlaneClient.listOrganizations();
|
||||
}
|
||||
|
||||
async loadAssistantsForSelectedOrg() {
|
||||
// Get the profiles and create their lifecycle managers
|
||||
const userId = await this.controlPlaneClient.userId;
|
||||
const selectedOrgId = await this.getSelectedOrgId();
|
||||
|
||||
let profiles: ProfileLifecycleManager[] | null = null;
|
||||
if (!userId) {
|
||||
// Not logged in
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
profiles = [...allLocalProfiles];
|
||||
} else {
|
||||
// Logged in
|
||||
const assistants =
|
||||
await this.controlPlaneClient.listAssistants(selectedOrgId);
|
||||
|
||||
const hubProfiles = await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create(
|
||||
{
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
assistant.ownerSlug,
|
||||
assistant.packageSlug,
|
||||
assistant.iconUrl,
|
||||
assistant.configResult.config?.version ?? "latest",
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
assistant.rawYaml,
|
||||
selectedOrgId,
|
||||
);
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
|
||||
if (selectedOrgId === null) {
|
||||
// Personal
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
profiles = [...hubProfiles, ...allLocalProfiles];
|
||||
const match = orgs.find((org) => org.id === currentSelection);
|
||||
if (match) {
|
||||
selectedOrg = match;
|
||||
} else {
|
||||
// Organization
|
||||
profiles = hubProfiles;
|
||||
selectedOrg = fallback;
|
||||
}
|
||||
}
|
||||
|
||||
await this.updateAvailableProfiles(profiles);
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
...selectedOrgs,
|
||||
[workspaceId]: selectedOrg.id,
|
||||
});
|
||||
|
||||
this.organizations = orgs;
|
||||
this.currentOrg = selectedOrg;
|
||||
this.currentProfile = selectedOrg.currentProfile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
|
||||
private async getAllLocalProfiles() {
|
||||
const localAssistantProfiles = await this.getLocalAssistantProfiles();
|
||||
return [this.localProfileManager, ...localAssistantProfiles];
|
||||
}
|
||||
|
||||
private async loadLocalProfilesOnly() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
await this.updateAvailableProfiles(allLocalProfiles);
|
||||
}
|
||||
|
||||
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
|
||||
this.profiles = profiles;
|
||||
|
||||
// If the last selected profile is in the list choose that
|
||||
// Otherwise, choose the first profile
|
||||
const previouslySelectedProfileId =
|
||||
await this.getPersistedSelectedProfileId();
|
||||
|
||||
// Check if the previously selected profile exists in the current profiles
|
||||
const profileExists = profiles.some(
|
||||
(profile) =>
|
||||
profile.profileDescription.id === previouslySelectedProfileId,
|
||||
);
|
||||
|
||||
const selectedProfileId = profileExists
|
||||
? previouslySelectedProfileId
|
||||
: (profiles[0]?.profileDescription.id ?? null);
|
||||
|
||||
// Notify listeners
|
||||
const profileDescriptions = profiles.map(
|
||||
(profile) => profile.profileDescription,
|
||||
);
|
||||
this.notifyProfileListeners(profileDescriptions, selectedProfileId);
|
||||
await this.setSelectedProfile(selectedProfileId);
|
||||
}
|
||||
|
||||
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
|
||||
// We use this to keep track of whether we should reload the assistants
|
||||
private lastFullSlugsList: FullSlug[] = [];
|
||||
|
||||
private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean {
|
||||
if (a.length !== b.length) {
|
||||
return true;
|
||||
}
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i].ownerSlug !== b[i].ownerSlug) {
|
||||
return true;
|
||||
}
|
||||
if (a[i].packageSlug !== b[i].packageSlug) {
|
||||
return true;
|
||||
}
|
||||
if (a[i].versionSlug !== b[i].versionSlug) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private async reloadHubAssistants() {
|
||||
const selectedOrgId = await this.getSelectedOrgId();
|
||||
const newFullSlugsList =
|
||||
await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId);
|
||||
|
||||
if (newFullSlugsList) {
|
||||
const shouldReload = this.fullSlugsListsDiffer(
|
||||
newFullSlugsList,
|
||||
this.lastFullSlugsList,
|
||||
);
|
||||
if (shouldReload) {
|
||||
await this.loadAssistantsForSelectedOrg();
|
||||
}
|
||||
this.lastFullSlugsList = newFullSlugsList;
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchControlPlaneProfiles() {
|
||||
if (await useHub(this.ideSettingsPromise)) {
|
||||
clearInterval(this.platformProfilesRefreshInterval);
|
||||
await this.loadAssistantsForSelectedOrg();
|
||||
|
||||
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
|
||||
// If so, we do the full (more expensive) reload
|
||||
this.platformProfilesRefreshInterval = setInterval(
|
||||
this.reloadHubAssistants.bind(this),
|
||||
PlatformProfileLoader.RELOAD_INTERVAL,
|
||||
private async getOrgs(): Promise<OrgWithProfiles[]> {
|
||||
const userId = await this.controlPlaneClient.userId;
|
||||
if (userId) {
|
||||
const orgDescs = await this.controlPlaneClient.listOrganizations();
|
||||
const personalHubOrg = await this.getPersonalHubOrg();
|
||||
const hubOrgs = await Promise.all(
|
||||
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
|
||||
);
|
||||
return [...hubOrgs, personalHubOrg];
|
||||
} else {
|
||||
try {
|
||||
const workspaces = await this.controlPlaneClient.listWorkspaces();
|
||||
const profiles = await this.getAllLocalProfiles();
|
||||
workspaces.forEach((workspace) => {
|
||||
const profileLoader = new ControlPlaneProfileLoader(
|
||||
workspace.id,
|
||||
workspace.name,
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
return [await this.getLocalOrg()];
|
||||
}
|
||||
}
|
||||
|
||||
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
|
||||
getSerializedOrgs(): SerializedOrgWithProfiles[] {
|
||||
return this.organizations.map((org) => ({
|
||||
iconUrl: org.iconUrl,
|
||||
id: org.id,
|
||||
name: org.name,
|
||||
slug: org.slug,
|
||||
profiles: org.profiles.map((profile) => profile.profileDescription),
|
||||
selectedProfileId: org.currentProfile?.profileDescription.id || null,
|
||||
}));
|
||||
}
|
||||
|
||||
private async getHubProfiles(orgScopeId: string | null) {
|
||||
const assistants = await this.controlPlaneClient.listAssistants(orgScopeId);
|
||||
|
||||
return await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create({
|
||||
configResult: {
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
ownerSlug: assistant.ownerSlug,
|
||||
packageSlug: assistant.packageSlug,
|
||||
iconUrl: assistant.iconUrl,
|
||||
versionSlug: assistant.configResult.config?.version ?? "latest",
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
ide: this.ide,
|
||||
ideSettingsPromise: this.ideSettingsPromise,
|
||||
llmLogger: this.llmLogger,
|
||||
rawYaml: assistant.rawYaml,
|
||||
orgScopeId: orgScopeId,
|
||||
});
|
||||
|
||||
await this.updateAvailableProfiles(profiles);
|
||||
} catch (e: any) {
|
||||
console.error("Failed to load profiles: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
}
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async getPersistedSelectedProfileId(): Promise<string | null> {
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const lastSelectedIds =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
return lastSelectedIds[workspaceId] ?? null;
|
||||
private async getNonPersonalHubOrg(
|
||||
org: OrganizationDescription,
|
||||
): Promise<OrgWithProfiles> {
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
});
|
||||
const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
async getSelectedOrgId(): Promise<string | null> {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return selectedOrgs[workspaceId] ?? null;
|
||||
private PERSONAL_ORG_DESC: OrganizationDescription = {
|
||||
iconUrl: "",
|
||||
id: "personal",
|
||||
name: "Personal",
|
||||
slug: undefined,
|
||||
};
|
||||
private async getPersonalHubOrg() {
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
includeGlobal: true,
|
||||
includeWorkspace: true,
|
||||
});
|
||||
const hubProfiles = await this.getHubProfiles(null);
|
||||
const profiles = [...hubProfiles, ...localProfiles];
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
|
||||
}
|
||||
|
||||
async setSelectedOrgId(orgId: string | null) {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
selectedOrgs[await this.getWorkspaceId()] = orgId;
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
|
||||
this.didSelectOrganization?.(orgId);
|
||||
private async getLocalOrg() {
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
includeGlobal: true,
|
||||
includeWorkspace: true,
|
||||
});
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
|
||||
}
|
||||
|
||||
async setSelectedProfile(profileId: string | null) {
|
||||
this.selectedProfileId = profileId;
|
||||
const result = await this.loadConfig();
|
||||
this.notifyConfigListeners(result);
|
||||
private async rectifyProfilesForOrg(
|
||||
org: OrganizationDescription,
|
||||
profiles: ProfileLifecycleManager[],
|
||||
): Promise<OrgWithProfiles> {
|
||||
const profileKey = await this.getProfileKey(org.id);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
selectedProfiles[await this.getWorkspaceId()] = profileId;
|
||||
this.globalContext.update(
|
||||
"lastSelectedProfileForWorkspace",
|
||||
selectedProfiles,
|
||||
|
||||
const currentSelection = selectedProfiles[profileKey];
|
||||
|
||||
const firstNonLocal = profiles.find(
|
||||
(profile) => profile.profileDescription.profileType !== "local",
|
||||
);
|
||||
const fallback =
|
||||
firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
|
||||
|
||||
let currentProfile: ProfileLifecycleManager | null;
|
||||
if (!currentSelection) {
|
||||
currentProfile = fallback;
|
||||
} else {
|
||||
const match = profiles.find(
|
||||
(profile) => profile.profileDescription.id === currentSelection,
|
||||
);
|
||||
if (match) {
|
||||
currentProfile = match;
|
||||
} else {
|
||||
currentProfile = fallback;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentProfile) {
|
||||
this.globalContext.update("lastSelectedProfileForWorkspace", {
|
||||
...selectedProfiles,
|
||||
[profileKey]: selectedProfiles.id ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
...org,
|
||||
profiles,
|
||||
currentProfile,
|
||||
};
|
||||
}
|
||||
|
||||
// A unique ID for the current workspace, built from folder names
|
||||
private async getWorkspaceId(): Promise<string> {
|
||||
const dirs = await this.ide.getWorkspaceDirs();
|
||||
return dirs.join("&");
|
||||
async getLocalProfiles(options: LoadAssistantFilesOptions) {
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
const localProfiles: ProfileLifecycleManager[] = [];
|
||||
|
||||
if (options.includeGlobal) {
|
||||
localProfiles.push(this.globalLocalProfileManager);
|
||||
}
|
||||
|
||||
if (options.includeWorkspace) {
|
||||
const assistantFiles = await getAllDotContinueYamlFiles(
|
||||
this.ide,
|
||||
{
|
||||
...options,
|
||||
includeGlobal: false, // Because the global comes from above
|
||||
},
|
||||
ASSISTANTS,
|
||||
);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.llmLogger,
|
||||
assistant,
|
||||
);
|
||||
});
|
||||
const localAssistantProfiles = profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
);
|
||||
localProfiles.push(...localAssistantProfiles);
|
||||
}
|
||||
|
||||
return localProfiles;
|
||||
}
|
||||
|
||||
// Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed
|
||||
updateIdeSettings(ideSettings: IdeSettings) {
|
||||
//////////////////
|
||||
// External actions that can cause a cascading config refresh
|
||||
// Should not be used internally
|
||||
//////////////////
|
||||
async refreshAll() {
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
// Ide settings change: refresh session and cascade refresh from the top
|
||||
async updateIdeSettings(ideSettings: IdeSettings) {
|
||||
this.ideSettingsPromise = Promise.resolve(ideSettings);
|
||||
void this.reloadConfig();
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
// Session change: refresh session and cascade refresh from the top
|
||||
async updateControlPlaneSessionInfo(
|
||||
sessionInfo: ControlPlaneSessionInfo | undefined,
|
||||
) {
|
||||
|
|
@ -386,38 +325,97 @@ export class ConfigHandler {
|
|||
Promise.resolve(sessionInfo),
|
||||
this.ideSettingsPromise,
|
||||
);
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
this.fetchControlPlaneProfiles().catch(async (e) => {
|
||||
console.error("Failed to fetch control plane profiles: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
await this.reloadConfig();
|
||||
// Org id: check id validity, save selection, switch and reload
|
||||
async setSelectedOrgId(orgId: string, profileId?: string) {
|
||||
if (orgId === this.currentOrg.id) {
|
||||
return;
|
||||
}
|
||||
const org = this.organizations.find((org) => org.id === orgId);
|
||||
if (!org) {
|
||||
throw new Error(`Org ${orgId} not found`);
|
||||
}
|
||||
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
...selectedOrgs,
|
||||
[workspaceId]: org.id,
|
||||
});
|
||||
}
|
||||
|
||||
private profilesListeners: ((
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) => void)[] = [];
|
||||
onDidChangeAvailableProfiles(
|
||||
listener: (
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) => void,
|
||||
) {
|
||||
this.profilesListeners.push(listener);
|
||||
}
|
||||
this.currentOrg = org;
|
||||
|
||||
private notifyProfileListeners(
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) {
|
||||
for (const listener of this.profilesListeners) {
|
||||
listener(profiles, selectedProfileId);
|
||||
if (profileId) {
|
||||
this.setSelectedProfileId(profileId);
|
||||
} else {
|
||||
this.currentProfile = org.currentProfile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
}
|
||||
|
||||
// Profile id: check id validity, save selection, switch and reload
|
||||
async setSelectedProfileId(profileId: string) {
|
||||
if (
|
||||
this.currentProfile &&
|
||||
profileId === this.currentProfile.profileDescription.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const profile = this.currentOrg.profiles.find(
|
||||
(profile) => profile.profileDescription.id === profileId,
|
||||
);
|
||||
if (!profile) {
|
||||
throw new Error(`Profile ${profileId} not found in current org`);
|
||||
}
|
||||
|
||||
const profileKey = await this.getProfileKey(this.currentOrg.id);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
this.globalContext.update("lastSelectedProfileForWorkspace", {
|
||||
...selectedProfiles,
|
||||
[profileKey]: profileId,
|
||||
});
|
||||
|
||||
this.currentProfile = profile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
|
||||
// Bottom level of cascade: refresh the current profile
|
||||
// IMPORTANT - must always refresh when switching profiles
|
||||
// Because of e.g. MCP singleton and docs service using things from config
|
||||
// Could improve this
|
||||
async reloadConfig() {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
||||
for (const org of this.organizations) {
|
||||
for (const profile of org.profiles) {
|
||||
if (
|
||||
profile.profileDescription.id !==
|
||||
this.currentProfile.profileDescription.id
|
||||
) {
|
||||
profile.clearConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { config, errors, configLoadInterrupted } =
|
||||
await this.currentProfile.reloadConfig(this.additionalContextProviders);
|
||||
|
||||
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
|
||||
return { config, errors, configLoadInterrupted };
|
||||
}
|
||||
|
||||
// Listeners setup - can listen to current profile updates
|
||||
private notifyConfigListeners(result: ConfigResult<ContinueConfig>) {
|
||||
// Notify listeners that config changed
|
||||
for (const listener of this.updateListeners) {
|
||||
listener(result);
|
||||
}
|
||||
|
|
@ -429,27 +427,9 @@ export class ConfigHandler {
|
|||
this.updateListeners.push(listener);
|
||||
}
|
||||
|
||||
// TODO: this isn't right, there are two different senses in which you want to "reload"
|
||||
async reloadConfig() {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
||||
const { config, errors, configLoadInterrupted } =
|
||||
await this.currentProfile.reloadConfig(this.additionalContextProviders);
|
||||
|
||||
if (config) {
|
||||
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
|
||||
}
|
||||
|
||||
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
|
||||
return { config, errors, configLoadInterrupted };
|
||||
}
|
||||
|
||||
// Methods for loading (without reloading) config
|
||||
// Serialized for passing to GUI
|
||||
// Load for just awaiting current config load promise for the profile
|
||||
async getSerializedConfig(): Promise<
|
||||
ConfigResult<BrowserSerializedContinueConfig>
|
||||
> {
|
||||
|
|
@ -465,10 +445,6 @@ export class ConfigHandler {
|
|||
);
|
||||
}
|
||||
|
||||
listProfiles(): ProfileDescription[] | null {
|
||||
return this.profiles?.map((p) => p.profileDescription) ?? null;
|
||||
}
|
||||
|
||||
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
|
|
@ -477,33 +453,46 @@ export class ConfigHandler {
|
|||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
return await this.currentProfile.loadConfig(
|
||||
const config = await this.currentProfile.loadConfig(
|
||||
this.additionalContextProviders,
|
||||
);
|
||||
}
|
||||
|
||||
async llmFromTitle(title?: string): Promise<ILLM> {
|
||||
const { config } = await this.loadConfig();
|
||||
const model = config?.models.find((m) => m.title === title);
|
||||
if (!model) {
|
||||
if (title === LOCAL_ONBOARDING_PROVIDER_TITLE) {
|
||||
// Special case, make calls to Ollama before we have it in the config
|
||||
const ollama = new Ollama({
|
||||
model: LOCAL_ONBOARDING_CHAT_MODEL,
|
||||
});
|
||||
return ollama;
|
||||
} else if (config?.models?.length) {
|
||||
return config?.models[0];
|
||||
}
|
||||
|
||||
throw new Error("No model found");
|
||||
if (config.errors?.length) {
|
||||
logger.warn("Errors loading config: ", config.errors);
|
||||
}
|
||||
|
||||
return model;
|
||||
return config;
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
|
||||
if (!openProfileId) {
|
||||
return;
|
||||
}
|
||||
const profile = this.currentOrg.profiles.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Ancient method of adding custom providers through vs code
|
||||
private additionalContextProviders: IContextProvider[] = [];
|
||||
registerCustomContextProvider(contextProvider: IContextProvider) {
|
||||
this.additionalContextProviders.push(contextProvider);
|
||||
void this.reloadConfig();
|
||||
}
|
||||
/**
|
||||
* Retrieves the titles of additional context providers that are of type "submenu".
|
||||
*
|
||||
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
|
||||
*/
|
||||
getAdditionalSubmenuContextProviders(): string[] {
|
||||
return this.additionalContextProviders
|
||||
.filter((provider) => provider.description.type === "submenu")
|
||||
.map((provider) => provider.description.title);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,16 @@ export interface OrganizationDescription {
|
|||
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
|
||||
}
|
||||
|
||||
export type OrgWithProfiles = OrganizationDescription & {
|
||||
profiles: ProfileLifecycleManager[];
|
||||
currentProfile: ProfileLifecycleManager | null;
|
||||
};
|
||||
|
||||
export type SerializedOrgWithProfiles = OrganizationDescription & {
|
||||
profiles: ProfileDescription[];
|
||||
selectedProfileId: string | null;
|
||||
};
|
||||
|
||||
export class ProfileLifecycleManager {
|
||||
private savedConfigResult: ConfigResult<ContinueConfig> | undefined;
|
||||
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
|
|
@ -85,7 +95,10 @@ export class ProfileLifecycleManager {
|
|||
try {
|
||||
result = await this.profileLoader.doLoadConfig();
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "Error loading config";
|
||||
const message =
|
||||
e instanceof Error
|
||||
? `${e.message}\n${e.stack ? e.stack : ""}`
|
||||
: "Error loading config";
|
||||
result = {
|
||||
errors: [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,26 +0,0 @@
|
|||
import { IDE } from "..";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
|
||||
|
||||
export async function getSystemPromptDotFile(ide: IDE): Promise<string | null> {
|
||||
const dirs = await ide.getWorkspaceDirs();
|
||||
|
||||
let prompts: string[] = [];
|
||||
for (const dir of dirs) {
|
||||
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
|
||||
if (await ide.fileExists(dotFile)) {
|
||||
try {
|
||||
const content = await ide.readFile(dotFile);
|
||||
prompts.push(content);
|
||||
} catch (e) {
|
||||
// ignore if file doesn't exist
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!prompts.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return prompts.join("\n\n");
|
||||
}
|
||||
32
core/config/getWorkspaceContinueRuleDotFiles.ts
Normal file
32
core/config/getWorkspaceContinueRuleDotFiles.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { ConfigValidationError } from "@continuedev/config-yaml";
|
||||
import { IDE, RuleWithSource } from "..";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
|
||||
|
||||
export async function getWorkspaceContinueRuleDotFiles(ide: IDE) {
|
||||
const dirs = await ide.getWorkspaceDirs();
|
||||
|
||||
const errors: ConfigValidationError[] = [];
|
||||
const rules: RuleWithSource[] = [];
|
||||
for (const dir of dirs) {
|
||||
try {
|
||||
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
|
||||
const exists = await ide.fileExists(dotFile);
|
||||
if (exists) {
|
||||
const content = await ide.readFile(dotFile);
|
||||
rules.push({
|
||||
rule: content,
|
||||
ruleFile: dotFile,
|
||||
source: ".continuerules",
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Failed to load system prompt dot file from workspace ${dir}: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { rules, errors };
|
||||
}
|
||||
|
|
@ -8,7 +8,6 @@ import {
|
|||
ConfigValidationError,
|
||||
ModelRole,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import * as JSONC from "comment-json";
|
||||
import * as tar from "tar";
|
||||
|
||||
|
|
@ -19,7 +18,6 @@ import {
|
|||
ContinueConfig,
|
||||
ContinueRcJson,
|
||||
CustomContextProvider,
|
||||
CustomLLM,
|
||||
EmbeddingsProviderDescription,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
|
|
@ -27,6 +25,7 @@ import {
|
|||
IdeSettings,
|
||||
IdeType,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
LLMOptions,
|
||||
ModelDescription,
|
||||
RerankerDescription,
|
||||
|
|
@ -37,17 +36,15 @@ import {
|
|||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
} from "../commands/index";
|
||||
import { AllRerankers } from "../context/allRerankers";
|
||||
import { MCPManagerSingleton } from "../context/mcp";
|
||||
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import FileContextProvider from "../context/providers/FileContextProvider";
|
||||
import { contextProviderClassFromName } from "../context/providers/index";
|
||||
import { useHub } from "../control-plane/env";
|
||||
import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
|
||||
import { BaseLLM } from "../llm";
|
||||
import { llmFromDescription } from "../llm/llms";
|
||||
import { LLMClasses, llmFromDescription } from "../llm/llms";
|
||||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
import { LLMReranker } from "../llm/llms/llm";
|
||||
|
|
@ -70,9 +67,12 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util";
|
||||
import {
|
||||
getModelByRole,
|
||||
isSupportedLanceDbCpuTargetForLinux,
|
||||
serializePromptTemplates,
|
||||
} from "./util";
|
||||
import { validateConfig } from "./validation.js";
|
||||
|
||||
export function resolveSerializedConfig(
|
||||
|
|
@ -203,12 +203,6 @@ async function serializedToIntermediateConfig(
|
|||
return config;
|
||||
}
|
||||
|
||||
function isModelDescription(
|
||||
llm: ModelDescription | CustomLLM,
|
||||
): llm is ModelDescription {
|
||||
return (llm as ModelDescription).title !== undefined;
|
||||
}
|
||||
|
||||
export function isContextProviderWithParams(
|
||||
contextProvider: CustomContextProvider | ContextProviderWithParams,
|
||||
): contextProvider is ContextProviderWithParams {
|
||||
|
|
@ -216,92 +210,106 @@ export function isContextProviderWithParams(
|
|||
}
|
||||
|
||||
/** Only difference between intermediate and final configs is the `models` array */
|
||||
async function intermediateToFinalConfig(
|
||||
config: Config,
|
||||
ide: IDE,
|
||||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
workOsAccessToken: string | undefined,
|
||||
loadPromptFiles: boolean = true,
|
||||
allowFreeTrial: boolean = true,
|
||||
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
async function intermediateToFinalConfig({
|
||||
config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
loadPromptFiles = true,
|
||||
allowFreeTrial = true,
|
||||
}: {
|
||||
config: Config;
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
loadPromptFiles?: boolean;
|
||||
allowFreeTrial?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
// Auto-detect models
|
||||
let models: BaseLLM[] = [];
|
||||
for (const desc of config.models) {
|
||||
if (isModelDescription(desc)) {
|
||||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
config.completionOptions,
|
||||
config.systemMessage,
|
||||
);
|
||||
if (!llm) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const detectedModels = await Promise.all(
|
||||
modelNames.map(async (modelName) => {
|
||||
return await llmFromDescription(
|
||||
{
|
||||
...desc,
|
||||
model: modelName,
|
||||
title: modelName,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
copyOf(config.completionOptions),
|
||||
config.systemMessage,
|
||||
);
|
||||
}),
|
||||
);
|
||||
models.push(
|
||||
...(detectedModels.filter(
|
||||
(x) => typeof x !== "undefined",
|
||||
) as BaseLLM[]),
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
await Promise.all(
|
||||
config.models.map(async (desc) => {
|
||||
if ("title" in desc) {
|
||||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
);
|
||||
if (!llm) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
models.push(llm);
|
||||
}
|
||||
} else {
|
||||
const llm = new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, writeLog } as any,
|
||||
});
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const models = modelNames.map(
|
||||
(modelName) =>
|
||||
new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, model: modelName, writeLog },
|
||||
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const detectedModels = await Promise.all(
|
||||
modelNames.map(async (modelName) => {
|
||||
return await llmFromDescription(
|
||||
{
|
||||
...desc,
|
||||
model: modelName,
|
||||
title: modelName,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
copyOf(config.completionOptions),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
models.push(...models);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
);
|
||||
models.push(
|
||||
...(detectedModels.filter(
|
||||
(x) => typeof x !== "undefined",
|
||||
) as BaseLLM[]),
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
}
|
||||
} else {
|
||||
models.push(llm);
|
||||
}
|
||||
} else {
|
||||
models.push(llm);
|
||||
const llm = new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, logger: llmLogger } as any,
|
||||
});
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const models = modelNames.map(
|
||||
(modelName) =>
|
||||
new CustomLLMClass({
|
||||
...desc,
|
||||
options: {
|
||||
...desc.options,
|
||||
model: modelName,
|
||||
logger: llmLogger,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
models.push(...models);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
}
|
||||
} else {
|
||||
models.push(llm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Prepare models
|
||||
for (const model of models) {
|
||||
|
|
@ -337,15 +345,14 @@ async function intermediateToFinalConfig(
|
|||
? config.tabAutocompleteModel
|
||||
: [config.tabAutocompleteModel]
|
||||
).map(async (desc) => {
|
||||
if (isModelDescription(desc)) {
|
||||
if ("title" in desc) {
|
||||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
config.systemMessage,
|
||||
);
|
||||
|
||||
if (llm?.providerName === "free-trial") {
|
||||
|
|
@ -420,38 +427,32 @@ async function intermediateToFinalConfig(
|
|||
function getEmbeddingsILLM(
|
||||
embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
|
||||
): ILLM | null {
|
||||
if (!embedConfig) {
|
||||
return null;
|
||||
}
|
||||
if ("providerName" in embedConfig) {
|
||||
return embedConfig;
|
||||
}
|
||||
const { provider, ...options } = embedConfig;
|
||||
const embeddingsProviderClass = allEmbeddingsProviders[provider];
|
||||
if (embeddingsProviderClass) {
|
||||
if (
|
||||
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
|
||||
) {
|
||||
return new embeddingsProviderClass();
|
||||
} else {
|
||||
const llmOptions: LLMOptions = {
|
||||
model: options.model ?? "UNSPECIFIED",
|
||||
...options,
|
||||
};
|
||||
return new embeddingsProviderClass(
|
||||
llmOptions,
|
||||
(url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...config.requestOptions,
|
||||
...options.requestOptions,
|
||||
}),
|
||||
);
|
||||
if (embedConfig) {
|
||||
// config.ts-injected ILLM
|
||||
if ("providerName" in embedConfig) {
|
||||
return embedConfig;
|
||||
}
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Embeddings provider ${provider} not found. Using default`,
|
||||
});
|
||||
const { provider, ...options } = embedConfig;
|
||||
if (provider === "transformers.js") {
|
||||
return new TransformersJsEmbeddingsProvider();
|
||||
} else {
|
||||
const cls = LLMClasses.find((c) => c.providerName === provider);
|
||||
if (cls) {
|
||||
const llmOptions: LLMOptions = {
|
||||
model: options.model ?? "UNSPECIFIED",
|
||||
...options,
|
||||
};
|
||||
return new cls(llmOptions);
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Embeddings provider ${provider} not found`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ideInfo.ideType === "vscode") {
|
||||
return new TransformersJsEmbeddingsProvider();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -464,11 +465,11 @@ async function intermediateToFinalConfig(
|
|||
if (!rerankingConfig) {
|
||||
return null;
|
||||
}
|
||||
// config.ts-injected ILLM
|
||||
if ("providerName" in rerankingConfig) {
|
||||
return rerankingConfig;
|
||||
}
|
||||
const { name, params } = config.reranker as RerankerDescription;
|
||||
const rerankerClass = AllRerankers[name];
|
||||
|
||||
if (name === "llm") {
|
||||
const llm = models.find((model) => model.title === params?.modelTitle);
|
||||
|
|
@ -481,16 +482,20 @@ async function intermediateToFinalConfig(
|
|||
} else {
|
||||
return new LLMReranker(llm);
|
||||
}
|
||||
} else if (rerankerClass) {
|
||||
const llmOptions: LLMOptions = {
|
||||
model: "rerank-2",
|
||||
...params,
|
||||
};
|
||||
return new rerankerClass(llmOptions, (url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...params?.requestOptions,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
const cls = LLMClasses.find((c) => c.providerName === name);
|
||||
if (cls) {
|
||||
const llmOptions: LLMOptions = {
|
||||
model: params?.model ?? "UNSPECIFIED",
|
||||
...params,
|
||||
};
|
||||
return new cls(llmOptions);
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Unknown reranking provider ${name}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -499,7 +504,6 @@ async function intermediateToFinalConfig(
|
|||
const continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
models,
|
||||
tools: [...allTools],
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: config.slashCommands ?? [],
|
||||
|
|
@ -521,8 +525,16 @@ async function intermediateToFinalConfig(
|
|||
rerank: newReranker ?? null,
|
||||
summarize: null, // Not implemented
|
||||
},
|
||||
rules: [],
|
||||
};
|
||||
|
||||
if (config.systemMessage) {
|
||||
continueConfig.rules.unshift({
|
||||
rule: config.systemMessage,
|
||||
source: "json-systemMessage",
|
||||
});
|
||||
}
|
||||
|
||||
// Trigger MCP server refreshes (Config is reloaded again once connected!)
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.setConnections(
|
||||
|
|
@ -539,7 +551,7 @@ async function intermediateToFinalConfig(
|
|||
// Handle experimental modelRole config values for apply and edit
|
||||
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
|
||||
if (inlineEditModel) {
|
||||
const match = continueConfig.models.find(
|
||||
const match = continueConfig.modelsByRole.chat.find(
|
||||
(m) => m.title === inlineEditModel,
|
||||
);
|
||||
if (match) {
|
||||
|
|
@ -558,7 +570,7 @@ async function intermediateToFinalConfig(
|
|||
"applyCodeBlock",
|
||||
)?.title;
|
||||
if (applyBlockModel) {
|
||||
const match = continueConfig.models.find(
|
||||
const match = continueConfig.modelsByRole.chat.find(
|
||||
(m) => m.title === applyBlockModel,
|
||||
);
|
||||
if (match) {
|
||||
|
|
@ -597,11 +609,12 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
contextLength: llm.contextLength,
|
||||
template: llm.template,
|
||||
completionOptions: llm.completionOptions,
|
||||
systemMessage: llm.systemMessage,
|
||||
baseChatSystemMessage: llm.baseChatSystemMessage,
|
||||
requestOptions: llm.requestOptions,
|
||||
promptTemplates: llm.promptTemplates as any,
|
||||
promptTemplates: serializePromptTemplates(llm.promptTemplates),
|
||||
capabilities: llm.capabilities,
|
||||
roles: llm.roles,
|
||||
configurationStatus: llm.getConfigurationStatus(),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -611,8 +624,6 @@ async function finalToBrowserConfig(
|
|||
): Promise<BrowserSerializedContinueConfig> {
|
||||
return {
|
||||
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
|
||||
models: final.models.map(llmToSerializedModelDescription),
|
||||
systemMessage: final.systemMessage,
|
||||
completionOptions: final.completionOptions,
|
||||
slashCommands: final.slashCommands?.map(
|
||||
({ run, ...slashCommandDescription }) => slashCommandDescription,
|
||||
|
|
@ -831,7 +842,7 @@ async function loadContinueConfigFromJson(
|
|||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
llmLogger: ILLMLogger,
|
||||
workOsAccessToken: string | undefined,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
|
|
@ -852,11 +863,6 @@ async function loadContinueConfigFromJson(
|
|||
return { errors, config: undefined, configLoadInterrupted: true };
|
||||
}
|
||||
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
if (systemPromptDotFile) {
|
||||
serialized.systemMessage = systemPromptDotFile;
|
||||
}
|
||||
|
||||
// Apply shared config
|
||||
// TODO: override several of these values with user/org shared config
|
||||
const sharedConfig = new GlobalContext().getSharedConfig();
|
||||
|
|
@ -925,15 +931,15 @@ async function loadContinueConfigFromJson(
|
|||
|
||||
// Convert to final config format
|
||||
const { config: finalConfig, errors: finalErrors } =
|
||||
await intermediateToFinalConfig(
|
||||
intermediate,
|
||||
await intermediateToFinalConfig({
|
||||
config: intermediate,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
);
|
||||
});
|
||||
return {
|
||||
config: finalConfig,
|
||||
errors: [...(errors ?? []), ...finalErrors],
|
||||
|
|
|
|||
|
|
@ -5,11 +5,12 @@ import {
|
|||
DEFAULT_IGNORE_FILETYPES,
|
||||
} from "../indexing/ignore";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { getGlobalAssistantsPath } from "../util/paths";
|
||||
import { getGlobalFolderWithName } from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
export const ASSISTANTS_FOLDER = ".continue/assistants";
|
||||
export const ASSISTANTS = "assistants";
|
||||
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
|
||||
|
||||
export function isLocalAssistantFile(uri: string): boolean {
|
||||
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
|
||||
|
|
@ -20,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean {
|
|||
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
|
||||
}
|
||||
|
||||
export async function getAssistantFilesFromDir(
|
||||
export async function listYamlFilesInDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
|
|
@ -53,21 +54,56 @@ export async function getAssistantFilesFromDir(
|
|||
}
|
||||
}
|
||||
|
||||
export async function getAllAssistantFiles(
|
||||
export interface LoadAssistantFilesOptions {
|
||||
includeGlobal: boolean;
|
||||
includeWorkspace: boolean;
|
||||
}
|
||||
|
||||
export function getDotContinueSubDirs(
|
||||
ide: IDE,
|
||||
options: LoadAssistantFilesOptions,
|
||||
workspaceDirs: string[],
|
||||
subDirName: string,
|
||||
): string[] {
|
||||
let fullDirs: string[] = [];
|
||||
|
||||
// Workspace .continue/<subDirName>
|
||||
if (options.includeWorkspace) {
|
||||
fullDirs = workspaceDirs.map((dir) =>
|
||||
joinPathsToUri(dir, ".continue", subDirName),
|
||||
);
|
||||
}
|
||||
|
||||
// ~/.continue/<subDirName>
|
||||
if (options.includeGlobal) {
|
||||
fullDirs.push(localPathToUri(getGlobalFolderWithName(subDirName)));
|
||||
}
|
||||
|
||||
return fullDirs;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method searches in both ~/.continue and workspace .continue
|
||||
* for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
|
||||
*/
|
||||
export async function getAllDotContinueYamlFiles(
|
||||
ide: IDE,
|
||||
options: LoadAssistantFilesOptions,
|
||||
subDirName: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let assistantFiles: { path: string; content: string }[] = [];
|
||||
|
||||
let dirsToCheck = [ASSISTANTS_FOLDER];
|
||||
const fullDirs = workspaceDirs
|
||||
.map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
|
||||
.flat();
|
||||
// Get all directories to check for assistant files
|
||||
const fullDirs = getDotContinueSubDirs(
|
||||
ide,
|
||||
options,
|
||||
workspaceDirs,
|
||||
subDirName,
|
||||
);
|
||||
|
||||
fullDirs.push(localPathToUri(getGlobalAssistantsPath()));
|
||||
|
||||
assistantFiles = (
|
||||
await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir)))
|
||||
// Get all assistant files from the directories
|
||||
const assistantFiles = (
|
||||
await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
|
||||
).flat();
|
||||
|
||||
return await Promise.all(
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
/**
|
||||
* I'm disabling this rule for the entire file under the assumption
|
||||
* that this is a one-time migration script. I'm expecting this
|
||||
* code to be removed in the future.
|
||||
*/
|
||||
/* eslint-disable max-statements */
|
||||
|
||||
import { IDE } from "..";
|
||||
import { deduplicateArray } from "../util";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
|
|
|
|||
|
|
@ -1,79 +0,0 @@
|
|||
import { ConfigJson } from "@continuedev/config-types";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { PRODUCTION_ENV } from "../../control-plane/env.js";
|
||||
import {
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
SerializedContinueConfig,
|
||||
} from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
export default class ControlPlaneProfileLoader implements IProfileLoader {
|
||||
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
|
||||
|
||||
description: ProfileDescription;
|
||||
|
||||
workspaceSettings: ConfigJson | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly workspaceId: string,
|
||||
private workspaceTitle: string,
|
||||
private readonly controlPlaneClient: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
private readonly onReload: () => void,
|
||||
) {
|
||||
this.description = {
|
||||
id: workspaceId,
|
||||
profileType: "control-plane",
|
||||
iconUrl: "",
|
||||
fullSlug: {
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
title: workspaceTitle,
|
||||
errors: undefined,
|
||||
uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`,
|
||||
};
|
||||
|
||||
setInterval(async () => {
|
||||
this.workspaceSettings =
|
||||
await this.controlPlaneClient.getSettingsForWorkspace(
|
||||
this.description.id,
|
||||
);
|
||||
this.onReload();
|
||||
}, ControlPlaneProfileLoader.RELOAD_INTERVAL);
|
||||
}
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
const settings =
|
||||
this.workspaceSettings ??
|
||||
((await this.controlPlaneClient.getSettingsForWorkspace(
|
||||
this.description.id,
|
||||
)) as any);
|
||||
const serializedConfig: SerializedContinueConfig = settings;
|
||||
|
||||
return await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
serializedConfig,
|
||||
undefined,
|
||||
undefined,
|
||||
this.workspaceId,
|
||||
undefined,
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
setIsActive(isActive: boolean): void {}
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import { getPrimaryConfigFilePath } from "../../util/paths.js";
|
||||
|
|
@ -17,7 +17,7 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
private ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
private llmLogger: ILLMLogger,
|
||||
private overrideAssistantFile?:
|
||||
| { path: string; content: string }
|
||||
| undefined,
|
||||
|
|
@ -55,18 +55,20 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
description: ProfileDescription;
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
const result = await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
this.description.id,
|
||||
this.overrideAssistantFile?.path,
|
||||
null,
|
||||
);
|
||||
const result = await doLoadConfig({
|
||||
ide: this.ide,
|
||||
ideSettingsPromise: this.ideSettingsPromise,
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
llmLogger: this.llmLogger,
|
||||
profileId: this.description.id,
|
||||
overrideConfigYamlByPath: this.overrideAssistantFile?.path,
|
||||
orgScopeId: null,
|
||||
packageIdentifier: {
|
||||
uriType: "file",
|
||||
filePath:
|
||||
this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
|
||||
},
|
||||
});
|
||||
|
||||
this.description.errors = result.errors;
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
|
|||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
|
|
@ -21,33 +21,81 @@ export interface PlatformConfigMetadata {
|
|||
export default class PlatformProfileLoader implements IProfileLoader {
|
||||
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
|
||||
|
||||
private constructor(
|
||||
private configResult: ConfigResult<AssistantUnrolled>,
|
||||
private readonly ownerSlug: string,
|
||||
private readonly packageSlug: string,
|
||||
private readonly iconUrl: string,
|
||||
private readonly versionSlug: string,
|
||||
private readonly controlPlaneClient: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
readonly description: ProfileDescription,
|
||||
private readonly orgScopeId: string | null,
|
||||
) {}
|
||||
private configResult: ConfigResult<AssistantUnrolled>;
|
||||
private readonly ownerSlug: string;
|
||||
private readonly packageSlug: string;
|
||||
private readonly iconUrl: string;
|
||||
private readonly versionSlug: string;
|
||||
private readonly controlPlaneClient: ControlPlaneClient;
|
||||
private readonly ide: IDE;
|
||||
private ideSettingsPromise: Promise<IdeSettings>;
|
||||
private llmLogger: ILLMLogger;
|
||||
readonly description: ProfileDescription;
|
||||
private readonly orgScopeId: string | null;
|
||||
|
||||
static async create(
|
||||
configResult: ConfigResult<AssistantUnrolled>,
|
||||
ownerSlug: string,
|
||||
packageSlug: string,
|
||||
iconUrl: string,
|
||||
versionSlug: string,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
ide: IDE,
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
writeLog: (message: string) => Promise<void>,
|
||||
rawYaml: string,
|
||||
orgScopeId: string | null,
|
||||
): Promise<PlatformProfileLoader> {
|
||||
private constructor({
|
||||
configResult,
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
iconUrl,
|
||||
versionSlug,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
llmLogger,
|
||||
description,
|
||||
orgScopeId,
|
||||
}: {
|
||||
configResult: ConfigResult<AssistantUnrolled>;
|
||||
ownerSlug: string;
|
||||
packageSlug: string;
|
||||
iconUrl: string;
|
||||
versionSlug: string;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
ide: IDE;
|
||||
ideSettingsPromise: Promise<IdeSettings>;
|
||||
llmLogger: ILLMLogger;
|
||||
description: ProfileDescription;
|
||||
orgScopeId: string | null;
|
||||
}) {
|
||||
this.configResult = configResult;
|
||||
this.ownerSlug = ownerSlug;
|
||||
this.packageSlug = packageSlug;
|
||||
this.iconUrl = iconUrl;
|
||||
this.versionSlug = versionSlug;
|
||||
this.controlPlaneClient = controlPlaneClient;
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
this.llmLogger = llmLogger;
|
||||
this.description = description;
|
||||
this.orgScopeId = orgScopeId;
|
||||
}
|
||||
|
||||
static async create({
|
||||
configResult,
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
iconUrl,
|
||||
versionSlug,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
llmLogger,
|
||||
rawYaml,
|
||||
orgScopeId,
|
||||
}: {
|
||||
configResult: ConfigResult<AssistantUnrolled>;
|
||||
ownerSlug: string;
|
||||
packageSlug: string;
|
||||
iconUrl: string;
|
||||
versionSlug: string;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
ide: IDE;
|
||||
ideSettingsPromise: Promise<IdeSettings>;
|
||||
llmLogger: ILLMLogger;
|
||||
rawYaml: string;
|
||||
orgScopeId: string | null;
|
||||
}): Promise<PlatformProfileLoader> {
|
||||
const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
|
||||
|
||||
const description: ProfileDescription = {
|
||||
|
|
@ -65,7 +113,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
rawYaml,
|
||||
};
|
||||
|
||||
return new PlatformProfileLoader(
|
||||
return new PlatformProfileLoader({
|
||||
configResult,
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
|
|
@ -74,10 +122,10 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
controlPlaneClient,
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
description,
|
||||
orgScopeId,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
|
|
@ -89,21 +137,23 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
};
|
||||
}
|
||||
|
||||
const results = await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
undefined,
|
||||
this.configResult.config,
|
||||
{
|
||||
ownerSlug: this.ownerSlug,
|
||||
packageSlug: this.packageSlug,
|
||||
const results = await doLoadConfig({
|
||||
ide: this.ide,
|
||||
ideSettingsPromise: this.ideSettingsPromise,
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
llmLogger: this.llmLogger,
|
||||
overrideConfigYaml: this.configResult.config,
|
||||
profileId: this.description.id,
|
||||
orgScopeId: this.orgScopeId,
|
||||
packageIdentifier: {
|
||||
uriType: "slug",
|
||||
fullSlug: {
|
||||
ownerSlug: this.ownerSlug,
|
||||
packageSlug: this.packageSlug,
|
||||
versionSlug: this.versionSlug,
|
||||
},
|
||||
},
|
||||
this.description.id,
|
||||
undefined,
|
||||
this.orgScopeId,
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
config: results.config,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
ModelRole,
|
||||
PackageIdentifier,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
||||
import {
|
||||
|
|
@ -12,11 +13,12 @@ import {
|
|||
ContinueRcJson,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
SerializedContinueConfig,
|
||||
Tool,
|
||||
} from "../../";
|
||||
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
|
||||
import { MCPManagerSingleton } from "../../context/mcp";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import MCPContextProvider from "../../context/providers/MCPContextProvider";
|
||||
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
|
|
@ -28,25 +30,37 @@ import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
|
|||
import { localPathOrUriToPath } from "../../util/pathToUri";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { TTS } from "../../util/tts";
|
||||
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
|
||||
import { loadContinueConfigFromJson } from "../load";
|
||||
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
|
||||
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
|
||||
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
|
||||
|
||||
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
|
||||
export default async function doLoadConfig(options: {
|
||||
ide: IDE;
|
||||
ideSettingsPromise: Promise<IdeSettings>;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
llmLogger: ILLMLogger;
|
||||
overrideConfigJson?: SerializedContinueConfig;
|
||||
overrideConfigYaml?: AssistantUnrolled;
|
||||
profileId: string;
|
||||
overrideConfigYamlByPath?: string;
|
||||
orgScopeId: string | null;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<ContinueConfig>> {
|
||||
const {
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
overrideConfigJson,
|
||||
overrideConfigYaml,
|
||||
profileId,
|
||||
overrideConfigYamlByPath,
|
||||
orgScopeId,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
export default async function doLoadConfig(
|
||||
ide: IDE,
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
writeLog: (message: string) => Promise<void>,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
profileId: string,
|
||||
overrideConfigYamlByPath: string | undefined,
|
||||
orgScopeId: string | null,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const workspaceConfigs = await getWorkspaceConfigs(ide);
|
||||
const ideInfo = await ide.getIdeInfo();
|
||||
const uniqueId = await ide.getUniqueId();
|
||||
|
|
@ -69,19 +83,18 @@ export default async function doLoadConfig(
|
|||
let configLoadInterrupted = false;
|
||||
|
||||
if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
|
||||
const result = await loadContinueConfigFromYaml(
|
||||
const result = await loadContinueConfigFromYaml({
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
workOsAccessToken,
|
||||
llmLogger,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
configYamlPath,
|
||||
orgScopeId,
|
||||
);
|
||||
packageIdentifier,
|
||||
workOsAccessToken,
|
||||
});
|
||||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
configLoadInterrupted = result.configLoadInterrupted;
|
||||
|
|
@ -92,7 +105,7 @@ export default async function doLoadConfig(
|
|||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigJson,
|
||||
);
|
||||
|
|
@ -109,6 +122,12 @@ export default async function doLoadConfig(
|
|||
// Remove ability have undefined errors, just have an array
|
||||
errors = [...(errors ?? [])];
|
||||
|
||||
// Add rules from .continuerules files
|
||||
const { rules, errors: continueRulesErrors } =
|
||||
await getWorkspaceContinueRuleDotFiles(ide);
|
||||
newConfig.rules.unshift(...rules);
|
||||
errors.push(...continueRulesErrors);
|
||||
|
||||
// Rectify model selections for each role
|
||||
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
|
||||
|
||||
|
|
@ -160,6 +179,7 @@ export default async function doLoadConfig(
|
|||
const serverContextProvider = new MCPContextProvider({
|
||||
submenuItems,
|
||||
mcpId: server.id,
|
||||
serverName: server.name,
|
||||
});
|
||||
newConfig.contextProviders.push(serverContextProvider);
|
||||
}
|
||||
|
|
@ -217,13 +237,13 @@ export default async function doLoadConfig(
|
|||
};
|
||||
|
||||
if (newConfig.analytics) {
|
||||
await TeamAnalytics.setup(
|
||||
newConfig.analytics,
|
||||
uniqueId,
|
||||
ideInfo.extensionVersion,
|
||||
controlPlaneClient,
|
||||
controlPlaneProxyInfo,
|
||||
);
|
||||
// await TeamAnalytics.setup(
|
||||
// newConfig.analytics,
|
||||
// uniqueId,
|
||||
// ideInfo.extensionVersion,
|
||||
// controlPlaneClient,
|
||||
// controlPlaneProxyInfo,
|
||||
// );
|
||||
} else {
|
||||
await TeamAnalytics.shutdown();
|
||||
}
|
||||
|
|
@ -256,7 +276,7 @@ async function injectControlPlaneProxyInfo(
|
|||
}
|
||||
});
|
||||
|
||||
config.models.forEach((model) => {
|
||||
config.modelsByRole.chat.forEach((model) => {
|
||||
if (model.providerName === "continue-proxy") {
|
||||
(model as ContinueProxy).controlPlaneProxyInfo = info;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ModelRole } from "@continuedev/config-yaml";
|
||||
|
||||
import { ContinueConfig, ILLM } from "..";
|
||||
import { LLMConfigurationStatuses } from "../llm/constants";
|
||||
import {
|
||||
GlobalContext,
|
||||
GlobalContextModelSelections,
|
||||
|
|
@ -19,19 +20,20 @@ export function rectifySelectedModelsFromGlobalContext(
|
|||
|
||||
let fellBack = false;
|
||||
|
||||
// chat and summarize not implemented yet
|
||||
// default chat model is stored in GUI still
|
||||
|
||||
// summarize not implemented yet
|
||||
const roles: ModelRole[] = [
|
||||
"autocomplete",
|
||||
"apply",
|
||||
"edit",
|
||||
"embed",
|
||||
"rerank",
|
||||
"chat",
|
||||
];
|
||||
|
||||
for (const role of roles) {
|
||||
let newModel: ILLM | null = null;
|
||||
const currentSelection = currentForProfile[role] ?? null;
|
||||
|
||||
if (currentSelection) {
|
||||
const match = continueConfig.modelsByRole[role].find(
|
||||
(m) => m.title === currentSelection,
|
||||
|
|
@ -40,12 +42,23 @@ export function rectifySelectedModelsFromGlobalContext(
|
|||
newModel = match;
|
||||
}
|
||||
}
|
||||
|
||||
if (!newModel && continueConfig.modelsByRole[role].length > 0) {
|
||||
newModel = continueConfig.modelsByRole[role][0];
|
||||
}
|
||||
|
||||
if (!(currentSelection === (newModel?.title ?? null))) {
|
||||
fellBack = true;
|
||||
}
|
||||
|
||||
// Currently only check for configuration status for apply
|
||||
if (
|
||||
role === "apply" &&
|
||||
newModel?.getConfigurationStatus() !== LLMConfigurationStatuses.VALID
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
configCopy.selectedModelByRole[role] = newModel;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ declare global {
|
|||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
llmLogger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
|
|
@ -403,6 +403,7 @@ declare global {
|
|||
| "generated"
|
||||
| "calling"
|
||||
| "done"
|
||||
| "errored"
|
||||
| "canceled";
|
||||
|
||||
// Will exist only on "assistant" messages with tool calls
|
||||
|
|
@ -433,6 +434,94 @@ declare global {
|
|||
|
||||
export type ToastType = "info" | "error" | "warning";
|
||||
|
||||
export interface LLMInteractionBase {
|
||||
interactionId: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartChat extends LLMInteractionBase {
|
||||
kind: "startChat";
|
||||
messages: ChatMessage[];
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartComplete extends LLMInteractionBase {
|
||||
kind: "startComplete";
|
||||
prompt: string;
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartFim extends LLMInteractionBase {
|
||||
kind: "startFim";
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionChunk extends LLMInteractionBase {
|
||||
kind: "chunk";
|
||||
chunk: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionMessage extends LLMInteractionBase {
|
||||
kind: "message";
|
||||
message: ChatMessage;
|
||||
}
|
||||
|
||||
export interface LLMInteractionEnd extends LLMInteractionBase {
|
||||
promptTokens: number;
|
||||
generatedTokens: number;
|
||||
thinkingTokens: number;
|
||||
}
|
||||
|
||||
export interface LLMInteractionSuccess extends LLMInteractionEnd {
|
||||
kind: "success";
|
||||
}
|
||||
|
||||
export interface LLMInteractionCancel extends LLMInteractionEnd {
|
||||
kind: "cancel";
|
||||
}
|
||||
|
||||
export interface LLMInteractionError extends LLMInteractionEnd {
|
||||
kind: "error";
|
||||
name: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type LLMInteractionItem =
|
||||
| LLMInteractionStartChat
|
||||
| LLMInteractionStartComplete
|
||||
| LLMInteractionStartFim
|
||||
| LLMInteractionChunk
|
||||
| LLMInteractionMessage
|
||||
| LLMInteractionSuccess
|
||||
| LLMInteractionCancel
|
||||
| LLMInteractionError;
|
||||
|
||||
// When we log a LLM interaction, we want to add the interactionId and timestamp
|
||||
// in the logger code, so we need a type that omits these members from *each*
|
||||
// member of the union. This can be done by using the distributive behavior of
|
||||
// conditional types in Typescript.
|
||||
//
|
||||
// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
|
||||
// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s
|
||||
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
|
||||
? Omit<T, K>
|
||||
: never;
|
||||
|
||||
export type LLMInteractionItemDetails = DistributiveOmit<
|
||||
LLMInteractionItem,
|
||||
"interactionId" | "timestamp"
|
||||
>;
|
||||
|
||||
export interface ILLMInteractionLog {
|
||||
logItem(item: LLMInteractionItemDetails): void;
|
||||
}
|
||||
|
||||
export interface ILLMLogger {
|
||||
createInteractionLog(): ILLMInteractionLog;
|
||||
}
|
||||
|
||||
export interface LLMOptions {
|
||||
model: string;
|
||||
|
||||
|
|
@ -446,7 +535,7 @@ declare global {
|
|||
template?: TemplateType;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
aiGatewaySlug?: string;
|
||||
|
|
@ -570,7 +659,6 @@ declare global {
|
|||
remoteConfigServerUrl: string | undefined;
|
||||
remoteConfigSyncPeriod: number;
|
||||
userToken: string;
|
||||
enableControlServerBeta: boolean;
|
||||
pauseCodebaseIndexOnStart: boolean;
|
||||
}
|
||||
|
||||
|
|
@ -870,7 +958,7 @@ declare global {
|
|||
cacheBehavior?: CacheBehavior;
|
||||
}
|
||||
|
||||
export interface EmbedOptions {
|
||||
export interface JSONEmbedOptions {
|
||||
apiBase?: string;
|
||||
apiKey?: string;
|
||||
model?: string;
|
||||
|
|
|
|||
45
core/config/util.test.ts
Normal file
45
core/config/util.test.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { PromptTemplate } from "..";
|
||||
import { serializePromptTemplates } from "./util";
|
||||
|
||||
describe("serializePromptTemplates", () => {
|
||||
it("should return undefined for undefined input", () => {
|
||||
expect(serializePromptTemplates(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should convert function templates to empty strings", () => {
|
||||
const functionTemplate: PromptTemplate = () => "Generated template";
|
||||
const templates: Record<string, PromptTemplate> = {
|
||||
template1: functionTemplate,
|
||||
};
|
||||
|
||||
const result = serializePromptTemplates(templates);
|
||||
|
||||
expect(result).toEqual({ template1: "" });
|
||||
});
|
||||
|
||||
it("should pass through string templates unchanged", () => {
|
||||
const templates: Record<string, PromptTemplate> = {
|
||||
template1: "This is a static template",
|
||||
template2: "Another static template",
|
||||
};
|
||||
|
||||
const result = serializePromptTemplates(templates);
|
||||
|
||||
expect(result).toEqual(templates);
|
||||
});
|
||||
|
||||
it("should handle mixed template types", () => {
|
||||
const functionTemplate: PromptTemplate = () => "Generated template";
|
||||
const templates: Record<string, PromptTemplate> = {
|
||||
function: functionTemplate,
|
||||
string: "This is a static template",
|
||||
};
|
||||
|
||||
const result = serializePromptTemplates(templates);
|
||||
|
||||
expect(result).toEqual({
|
||||
function: "",
|
||||
string: "This is a static template",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,13 +1,16 @@
|
|||
import fs from "fs";
|
||||
import os from "os";
|
||||
|
||||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import {
|
||||
ContinueConfig,
|
||||
ExperimentalModelRoles,
|
||||
IDE,
|
||||
ILLM,
|
||||
ModelDescription,
|
||||
JSONModelDescription,
|
||||
PromptTemplate,
|
||||
} from "../";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigFile } from "../util/paths";
|
||||
|
||||
|
|
@ -22,16 +25,21 @@ function stringify(obj: any, indentation?: number): string {
|
|||
}
|
||||
|
||||
export function addModel(
|
||||
model: ModelDescription,
|
||||
model: JSONModelDescription,
|
||||
role?: keyof ExperimentalModelRoles,
|
||||
) {
|
||||
editConfigFile(
|
||||
(config) => {
|
||||
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
|
||||
if (config.models?.some((m) => stringify(m) === stringify(model))) {
|
||||
return config;
|
||||
}
|
||||
if (config.models?.some((m: any) => m?.title === model.title)) {
|
||||
model.title = `${model.title} (1)`;
|
||||
|
||||
const numMatches = config.models?.reduce(
|
||||
(prev, curr) => (curr.title.startsWith(model.title) ? prev + 1 : prev),
|
||||
0,
|
||||
);
|
||||
if (numMatches !== 0) {
|
||||
model.title = `${model.title} (${numMatches})`;
|
||||
}
|
||||
|
||||
config.models.push(model);
|
||||
|
|
@ -50,22 +58,34 @@ export function addModel(
|
|||
return config;
|
||||
},
|
||||
(config) => {
|
||||
if (config.models?.some((m: any) => m?.title === model.title)) {
|
||||
model.title = `${model.title} (1)`;
|
||||
const numMatches = config.models?.reduce(
|
||||
(prev, curr) =>
|
||||
"name" in curr && curr.name.startsWith(model.title) ? prev + 1 : prev,
|
||||
0,
|
||||
);
|
||||
if (numMatches !== 0) {
|
||||
model.title = `${model.title} (${numMatches})`;
|
||||
}
|
||||
|
||||
if (!config.models) {
|
||||
config.models = [];
|
||||
}
|
||||
|
||||
config.models.push({
|
||||
const desc: ModelConfig = {
|
||||
name: model.title,
|
||||
provider: model.provider,
|
||||
model: model.model,
|
||||
apiKey: model.apiKey,
|
||||
apiBase: model.apiBase,
|
||||
defaultCompletionOptions: model.completionOptions,
|
||||
});
|
||||
};
|
||||
if (model.systemMessage) {
|
||||
desc.chatOptions = {
|
||||
baseSystemMessage:
|
||||
DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage,
|
||||
};
|
||||
}
|
||||
config.models.push(desc);
|
||||
return config;
|
||||
},
|
||||
);
|
||||
|
|
@ -94,7 +114,7 @@ export function getModelByRole<T extends keyof ExperimentalModelRoles>(
|
|||
return undefined;
|
||||
}
|
||||
|
||||
const matchingModel = config.models.find(
|
||||
const matchingModel = config.modelsByRole.chat.find(
|
||||
(model) => model.title === roleTitle,
|
||||
);
|
||||
|
||||
|
|
@ -169,3 +189,22 @@ async function showUnsupportedCpuToast(ide: IDE) {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is required because users are only able to define prompt templates as a
|
||||
* string, while internally we also allow prompt templates to be functions
|
||||
* @param templates
|
||||
* @returns
|
||||
*/
|
||||
export function serializePromptTemplates(
|
||||
templates: Record<string, PromptTemplate> | undefined,
|
||||
): Record<string, string> | undefined {
|
||||
if (!templates) return undefined;
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(templates).map(([key, template]) => {
|
||||
const serialized = typeof template === "function" ? "" : template;
|
||||
return [key, serialized];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
97
core/config/workspace/workspaceBlocks.ts
Normal file
97
core/config/workspace/workspaceBlocks.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { BlockType, ConfigYaml } from "@continuedev/config-yaml";
|
||||
import * as YAML from "yaml";
|
||||
import { IDE } from "../..";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
|
||||
const configYaml: ConfigYaml = {
|
||||
name: `New ${blockType.slice(0, -1)}`,
|
||||
version: "0.0.1",
|
||||
schema: "v1",
|
||||
};
|
||||
switch (blockType) {
|
||||
case "context":
|
||||
configYaml.context = [
|
||||
{
|
||||
provider: "file",
|
||||
},
|
||||
];
|
||||
break;
|
||||
case "models":
|
||||
configYaml.models = [
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-7-sonnet-latest",
|
||||
apiKey: "${{ secrets.ANTHROPIC_API_KEY }}",
|
||||
name: "Claude 3.7 Sonnet",
|
||||
roles: ["chat", "edit"],
|
||||
},
|
||||
];
|
||||
break;
|
||||
case "rules":
|
||||
configYaml.rules = ["Always give concise responses"];
|
||||
break;
|
||||
case "docs":
|
||||
configYaml.docs = [
|
||||
{
|
||||
name: "New docs",
|
||||
startUrl: "https://docs.continue.dev",
|
||||
},
|
||||
];
|
||||
break;
|
||||
case "prompts":
|
||||
configYaml.prompts = [
|
||||
{
|
||||
name: "New prompt",
|
||||
description: "New prompt",
|
||||
prompt:
|
||||
"Please write a thorough suite of unit tests for this code, making sure to cover all relevant edge cases",
|
||||
},
|
||||
];
|
||||
break;
|
||||
case "mcpServers":
|
||||
configYaml.mcpServers = [
|
||||
{
|
||||
name: "New MCP server",
|
||||
command: "npx",
|
||||
args: ["-y", "<your-mcp-server>"],
|
||||
env: {},
|
||||
},
|
||||
];
|
||||
break;
|
||||
}
|
||||
|
||||
return configYaml;
|
||||
}
|
||||
|
||||
export async function createNewWorkspaceBlockFile(
|
||||
ide: IDE,
|
||||
blockType: BlockType,
|
||||
): Promise<void> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
if (workspaceDirs.length === 0) {
|
||||
throw new Error(
|
||||
"No workspace directories found. Make sure you've opened a folder in your IDE.",
|
||||
);
|
||||
}
|
||||
|
||||
const baseDirUri = joinPathsToUri(workspaceDirs[0], `.continue/${blockType}`);
|
||||
|
||||
// Find the first available filename
|
||||
let counter = 0;
|
||||
let fileUri: string;
|
||||
do {
|
||||
const suffix = counter === 0 ? "" : `-${counter}`;
|
||||
fileUri = joinPathsToUri(
|
||||
baseDirUri,
|
||||
`new-${blockType.slice(0, -1)}${suffix}.yaml`,
|
||||
);
|
||||
counter++;
|
||||
} while (await ide.fileExists(fileUri));
|
||||
|
||||
await ide.writeFile(
|
||||
fileUri,
|
||||
YAML.stringify(getContentsForNewBlock(blockType)),
|
||||
);
|
||||
await ide.openFile(fileUri);
|
||||
}
|
||||
106
core/config/yaml/LocalPlatformClient.ts
Normal file
106
core/config/yaml/LocalPlatformClient.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import {
|
||||
FQSN,
|
||||
PlatformClient,
|
||||
SecretResult,
|
||||
SecretType,
|
||||
} from "@continuedev/config-yaml";
|
||||
import * as dotenv from "dotenv";
|
||||
import { IDE } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { getContinueDotEnv } from "../../util/paths";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
export class LocalPlatformClient implements PlatformClient {
|
||||
constructor(
|
||||
private orgScopeId: string | null,
|
||||
private readonly client: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
) {}
|
||||
|
||||
private async findSecretInEnvFiles(
|
||||
fqsn: FQSN,
|
||||
): Promise<SecretResult | undefined> {
|
||||
const secretValue =
|
||||
this.findSecretInLocalEnvFile(fqsn) ??
|
||||
(await this.findSecretInWorkspaceEnvFiles(fqsn));
|
||||
|
||||
if (secretValue) {
|
||||
return {
|
||||
found: true,
|
||||
fqsn,
|
||||
value: secretValue,
|
||||
secretLocation: {
|
||||
secretName: fqsn.secretName,
|
||||
secretType: SecretType.LocalEnv,
|
||||
},
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private findSecretInLocalEnvFile(fqsn: FQSN): string | undefined {
|
||||
try {
|
||||
const dotEnv = getContinueDotEnv();
|
||||
return dotEnv[fqsn.secretName];
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`Error reading ~/.continue/.env file: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private async findSecretInWorkspaceEnvFiles(
|
||||
fqsn: FQSN,
|
||||
): Promise<string | undefined> {
|
||||
try {
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
|
||||
for (const folder of workspaceDirs) {
|
||||
const envFilePath = joinPathsToUri(folder, ".env");
|
||||
try {
|
||||
const fileExists = await this.ide.fileExists(envFilePath);
|
||||
if (fileExists) {
|
||||
const envContent = await this.ide.readFile(envFilePath);
|
||||
const env = dotenv.parse(envContent);
|
||||
if (fqsn.secretName in env) {
|
||||
return env[fqsn.secretName];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`Error reading workspace .env file at ${envFilePath}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
// Continue to next workspace folder
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`Error searching workspace .env files: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
|
||||
if (fqsns.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const results = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
|
||||
|
||||
// For any secret that isn't found, look in .env files
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
if (!results[i]?.found) {
|
||||
const secretFromEnv = await this.findSecretInEnvFiles(fqsns[i]);
|
||||
if (secretFromEnv?.found) {
|
||||
results[i] = secretFromEnv;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,9 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
|||
|
||||
import { SerializedContinueConfig } from "../..";
|
||||
|
||||
/*
|
||||
TODO this is not functional
|
||||
*/
|
||||
export function convertConfigJsonToConfigYaml(
|
||||
configJson: SerializedContinueConfig,
|
||||
): AssistantUnrolled {
|
||||
|
|
|
|||
|
|
@ -1,98 +1,155 @@
|
|||
import fs from "node:fs";
|
||||
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
BLOCK_TYPES,
|
||||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
FQSN,
|
||||
isAssistantUnrolledNonNullable,
|
||||
MCPServer,
|
||||
ModelRole,
|
||||
PlatformClient,
|
||||
PackageIdentifier,
|
||||
RegistryClient,
|
||||
SecretResult,
|
||||
unrollAssistantFromContent,
|
||||
Rule,
|
||||
unrollAssistant,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
ContinueConfig,
|
||||
ExperimentalMCPOptions,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
} from "../..";
|
||||
import { slashFromCustomCommand } from "../../commands";
|
||||
import { AllRerankers } from "../../context/allRerankers";
|
||||
import { MCPManagerSingleton } from "../../context/mcp";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
|
||||
import DocsContextProvider from "../../context/providers/DocsContextProvider";
|
||||
import FileContextProvider from "../../context/providers/FileContextProvider";
|
||||
import { contextProviderClassFromName } from "../../context/providers/index";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders";
|
||||
import FreeTrial from "../../llm/llms/FreeTrial";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { allTools } from "../../tools";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { getConfigYamlPath } from "../../util/paths";
|
||||
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { logger } from "../../util/logger";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
|
||||
export class LocalPlatformClient implements PlatformClient {
|
||||
constructor(
|
||||
private orgScopeId: string | null,
|
||||
private readonly client: ControlPlaneClient,
|
||||
) {}
|
||||
|
||||
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
|
||||
if (fqsns.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const response = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
|
||||
return response;
|
||||
function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
||||
if (typeof rule === "string") {
|
||||
return {
|
||||
rule: rule,
|
||||
source: "rules-block",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
source: "rules-block",
|
||||
rule: rule.rule,
|
||||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConfigYaml(
|
||||
rawYaml: string,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
orgScopeId: string | null,
|
||||
ideSettings: IdeSettings,
|
||||
): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
function convertYamlMcpToContinueMcp(
|
||||
server: MCPServer,
|
||||
): ExperimentalMCPOptions {
|
||||
return {
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: server.command,
|
||||
args: server.args ?? [],
|
||||
env: server.env,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function loadConfigYaml(options: {
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
orgScopeId: string | null;
|
||||
ideSettings: IdeSettings;
|
||||
ide: IDE;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
const {
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
ideSettings,
|
||||
ide,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
// Add local .continue blocks
|
||||
const allLocalBlocks: PackageIdentifier[] = [];
|
||||
for (const blockType of BLOCK_TYPES) {
|
||||
const localBlocks = await getAllDotContinueYamlFiles(
|
||||
ide,
|
||||
{ includeGlobal: true, includeWorkspace: true },
|
||||
blockType,
|
||||
);
|
||||
allLocalBlocks.push(
|
||||
...localBlocks.map((b) => ({
|
||||
uriType: "file" as const,
|
||||
filePath: b.path,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const rootPath =
|
||||
packageIdentifier.uriType === "file"
|
||||
? dirname(getCleanUriPath(packageIdentifier.filePath))
|
||||
: undefined;
|
||||
|
||||
logger.info(
|
||||
`Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
|
||||
);
|
||||
|
||||
let config =
|
||||
overrideConfigYaml ??
|
||||
// This is how we allow use of blocks locally
|
||||
(await unrollAssistantFromContent(
|
||||
{
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
rawYaml,
|
||||
new RegistryClient(
|
||||
await controlPlaneClient.getAccessToken(),
|
||||
getControlPlaneEnvSync(
|
||||
ideSettings.continueTestEnvironment,
|
||||
ideSettings.enableControlServerBeta,
|
||||
).CONTROL_PLANE_URL,
|
||||
),
|
||||
(await unrollAssistant(
|
||||
packageIdentifier,
|
||||
new RegistryClient({
|
||||
accessToken: await controlPlaneClient.getAccessToken(),
|
||||
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
|
||||
.CONTROL_PLANE_URL,
|
||||
rootPath,
|
||||
}),
|
||||
{
|
||||
currentUserSlug: "",
|
||||
onPremProxyUrl: null,
|
||||
orgScopeId,
|
||||
platformClient: new LocalPlatformClient(orgScopeId, controlPlaneClient),
|
||||
platformClient: new LocalPlatformClient(
|
||||
orgScopeId,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
),
|
||||
renderSecrets: true,
|
||||
injectBlocks: allLocalBlocks,
|
||||
},
|
||||
));
|
||||
const errors = validateConfigYaml(config);
|
||||
|
||||
const errors = isAssistantUnrolledNonNullable(config)
|
||||
? validateConfigYaml(config)
|
||||
: [
|
||||
{
|
||||
fatal: true,
|
||||
message: "Assistant includes blocks that don't exist",
|
||||
},
|
||||
];
|
||||
|
||||
if (errors?.some((error) => error.fatal)) {
|
||||
return {
|
||||
|
|
@ -110,41 +167,33 @@ async function loadConfigYaml(
|
|||
};
|
||||
}
|
||||
|
||||
async function configYamlToContinueConfig(
|
||||
config: AssistantUnrolled,
|
||||
ide: IDE,
|
||||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
workOsAccessToken: string | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
allowFreeTrial: boolean = true,
|
||||
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
async function configYamlToContinueConfig(options: {
|
||||
config: AssistantUnrolled;
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
allowFreeTrial?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
let {
|
||||
config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
allowFreeTrial,
|
||||
} = options;
|
||||
allowFreeTrial = allowFreeTrial ?? true;
|
||||
|
||||
const localErrors: ConfigValidationError[] = [];
|
||||
|
||||
const continueConfig: ContinueConfig = {
|
||||
slashCommands: [],
|
||||
models: [],
|
||||
tools: [...allTools],
|
||||
mcpServerStatuses: [],
|
||||
systemMessage: config.rules?.join("\n"),
|
||||
experimental: {
|
||||
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: mcpServer.command,
|
||||
args: mcpServer.args ?? [],
|
||||
env: mcpServer.env,
|
||||
},
|
||||
})),
|
||||
},
|
||||
docs: config.docs?.map((doc) => ({
|
||||
title: doc.name,
|
||||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
})),
|
||||
rules: config.rules,
|
||||
contextProviders: [],
|
||||
modelsByRole: {
|
||||
chat: [],
|
||||
|
|
@ -156,7 +205,7 @@ async function configYamlToContinueConfig(
|
|||
summarize: [],
|
||||
},
|
||||
selectedModelByRole: {
|
||||
chat: null, // not currently used - defaultModel on GUI is used
|
||||
chat: null,
|
||||
edit: null, // not currently used
|
||||
apply: null,
|
||||
embed: null,
|
||||
|
|
@ -164,14 +213,44 @@ async function configYamlToContinueConfig(
|
|||
rerank: null,
|
||||
summarize: null,
|
||||
},
|
||||
data: config.data,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
// Right now, if there are any missing packages in the config, then we will just throw an error
|
||||
if (!isAssistantUnrolledNonNullable(config)) {
|
||||
return {
|
||||
config: continueConfig,
|
||||
errors: [
|
||||
{
|
||||
message: "Found missing blocks in config.yaml",
|
||||
fatal: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
for (const rule of config.rules ?? []) {
|
||||
continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
|
||||
}
|
||||
|
||||
continueConfig.data = config.data;
|
||||
continueConfig.docs = config.docs?.map((doc) => ({
|
||||
title: doc.name,
|
||||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
}));
|
||||
continueConfig.experimental = {
|
||||
modelContextProtocolServers: config.mcpServers?.map(
|
||||
convertYamlMcpToContinueMcp,
|
||||
),
|
||||
};
|
||||
|
||||
// Prompt files -
|
||||
try {
|
||||
const promptFiles = await getAllPromptFiles(ide, undefined, true);
|
||||
|
||||
for (const file of promptFiles) {
|
||||
promptFiles.forEach((file) => {
|
||||
try {
|
||||
const slashCommand = slashCommandFromPromptFileV1(
|
||||
file.path,
|
||||
|
|
@ -186,7 +265,7 @@ async function configYamlToContinueConfig(
|
|||
message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
|
|
@ -207,23 +286,18 @@ async function configYamlToContinueConfig(
|
|||
});
|
||||
|
||||
// Models
|
||||
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
|
||||
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
|
||||
for (const model of config.models ?? []) {
|
||||
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
|
||||
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
|
||||
try {
|
||||
const llms = await llmsFromModelConfig(
|
||||
const llms = await llmsFromModelConfig({
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
continueConfig.systemMessage,
|
||||
);
|
||||
|
||||
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
|
||||
continueConfig.models.push(...llms);
|
||||
}
|
||||
llmLogger,
|
||||
config: continueConfig,
|
||||
});
|
||||
|
||||
if (model.roles?.includes("chat")) {
|
||||
continueConfig.modelsByRole.chat.push(...llms);
|
||||
|
|
@ -246,59 +320,25 @@ async function configYamlToContinueConfig(
|
|||
}
|
||||
|
||||
if (model.roles?.includes("embed")) {
|
||||
const { provider, ...options } = model;
|
||||
const embeddingsProviderClass = allEmbeddingsProviders[provider];
|
||||
if (embeddingsProviderClass) {
|
||||
if (
|
||||
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
|
||||
) {
|
||||
const { provider } = model;
|
||||
if (provider === "transformers.js") {
|
||||
if (ideInfo.ideType === "vscode") {
|
||||
continueConfig.modelsByRole.embed.push(
|
||||
new embeddingsProviderClass(),
|
||||
new TransformersJsEmbeddingsProvider(),
|
||||
);
|
||||
} else {
|
||||
continueConfig.modelsByRole.embed.push(
|
||||
new embeddingsProviderClass(
|
||||
{
|
||||
...options,
|
||||
title: options.name,
|
||||
},
|
||||
(url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
}),
|
||||
),
|
||||
);
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Transformers.js embeddings provider not supported in this IDE.`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Unsupported embeddings model provider found: ${provider}`,
|
||||
});
|
||||
continueConfig.modelsByRole.embed.push(...llms);
|
||||
}
|
||||
}
|
||||
|
||||
if (model.roles?.includes("rerank")) {
|
||||
const { provider, ...options } = model;
|
||||
const rerankerClass = AllRerankers[provider];
|
||||
if (rerankerClass) {
|
||||
continueConfig.modelsByRole.rerank.push(
|
||||
new rerankerClass(
|
||||
{
|
||||
...options,
|
||||
title: options.name,
|
||||
},
|
||||
(url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
}),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Unsupported reranking model provider found: ${provider}`,
|
||||
});
|
||||
}
|
||||
continueConfig.modelsByRole.rerank.push(...llms);
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
|
|
@ -322,7 +362,7 @@ async function configYamlToContinueConfig(
|
|||
|
||||
if (allowFreeTrial) {
|
||||
// Obtain auth token (iff free trial being used)
|
||||
const freeTrialModels = continueConfig.models.filter(
|
||||
const freeTrialModels = continueConfig.modelsByRole.chat.filter(
|
||||
(model) => model.providerName === "free-trial",
|
||||
);
|
||||
if (freeTrialModels.length > 0) {
|
||||
|
|
@ -337,14 +377,15 @@ async function configYamlToContinueConfig(
|
|||
message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
// Remove free trial models
|
||||
continueConfig.models = continueConfig.models.filter(
|
||||
(model) => model.providerName !== "free-trial",
|
||||
);
|
||||
continueConfig.modelsByRole.chat =
|
||||
continueConfig.modelsByRole.chat.filter(
|
||||
(model) => model.providerName !== "free-trial",
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Remove free trial models
|
||||
continueConfig.models = continueConfig.models.filter(
|
||||
continueConfig.modelsByRole.chat = continueConfig.modelsByRole.chat.filter(
|
||||
(model) => model.providerName !== "free-trial",
|
||||
);
|
||||
}
|
||||
|
|
@ -374,7 +415,10 @@ async function configYamlToContinueConfig(
|
|||
}
|
||||
return undefined;
|
||||
}
|
||||
const instance: IContextProvider = new cls(context.params ?? {});
|
||||
const instance: IContextProvider = new cls({
|
||||
name: context.name,
|
||||
...context.params,
|
||||
});
|
||||
return instance;
|
||||
})
|
||||
.filter((p) => !!p) ?? []) as IContextProvider[];
|
||||
|
|
@ -407,34 +451,39 @@ async function configYamlToContinueConfig(
|
|||
return { config: continueConfig, errors: localErrors };
|
||||
}
|
||||
|
||||
export async function loadContinueConfigFromYaml(
|
||||
ide: IDE,
|
||||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
workOsAccessToken: string | undefined,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
configYamlPath: string | undefined,
|
||||
orgScopeId: string | null,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const rawYaml =
|
||||
overrideConfigYaml === undefined
|
||||
? fs.readFileSync(
|
||||
configYamlPath ?? getConfigYamlPath(ideInfo.ideType),
|
||||
"utf-8",
|
||||
)
|
||||
: "";
|
||||
export async function loadContinueConfigFromYaml(options: {
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
orgScopeId: string | null;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<ContinueConfig>> {
|
||||
const {
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
const configYamlResult = await loadConfigYaml(
|
||||
rawYaml,
|
||||
const configYamlResult = await loadConfigYaml({
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
ideSettings,
|
||||
);
|
||||
ide,
|
||||
packageIdentifier,
|
||||
});
|
||||
|
||||
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
|
||||
return {
|
||||
|
|
@ -445,32 +494,15 @@ export async function loadContinueConfigFromYaml(
|
|||
}
|
||||
|
||||
const { config: continueConfig, errors: localErrors } =
|
||||
await configYamlToContinueConfig(
|
||||
configYamlResult.config,
|
||||
await configYamlToContinueConfig({
|
||||
config: configYamlResult.config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
platformConfigMetadata,
|
||||
);
|
||||
|
||||
try {
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
if (systemPromptDotFile) {
|
||||
if (continueConfig.systemMessage) {
|
||||
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
|
||||
} else {
|
||||
continueConfig.systemMessage = systemPromptDotFile;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Apply shared config
|
||||
// TODO: override several of these values with user/org shared config
|
||||
|
|
|
|||
|
|
@ -1,9 +1,14 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
|
||||
import { IDE, IdeSettings, LLMOptions } from "../..";
|
||||
import {
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
LLMOptions,
|
||||
} from "../..";
|
||||
import { BaseLLM } from "../../llm";
|
||||
import { LLMClasses } from "../../llm/llms";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
|
||||
const AUTODETECT = "AUTODETECT";
|
||||
|
||||
|
|
@ -13,22 +18,27 @@ function getModelClass(
|
|||
return LLMClasses.find((llm) => llm.providerName === model.provider);
|
||||
}
|
||||
|
||||
function getContinueProxyModelName(
|
||||
ownerSlug: string,
|
||||
packageSlug: string,
|
||||
model: ModelConfig,
|
||||
): string {
|
||||
return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
|
||||
}
|
||||
// function getContinueProxyModelName(
|
||||
// ownerSlug: string,
|
||||
// packageSlug: string,
|
||||
// model: ModelConfig,
|
||||
// ): string {
|
||||
// return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
|
||||
// }
|
||||
|
||||
async function modelConfigToBaseLLM(
|
||||
model: ModelConfig,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM | undefined> {
|
||||
async function modelConfigToBaseLLM({
|
||||
model,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM | undefined> {
|
||||
const cls = getModelClass(model);
|
||||
|
||||
if (!cls) {
|
||||
|
|
@ -39,7 +49,7 @@ async function modelConfigToBaseLLM(
|
|||
|
||||
let options: LLMOptions = {
|
||||
...rest,
|
||||
// contextLength: model.defaultCompletionOptions?.contextLength ?? undefined,
|
||||
contextLength: model.defaultCompletionOptions?.contextLength,
|
||||
completionOptions: {
|
||||
...(model.defaultCompletionOptions ?? {}),
|
||||
model: model.model,
|
||||
|
|
@ -47,11 +57,12 @@ async function modelConfigToBaseLLM(
|
|||
model.defaultCompletionOptions?.maxTokens ??
|
||||
cls.defaultOptions?.completionOptions?.maxTokens,
|
||||
},
|
||||
writeLog,
|
||||
logger: llmLogger,
|
||||
uniqueId,
|
||||
title: model.name,
|
||||
systemMessage,
|
||||
template: model.promptTemplates?.chatTemplate,
|
||||
promptTemplates: model.promptTemplates,
|
||||
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
|
||||
capabilities: {
|
||||
tools: model.capabilities?.includes("tool_use"),
|
||||
uploadImage: model.capabilities?.includes("image_input"),
|
||||
|
|
@ -127,16 +138,23 @@ async function modelConfigToBaseLLM(
|
|||
return llm;
|
||||
}
|
||||
|
||||
async function autodetectModels(
|
||||
llm: BaseLLM,
|
||||
model: ModelConfig,
|
||||
ide: IDE,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM[]> {
|
||||
async function autodetectModels({
|
||||
llm,
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
config,
|
||||
}: {
|
||||
llm: BaseLLM;
|
||||
model: ModelConfig;
|
||||
ide: IDE;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const detectedModels = await Promise.all(
|
||||
|
|
@ -146,18 +164,17 @@ async function autodetectModels(
|
|||
return undefined;
|
||||
}
|
||||
|
||||
return await modelConfigToBaseLLM(
|
||||
{
|
||||
return await modelConfigToBaseLLM({
|
||||
model: {
|
||||
...model,
|
||||
model: modelName,
|
||||
name: modelName,
|
||||
},
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
llmLogger,
|
||||
config,
|
||||
});
|
||||
}),
|
||||
);
|
||||
return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[];
|
||||
|
|
@ -167,38 +184,42 @@ async function autodetectModels(
|
|||
}
|
||||
}
|
||||
|
||||
export async function llmsFromModelConfig(
|
||||
model: ModelConfig,
|
||||
ide: IDE,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM(
|
||||
export async function llmsFromModelConfig({
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
ide: IDE;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM({
|
||||
model,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
llmLogger,
|
||||
config,
|
||||
});
|
||||
if (!baseLlm) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (model.model === AUTODETECT) {
|
||||
const models = await autodetectModels(
|
||||
baseLlm,
|
||||
const models = await autodetectModels({
|
||||
llm: baseLlm,
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
llmLogger,
|
||||
config,
|
||||
});
|
||||
return models;
|
||||
} else {
|
||||
return [baseLlm];
|
||||
|
|
|
|||
|
|
@ -1,19 +0,0 @@
|
|||
import Bedrock from "../llm/llms/Bedrock";
|
||||
import Cohere from "../llm/llms/Cohere";
|
||||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI";
|
||||
import { LLMReranker } from "../llm/llms/llm";
|
||||
import ContinueProxy from "../llm/llms/stubs/ContinueProxy";
|
||||
import Voyage from "../llm/llms/Voyage";
|
||||
import WatsonX from "../llm/llms/WatsonX";
|
||||
|
||||
export const AllRerankers: { [key: string]: any } = {
|
||||
cohere: Cohere,
|
||||
bedrock: Bedrock,
|
||||
llm: LLMReranker,
|
||||
voyage: Voyage,
|
||||
watsonx: WatsonX,
|
||||
"free-trial": FreeTrial,
|
||||
"huggingface-tei": HuggingFaceTEI,
|
||||
"continue-proxy": ContinueProxy,
|
||||
};
|
||||
219
core/context/mcp/MCPConnection.test.ts
Normal file
219
core/context/mcp/MCPConnection.test.ts
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import MCPConnection from "./MCPConnection";
|
||||
|
||||
describe("MCPConnection", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("constructor", () => {
|
||||
it("should create instance with stdio transport", () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "test-cmd",
|
||||
args: ["--test"],
|
||||
env: { TEST: "true" },
|
||||
},
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
expect(conn).toBeInstanceOf(MCPConnection);
|
||||
expect(conn.status).toBe("not-connected");
|
||||
});
|
||||
|
||||
it("should create instance with websocket transport", () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "websocket" as const,
|
||||
url: "ws://test.com",
|
||||
},
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
expect(conn).toBeInstanceOf(MCPConnection);
|
||||
expect(conn.status).toBe("not-connected");
|
||||
});
|
||||
|
||||
it("should create instance with SSE transport", () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "sse" as const,
|
||||
url: "http://test.com/events",
|
||||
},
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
expect(conn).toBeInstanceOf(MCPConnection);
|
||||
expect(conn.status).toBe("not-connected");
|
||||
});
|
||||
|
||||
it("should throw on invalid transport type", () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "invalid",
|
||||
} as any,
|
||||
};
|
||||
|
||||
expect(() => new MCPConnection(options)).toThrow(
|
||||
"Unsupported transport type: invalid",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStatus", () => {
|
||||
it("should return current status", () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "test",
|
||||
args: [],
|
||||
},
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
const status = conn.getStatus();
|
||||
|
||||
expect(status).toEqual({
|
||||
...options,
|
||||
errors: [],
|
||||
prompts: [],
|
||||
resources: [],
|
||||
tools: [],
|
||||
status: "not-connected",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("connectClient", () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "test-cmd",
|
||||
args: [],
|
||||
},
|
||||
};
|
||||
|
||||
it("should connect successfully", async () => {
|
||||
const conn = new MCPConnection(options);
|
||||
const mockConnect = jest
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockResolvedValue(undefined);
|
||||
const mockGetServerCapabilities = jest
|
||||
.spyOn(Client.prototype, "getServerCapabilities")
|
||||
.mockReturnValue({
|
||||
resources: {},
|
||||
tools: {},
|
||||
prompts: {},
|
||||
});
|
||||
|
||||
const mockListResources = jest
|
||||
.spyOn(Client.prototype, "listResources")
|
||||
.mockResolvedValue({
|
||||
resources: [{ name: "test-resource", uri: "test-uri" }],
|
||||
});
|
||||
const mockListTools = jest
|
||||
.spyOn(Client.prototype, "listTools")
|
||||
.mockResolvedValue({
|
||||
tools: [
|
||||
{
|
||||
name: "test-tool",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const mockListPrompts = jest
|
||||
.spyOn(Client.prototype, "listPrompts")
|
||||
.mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
|
||||
|
||||
const abortController = new AbortController();
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
|
||||
expect(conn.status).toBe("connected");
|
||||
expect(conn.resources).toHaveLength(1);
|
||||
expect(conn.tools).toHaveLength(1);
|
||||
expect(conn.prompts).toHaveLength(1);
|
||||
expect(mockConnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle connection timeout", async () => {
|
||||
const conn = new MCPConnection({ ...options, timeout: 1 });
|
||||
const mockConnect = jest
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(resolve, 100)),
|
||||
);
|
||||
|
||||
const abortController = new AbortController();
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
|
||||
expect(conn.status).toBe("error");
|
||||
expect(conn.errors[0]).toContain("Failed to connect to MCP server");
|
||||
expect(mockConnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle already connected state", async () => {
|
||||
const conn = new MCPConnection(options);
|
||||
conn.status = "connected";
|
||||
|
||||
const mockConnect = jest.spyOn(Client.prototype, "connect");
|
||||
const abortController = new AbortController();
|
||||
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
|
||||
expect(mockConnect).not.toHaveBeenCalled();
|
||||
expect(conn.status).toBe("connected");
|
||||
});
|
||||
|
||||
it("should handle transport errors", async () => {
|
||||
const conn = new MCPConnection(options);
|
||||
const mockConnect = jest
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockRejectedValue(new Error("spawn test-cmd ENOENT"));
|
||||
|
||||
const abortController = new AbortController();
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
|
||||
expect(conn.status).toBe("error");
|
||||
expect(conn.errors[0]).toContain('command "test-cmd" not found');
|
||||
expect(mockConnect).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe.skip("actually connect to Filesystem MCP", () => {
|
||||
it("should connect and include correct tools", async () => {
|
||||
const conn = new MCPConnection({
|
||||
id: "filesystem",
|
||||
name: "Filesystem",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const abortController = new AbortController();
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
expect(conn.status).toBe("connected");
|
||||
} finally {
|
||||
await conn.disconnect();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
|
||||
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
|
||||
import {
|
||||
MCPConnectionStatus,
|
||||
|
|
@ -13,115 +14,7 @@ import {
|
|||
MCPTool,
|
||||
} from "../..";
|
||||
|
||||
export class MCPManagerSingleton {
|
||||
private static instance: MCPManagerSingleton;
|
||||
|
||||
public onConnectionsRefreshed?: () => void;
|
||||
private connections: Map<string, MCPConnection> = new Map();
|
||||
|
||||
private abortController: AbortController = new AbortController();
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): MCPManagerSingleton {
|
||||
if (!MCPManagerSingleton.instance) {
|
||||
MCPManagerSingleton.instance = new MCPManagerSingleton();
|
||||
}
|
||||
return MCPManagerSingleton.instance;
|
||||
}
|
||||
|
||||
createConnection(id: string, options: MCPOptions): MCPConnection {
|
||||
if (!this.connections.has(id)) {
|
||||
const connection = new MCPConnection(options);
|
||||
this.connections.set(id, connection);
|
||||
return connection;
|
||||
} else {
|
||||
return this.connections.get(id)!;
|
||||
}
|
||||
}
|
||||
|
||||
getConnection(id: string) {
|
||||
return this.connections.get(id);
|
||||
}
|
||||
|
||||
async removeConnection(id: string) {
|
||||
const connection = this.connections.get(id);
|
||||
if (connection) {
|
||||
await connection.client.close();
|
||||
}
|
||||
|
||||
this.connections.delete(id);
|
||||
}
|
||||
|
||||
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
|
||||
let refresh = false;
|
||||
|
||||
// Remove any connections that are no longer in config
|
||||
Array.from(this.connections.entries()).forEach(([id, connection]) => {
|
||||
if (!servers.find((s) => s.id === id)) {
|
||||
refresh = true;
|
||||
connection.abortController.abort();
|
||||
void connection.client.close();
|
||||
this.connections.delete(id);
|
||||
}
|
||||
});
|
||||
|
||||
// Add any connections that are not yet in manager
|
||||
servers.forEach((server) => {
|
||||
if (!this.connections.has(server.id)) {
|
||||
refresh = true;
|
||||
this.connections.set(server.id, new MCPConnection(server));
|
||||
}
|
||||
});
|
||||
|
||||
// NOTE the id is made by stringifying the options
|
||||
if (refresh) {
|
||||
void this.refreshConnections(forceRefresh);
|
||||
}
|
||||
}
|
||||
|
||||
async refreshConnection(serverId: string) {
|
||||
const connection = this.connections.get(serverId);
|
||||
if (!connection) {
|
||||
throw new Error(`MCP Connection ${serverId} not found`);
|
||||
}
|
||||
await connection.connectClient(true, this.abortController.signal);
|
||||
if (this.onConnectionsRefreshed) {
|
||||
this.onConnectionsRefreshed();
|
||||
}
|
||||
}
|
||||
|
||||
async refreshConnections(force: boolean) {
|
||||
this.abortController.abort();
|
||||
this.abortController = new AbortController();
|
||||
await Promise.race([
|
||||
new Promise((resolve) => {
|
||||
this.abortController.signal.addEventListener("abort", () => {
|
||||
resolve(undefined);
|
||||
});
|
||||
}),
|
||||
(async () => {
|
||||
await Promise.all(
|
||||
Array.from(this.connections.values()).map(async (connection) => {
|
||||
await connection.connectClient(force, this.abortController.signal);
|
||||
}),
|
||||
);
|
||||
if (this.onConnectionsRefreshed) {
|
||||
this.onConnectionsRefreshed();
|
||||
}
|
||||
})(),
|
||||
]);
|
||||
}
|
||||
|
||||
getStatuses(): (MCPServerStatus & { client: Client })[] {
|
||||
return Array.from(this.connections.values()).map((connection) => ({
|
||||
...connection.getStatus(),
|
||||
client: connection.client,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds
|
||||
export const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds
|
||||
|
||||
class MCPConnection {
|
||||
public client: Client;
|
||||
|
|
@ -137,7 +30,7 @@ class MCPConnection {
|
|||
public tools: MCPTool[] = [];
|
||||
public resources: MCPResource[] = [];
|
||||
|
||||
constructor(private readonly options: MCPOptions) {
|
||||
constructor(public options: MCPOptions) {
|
||||
this.transport = this.constructTransport(options);
|
||||
|
||||
this.client = new Client(
|
||||
|
|
@ -153,6 +46,12 @@ class MCPConnection {
|
|||
this.abortController = new AbortController();
|
||||
}
|
||||
|
||||
async disconnect() {
|
||||
this.abortController.abort();
|
||||
await this.client.close();
|
||||
await this.transport.close();
|
||||
}
|
||||
|
||||
private constructTransport(options: MCPOptions): Transport {
|
||||
switch (options.transport.type) {
|
||||
case "stdio":
|
||||
219
core/context/mcp/MCPManagerSingleton.test.ts
Normal file
219
core/context/mcp/MCPManagerSingleton.test.ts
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
import { MCPOptions } from "../..";
|
||||
import MCPConnection from "./MCPConnection";
|
||||
import { MCPManagerSingleton } from "./MCPManagerSingleton";
|
||||
|
||||
// Create test versions with stubbed behavior
|
||||
class TestMCPConnection extends MCPConnection {
|
||||
constructor(options: MCPOptions) {
|
||||
super(options);
|
||||
|
||||
// Override with test implementations
|
||||
this.client = {
|
||||
close: async () => {},
|
||||
connect: async () => {},
|
||||
getServerCapabilities: () => ({}),
|
||||
listResources: async () => ({ resources: [] }),
|
||||
listTools: async () => ({ tools: [] }),
|
||||
listPrompts: async () => ({ prompts: [] }),
|
||||
} as any;
|
||||
|
||||
this.abortController = new AbortController();
|
||||
this.connectClient = jest.fn().mockResolvedValue(undefined);
|
||||
this.getStatus = jest
|
||||
.fn()
|
||||
.mockReturnValue({ status: "connected", errors: [] });
|
||||
}
|
||||
}
|
||||
|
||||
describe("MCPManagerSingleton", () => {
|
||||
let manager: MCPManagerSingleton;
|
||||
const testOptions: MCPOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: "test-command",
|
||||
args: [],
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset singleton
|
||||
(MCPManagerSingleton as any).instance = undefined;
|
||||
manager = MCPManagerSingleton.getInstance();
|
||||
|
||||
// Replace the connections map with our own that will use TestMCPConnection
|
||||
const connectionsMap = new Map<string, MCPConnection>();
|
||||
Object.defineProperty(manager, "connections", {
|
||||
value: connectionsMap,
|
||||
writable: true,
|
||||
});
|
||||
|
||||
// Override createConnection to use our TestMCPConnection
|
||||
manager.createConnection = function (
|
||||
id: string,
|
||||
options: MCPOptions,
|
||||
): MCPConnection {
|
||||
if (!this.connections.has(id)) {
|
||||
const connection = new TestMCPConnection(options);
|
||||
this.connections.set(id, connection);
|
||||
return connection;
|
||||
} else {
|
||||
return this.connections.get(id)!;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
describe("getInstance", () => {
|
||||
it("should create singleton instance", () => {
|
||||
const instance1 = MCPManagerSingleton.getInstance();
|
||||
const instance2 = MCPManagerSingleton.getInstance();
|
||||
expect(instance1).toBe(instance2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createConnection", () => {
|
||||
it("should create new connection if none exists", () => {
|
||||
const connection = manager.createConnection("test-id", testOptions);
|
||||
expect(connection).toBeInstanceOf(MCPConnection);
|
||||
});
|
||||
|
||||
it("should return existing connection if exists", () => {
|
||||
const connection1 = manager.createConnection("test-id", testOptions);
|
||||
const connection2 = manager.createConnection("test-id", testOptions);
|
||||
expect(connection1).toBe(connection2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getConnection", () => {
|
||||
it("should return undefined for non-existent connection", () => {
|
||||
expect(manager.getConnection("non-existent")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return existing connection", () => {
|
||||
const connection = manager.createConnection("test-id", testOptions);
|
||||
expect(manager.getConnection("test-id")).toBe(connection);
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeConnection", () => {
|
||||
it("should remove connection and close client", async () => {
|
||||
// Create a spy on the close method
|
||||
const connection = manager.createConnection(
|
||||
"test-id",
|
||||
testOptions,
|
||||
) as TestMCPConnection;
|
||||
const closeSpy = jest.spyOn(connection.client, "close");
|
||||
|
||||
await manager.removeConnection("test-id");
|
||||
|
||||
expect(closeSpy).toHaveBeenCalled();
|
||||
expect(manager.getConnection("test-id")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle non-existent connection", async () => {
|
||||
await expect(
|
||||
manager.removeConnection("non-existent"),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("setConnections", () => {
|
||||
it("should add new connections", () => {
|
||||
const servers = [testOptions];
|
||||
manager.setConnections(servers, false);
|
||||
expect(manager.getConnection(testOptions.id)).toBeInstanceOf(
|
||||
MCPConnection,
|
||||
);
|
||||
});
|
||||
|
||||
it("should remove old connections", () => {
|
||||
// Create initial connection
|
||||
const connection = manager.createConnection(
|
||||
"test-id",
|
||||
testOptions,
|
||||
) as TestMCPConnection;
|
||||
const abortSpy = jest.spyOn(connection.abortController, "abort");
|
||||
const closeSpy = jest.spyOn(connection.client, "close");
|
||||
|
||||
// Remove it by setting empty server list
|
||||
manager.setConnections([], false);
|
||||
|
||||
expect(abortSpy).toHaveBeenCalled();
|
||||
expect(closeSpy).toHaveBeenCalled();
|
||||
expect(manager.getConnection("test-id")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("refreshConnection", () => {
|
||||
it("should refresh specific connection", async () => {
|
||||
const connection = manager.createConnection(
|
||||
"test-id",
|
||||
testOptions,
|
||||
) as TestMCPConnection;
|
||||
|
||||
await manager.refreshConnection("test-id");
|
||||
|
||||
expect(connection.connectClient).toHaveBeenCalledWith(
|
||||
true,
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error for non-existent connection", async () => {
|
||||
await expect(manager.refreshConnection("non-existent")).rejects.toThrow(
|
||||
"MCP Connection non-existent not found",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("refreshConnections", () => {
|
||||
it("should refresh all connections", async () => {
|
||||
const connection1 = manager.createConnection("test-id-1", {
|
||||
...testOptions,
|
||||
id: "test-id-1",
|
||||
}) as TestMCPConnection;
|
||||
|
||||
const connection2 = manager.createConnection("test-id-2", {
|
||||
...testOptions,
|
||||
id: "test-id-2",
|
||||
}) as TestMCPConnection;
|
||||
|
||||
await manager.refreshConnections(true);
|
||||
|
||||
expect(connection1.connectClient).toHaveBeenCalledWith(
|
||||
true,
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
expect(connection2.connectClient).toHaveBeenCalledWith(
|
||||
true,
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
});
|
||||
|
||||
it("should call onConnectionsRefreshed if defined", async () => {
|
||||
const mockCallback = jest.fn();
|
||||
manager.onConnectionsRefreshed = mockCallback;
|
||||
manager.createConnection("test-id", testOptions);
|
||||
|
||||
await manager.refreshConnections(true);
|
||||
|
||||
expect(mockCallback).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStatuses", () => {
|
||||
it("should return statuses for all connections", () => {
|
||||
const connection = manager.createConnection(
|
||||
"test-id",
|
||||
testOptions,
|
||||
) as TestMCPConnection;
|
||||
const mockStatus = { status: "connected", errors: [] };
|
||||
connection.getStatus = jest.fn().mockReturnValue(mockStatus);
|
||||
|
||||
const statuses = manager.getStatuses();
|
||||
expect(statuses).toHaveLength(1);
|
||||
expect(statuses[0]).toEqual({ ...mockStatus, client: connection.client });
|
||||
});
|
||||
});
|
||||
});
|
||||
164
core/context/mcp/MCPManagerSingleton.ts
Normal file
164
core/context/mcp/MCPManagerSingleton.ts
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import {
|
||||
MCPOptions,
|
||||
MCPServerStatus,
|
||||
StdioOptions,
|
||||
TransportOptions,
|
||||
} from "../..";
|
||||
import MCPConnection from "./MCPConnection";
|
||||
|
||||
export class MCPManagerSingleton {
|
||||
private static instance: MCPManagerSingleton;
|
||||
|
||||
public onConnectionsRefreshed?: () => void;
|
||||
public connections: Map<string, MCPConnection> = new Map();
|
||||
|
||||
private abortController: AbortController = new AbortController();
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): MCPManagerSingleton {
|
||||
if (!MCPManagerSingleton.instance) {
|
||||
MCPManagerSingleton.instance = new MCPManagerSingleton();
|
||||
}
|
||||
return MCPManagerSingleton.instance;
|
||||
}
|
||||
|
||||
createConnection(id: string, options: MCPOptions): MCPConnection {
|
||||
if (!this.connections.has(id)) {
|
||||
const connection = new MCPConnection(options);
|
||||
this.connections.set(id, connection);
|
||||
return connection;
|
||||
} else {
|
||||
return this.connections.get(id)!;
|
||||
}
|
||||
}
|
||||
|
||||
getConnection(id: string) {
|
||||
return this.connections.get(id);
|
||||
}
|
||||
|
||||
async removeConnection(id: string) {
|
||||
const connection = this.connections.get(id);
|
||||
if (connection) {
|
||||
await connection.client.close();
|
||||
}
|
||||
|
||||
this.connections.delete(id);
|
||||
}
|
||||
|
||||
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
|
||||
let refresh = false;
|
||||
|
||||
// Remove any connections that are no longer in config
|
||||
Array.from(this.connections.entries()).forEach(([id, connection]) => {
|
||||
if (
|
||||
!servers.find(
|
||||
// Refresh the connection if TransportOptions changed
|
||||
(s) =>
|
||||
s.id === id &&
|
||||
this.compareTransportOptions(
|
||||
connection.options.transport,
|
||||
s.transport,
|
||||
),
|
||||
)
|
||||
) {
|
||||
refresh = true;
|
||||
connection.abortController.abort();
|
||||
void connection.client.close();
|
||||
this.connections.delete(id);
|
||||
}
|
||||
});
|
||||
|
||||
// Add any connections that are not yet in manager
|
||||
servers.forEach((server) => {
|
||||
if (!this.connections.has(server.id)) {
|
||||
refresh = true;
|
||||
this.connections.set(server.id, new MCPConnection(server));
|
||||
} else {
|
||||
const conn = this.connections.get(server.id);
|
||||
if (conn) {
|
||||
// We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
|
||||
conn.options = server;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// NOTE the id is made by stringifying the options
|
||||
if (refresh) {
|
||||
void this.refreshConnections(forceRefresh);
|
||||
}
|
||||
}
|
||||
|
||||
private compareTransportOptions(
|
||||
a: TransportOptions,
|
||||
b: TransportOptions,
|
||||
): boolean {
|
||||
if (a.type !== b.type) {
|
||||
return false;
|
||||
}
|
||||
if (a.type === "stdio" && b.type === "stdio") {
|
||||
return (
|
||||
a.command === b.command &&
|
||||
JSON.stringify(a.args) === JSON.stringify(b.args) &&
|
||||
this.compareEnv(a, b)
|
||||
);
|
||||
} else if (a.type !== "stdio" && b.type !== "stdio") {
|
||||
return a.url === b.url;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private compareEnv(a: StdioOptions, b: StdioOptions): boolean {
|
||||
const aEnv = a.env ?? {};
|
||||
const bEnv = b.env ?? {};
|
||||
const aKeys = Object.keys(aEnv);
|
||||
const bKeys = Object.keys(bEnv);
|
||||
|
||||
return (
|
||||
aKeys.length === bKeys.length &&
|
||||
aKeys.every((key) => aEnv[key] === bEnv[key])
|
||||
);
|
||||
}
|
||||
|
||||
async refreshConnection(serverId: string) {
|
||||
const connection = this.connections.get(serverId);
|
||||
if (!connection) {
|
||||
throw new Error(`MCP Connection ${serverId} not found`);
|
||||
}
|
||||
await connection.connectClient(true, this.abortController.signal);
|
||||
if (this.onConnectionsRefreshed) {
|
||||
this.onConnectionsRefreshed();
|
||||
}
|
||||
}
|
||||
|
||||
async refreshConnections(force: boolean) {
|
||||
this.abortController.abort();
|
||||
this.abortController = new AbortController();
|
||||
await Promise.race([
|
||||
new Promise((resolve) => {
|
||||
this.abortController.signal.addEventListener("abort", () => {
|
||||
resolve(undefined);
|
||||
});
|
||||
}),
|
||||
(async () => {
|
||||
await Promise.all(
|
||||
Array.from(this.connections.values()).map(async (connection) => {
|
||||
await connection.connectClient(force, this.abortController.signal);
|
||||
}),
|
||||
);
|
||||
if (this.onConnectionsRefreshed) {
|
||||
this.onConnectionsRefreshed();
|
||||
}
|
||||
})(),
|
||||
]);
|
||||
}
|
||||
|
||||
getStatuses(): (MCPServerStatus & { client: Client })[] {
|
||||
return Array.from(this.connections.values()).map((connection) => ({
|
||||
...connection.getStatus(),
|
||||
client: connection.client,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
|
@ -24,6 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider {
|
|||
this.options.title || ContinueProxyContextProvider.description.title,
|
||||
displayTitle:
|
||||
this.options.displayTitle ||
|
||||
this.options.name ||
|
||||
ContinueProxyContextProvider.description.displayTitle,
|
||||
description:
|
||||
this.options.description ||
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ class FolderContextProvider extends BaseContextProvider {
|
|||
const folders = await walkDirs(
|
||||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
include: "dirs",
|
||||
source: "load submenu items - folder",
|
||||
},
|
||||
workspaceDirs,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import isLocalhost from "is-localhost-ip";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
IDE,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
|
|
@ -14,25 +16,41 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
private async getWorkspacePath(ide: IDE, url: URL) {
|
||||
try {
|
||||
const currentFile = await ide.getCurrentFile();
|
||||
// `isLocalhost` actually also returns true for other local addresses, not just localhost
|
||||
return await isLocalhost(url.hostname) ?
|
||||
(await ide.getWorkspaceDirs()).find(workspaceDirectory => {
|
||||
return currentFile?.path.startsWith(workspaceDirectory)
|
||||
}) : undefined
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
override get description(): ContextProviderDescription {
|
||||
return {
|
||||
title: this.options.title || "http",
|
||||
displayTitle: this.options.displayTitle || "HTTP",
|
||||
title: this.options.title || HttpContextProvider.description.title,
|
||||
displayTitle:
|
||||
this.options.displayTitle ||
|
||||
this.options.name ||
|
||||
HttpContextProvider.description.displayTitle,
|
||||
description:
|
||||
this.options.description ||
|
||||
"Retrieve a context item from a custom server",
|
||||
type: "normal",
|
||||
this.options.description || HttpContextProvider.description.description,
|
||||
type: HttpContextProvider.description.type,
|
||||
renderInlineAs:
|
||||
this.options.renderInlineAs ||
|
||||
HttpContextProvider.description.renderInlineAs,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const response = await extras.fetch(new URL(this.options.url), {
|
||||
const parsedUrl = new URL(this.options.url)
|
||||
const response = await extras.fetch(parsedUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
|
@ -42,6 +60,7 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
query: query || "",
|
||||
fullInput: extras.fullInput,
|
||||
options: this.options.options,
|
||||
workspacePath: await this.getWorkspacePath(extras.ide, parsedUrl),
|
||||
}),
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -6,10 +6,11 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../";
|
||||
import { MCPManagerSingleton } from "../mcp";
|
||||
import { MCPManagerSingleton } from "../mcp/MCPManagerSingleton";
|
||||
|
||||
interface MCPContextProviderOptions {
|
||||
mcpId: string;
|
||||
serverName: string;
|
||||
submenuItems: ContextSubmenuItem[];
|
||||
}
|
||||
|
||||
|
|
@ -20,6 +21,16 @@ class MCPContextProvider extends BaseContextProvider {
|
|||
description: "Model Context Protocol",
|
||||
type: "submenu",
|
||||
};
|
||||
override get description(): ContextProviderDescription {
|
||||
return {
|
||||
title: `${MCPContextProvider.description.title}-${this.options["mcpId"]}`,
|
||||
displayTitle: this.options["serverName"]
|
||||
? `${this.options["serverName"]} resources`
|
||||
: "MCP",
|
||||
description: "Model Context Protocol",
|
||||
type: "submenu",
|
||||
};
|
||||
}
|
||||
|
||||
static encodeMCPResourceId(mcpId: string, uri: string): string {
|
||||
return JSON.stringify({ mcpId, uri });
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ class RepoMapContextProvider extends BaseContextProvider {
|
|||
const folders = await walkDirs(
|
||||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
include: "dirs",
|
||||
source: "load submenu items - repo map",
|
||||
},
|
||||
workspaceDirs,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class SearchContextProvider extends BaseContextProvider {
|
||||
|
|
@ -19,10 +20,11 @@ class SearchContextProvider extends BaseContextProvider {
|
|||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const results = await extras.ide.getSearchResults(query);
|
||||
const formatted = formatGrepSearchResults(results);
|
||||
return [
|
||||
{
|
||||
description: "Search results",
|
||||
content: `Results of searching codebase for "${query}":\n\n${results}`,
|
||||
content: `Results of searching codebase for "${query}":\n\n${formatted}`,
|
||||
name: "Search results",
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
IContextProvider,
|
||||
} from "../..";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { LLMLogger } from "../../llm/logger";
|
||||
import { TEST_DIR } from "../../test/testDir";
|
||||
import FileSystemIde from "../../util/filesystem";
|
||||
|
||||
|
|
@ -26,13 +27,13 @@ async function getContextProviderExtras(
|
|||
): Promise<ContextProviderExtras> {
|
||||
const ide = new FileSystemIde(TEST_DIR);
|
||||
const ideSettingsPromise = ide.getIdeSettings();
|
||||
const llmLogger = new LLMLogger();
|
||||
const configHandler = new ConfigHandler(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
async (text) => {},
|
||||
llmLogger,
|
||||
Promise.resolve(undefined),
|
||||
);
|
||||
await configHandler.initializedPromise;
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not found");
|
||||
|
|
@ -44,7 +45,7 @@ async function getContextProviderExtras(
|
|||
config,
|
||||
embeddingsProvider: config.selectedModelByRole.embed,
|
||||
fetch: fetch,
|
||||
llm: config.models[0],
|
||||
llm: config.modelsByRole.chat[0],
|
||||
reranker: config.selectedModelByRole.rerank,
|
||||
selectedCode: [],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
const cleanedTokens = [...tokens].join(" ");
|
||||
const trigrams = nlp.string.ngram(cleanedTokens, 3);
|
||||
|
||||
return trigrams;
|
||||
return trigrams.map(this.escapeFtsQueryString);
|
||||
}
|
||||
|
||||
private escapeFtsQueryString(query: string): string {
|
||||
|
|
@ -84,9 +84,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
return [];
|
||||
}
|
||||
|
||||
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
|
||||
const tokens = this.escapeFtsQueryString(tokensRaw);
|
||||
|
||||
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
|
||||
|
||||
return await this.ftsIndex.retrieve({
|
||||
n,
|
||||
text: tokens,
|
||||
|
|
|
|||
|
|
@ -21,16 +21,6 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
|
|||
const WORKOS_ENV_ID_PRODUCTION = "continue";
|
||||
const WORKOS_ENV_ID_STAGING = "continue-staging";
|
||||
|
||||
export const PRODUCTION_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL:
|
||||
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
|
||||
CONTROL_PLANE_URL:
|
||||
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
|
||||
AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
|
||||
APP_URL: "https://app.continue.dev/",
|
||||
};
|
||||
|
||||
const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/",
|
||||
CONTROL_PLANE_URL: "https://api.continue.dev/",
|
||||
|
|
@ -71,15 +61,11 @@ export async function getControlPlaneEnv(
|
|||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<ControlPlaneEnv> {
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
return getControlPlaneEnvSync(
|
||||
ideSettings.continueTestEnvironment,
|
||||
ideSettings.enableControlServerBeta,
|
||||
);
|
||||
return getControlPlaneEnvSync(ideSettings.continueTestEnvironment);
|
||||
}
|
||||
|
||||
export function getControlPlaneEnvSync(
|
||||
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
|
||||
enableControlServerBeta: IdeSettings["enableControlServerBeta"],
|
||||
): ControlPlaneEnv {
|
||||
// Note .local overrides .staging
|
||||
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
|
||||
|
|
@ -90,10 +76,6 @@ export function getControlPlaneEnvSync(
|
|||
return STAGING_ENV;
|
||||
}
|
||||
|
||||
if (enableControlServerBeta === true) {
|
||||
return PRODUCTION_ENV;
|
||||
}
|
||||
|
||||
const env =
|
||||
ideTestEnvironment === "production"
|
||||
? "hub"
|
||||
|
|
@ -109,17 +91,12 @@ export function getControlPlaneEnvSync(
|
|||
? STAGING_ENV
|
||||
: env === "test"
|
||||
? TEST_ENV
|
||||
: env === "hub"
|
||||
? PRODUCTION_HUB_ENV
|
||||
: PRODUCTION_ENV;
|
||||
: PRODUCTION_HUB_ENV;
|
||||
}
|
||||
|
||||
export async function useHub(
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<boolean> {
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
if (ideSettings.enableControlServerBeta) {
|
||||
return false;
|
||||
}
|
||||
return ideSettings.continueTestEnvironment !== "none";
|
||||
}
|
||||
|
|
|
|||
871
core/core.ts
871
core/core.ts
File diff suppressed because it is too large
Load diff
|
|
@ -41,4 +41,16 @@ describe("Test myers diff function", () => {
|
|||
{ type: "same", line: "C" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("should ignore single-line whitespace-only differences", () => {
|
||||
const linesA = "A\n B\nC\n";
|
||||
const linesB = "A\nB\nC";
|
||||
|
||||
const diffLines = myersDiff(linesA, linesB);
|
||||
expect(diffLines).toEqual([
|
||||
{ type: "same", line: "A" },
|
||||
{ type: "same", line: " B" },
|
||||
{ type: "same", line: "C" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -30,8 +30,21 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
|
|||
const theirFormat = diffLines(oldContent, newContent, {
|
||||
ignoreNewlineAtEof: true,
|
||||
});
|
||||
const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
|
||||
let ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
|
||||
|
||||
// Combine consecutive old/new pairs that are identical after trimming
|
||||
for (let i = 0; i < ourFormat.length - 1; i++) {
|
||||
if (
|
||||
ourFormat[i]?.type === "old" &&
|
||||
ourFormat[i + 1]?.type === "new" &&
|
||||
ourFormat[i].line.trim() === ourFormat[i + 1].line.trim()
|
||||
) {
|
||||
ourFormat[i] = { type: "same", line: ourFormat[i].line };
|
||||
ourFormat.splice(i + 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove trailing empty old lines
|
||||
while (
|
||||
ourFormat.length > 0 &&
|
||||
ourFormat[ourFormat.length - 1].type === "old" &&
|
||||
|
|
|
|||
|
|
@ -2,10 +2,9 @@ import { DiffLine, ILLM } from "../..";
|
|||
import { generateLines } from "../../diff/util";
|
||||
import { supportedLanguages } from "../../util/treeSitter";
|
||||
import { getUriFileExtension } from "../../util/uri";
|
||||
|
||||
import { deterministicApplyLazyEdit } from "./deterministic";
|
||||
import { streamLazyApply } from "./streamLazyApply";
|
||||
import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply";
|
||||
import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply";
|
||||
|
||||
function canUseInstantApply(filename: string) {
|
||||
const fileExtension = getUriFileExtension(filename);
|
||||
|
|
@ -14,36 +13,44 @@ function canUseInstantApply(filename: string) {
|
|||
|
||||
export async function applyCodeBlock(
|
||||
oldFile: string,
|
||||
newFile: string,
|
||||
newLazyFile: string,
|
||||
filename: string,
|
||||
llm: ILLM,
|
||||
fastLlm: ILLM,
|
||||
): Promise<[boolean, AsyncGenerator<DiffLine>]> {
|
||||
// This was buggy, removed for now, maybe forever
|
||||
if (false && canUseInstantApply(filename)) {
|
||||
const diffLines = await deterministicApplyLazyEdit(
|
||||
): Promise<{
|
||||
isInstantApply: boolean;
|
||||
diffLinesGenerator: AsyncGenerator<DiffLine>;
|
||||
}> {
|
||||
if (canUseInstantApply(filename)) {
|
||||
const diffLines = await deterministicApplyLazyEdit({
|
||||
oldFile,
|
||||
newFile,
|
||||
newLazyFile,
|
||||
filename,
|
||||
);
|
||||
onlyFullFileRewrite: true,
|
||||
});
|
||||
|
||||
// Fall back to LLM method if we couldn't apply deterministically
|
||||
if (diffLines !== undefined) {
|
||||
const diffGenerator = generateLines(diffLines!);
|
||||
return [true, diffGenerator];
|
||||
return {
|
||||
isInstantApply: true,
|
||||
diffLinesGenerator: generateLines(diffLines!),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// If the code block is a diff
|
||||
if (isUnifiedDiffFormat(newFile)) {
|
||||
if (isUnifiedDiffFormat(newLazyFile)) {
|
||||
try {
|
||||
const diffLines = applyUnifiedDiff(oldFile, newFile);
|
||||
const diffGenerator = generateLines(diffLines!);
|
||||
return [true, diffGenerator];
|
||||
const diffLines = applyUnifiedDiff(oldFile, newLazyFile);
|
||||
return {
|
||||
isInstantApply: true,
|
||||
diffLinesGenerator: generateLines(diffLines!),
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Failed to apply unified diff", e);
|
||||
}
|
||||
}
|
||||
|
||||
return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)];
|
||||
return {
|
||||
isInstantApply: false,
|
||||
diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,11 +21,11 @@ async function collectDiffs(
|
|||
): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> {
|
||||
const ourDiffs: DiffLine[] = [];
|
||||
|
||||
for (const diffLine of (await deterministicApplyLazyEdit(
|
||||
for (const diffLine of (await deterministicApplyLazyEdit({
|
||||
oldFile,
|
||||
newFile,
|
||||
newLazyFile: newFile,
|
||||
filename,
|
||||
)) ?? []) {
|
||||
})) ?? []) {
|
||||
ourDiffs.push(diffLine);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,11 @@ type AstReplacements = Array<{
|
|||
replacementNodes: Parser.SyntaxNode[];
|
||||
}>;
|
||||
|
||||
const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/;
|
||||
export function isLazyText(text: string): boolean {
|
||||
return LAZY_COMMENT_REGEX.test(text);
|
||||
}
|
||||
|
||||
function reconstructNewFile(
|
||||
oldFile: string,
|
||||
newFile: string,
|
||||
|
|
@ -121,11 +126,23 @@ function nodeSurroundedInLazyBlocks(
|
|||
}
|
||||
|
||||
// TODO: If we don't have high confidence, return undefined to fall back to slower methods
|
||||
export async function deterministicApplyLazyEdit(
|
||||
oldFile: string,
|
||||
newLazyFile: string,
|
||||
filename: string,
|
||||
): Promise<DiffLine[] | undefined> {
|
||||
export async function deterministicApplyLazyEdit({
|
||||
oldFile,
|
||||
newLazyFile,
|
||||
filename,
|
||||
/**
|
||||
* Using this as a flag to slowly reintroduce lazy applies.
|
||||
* With this set, we will only attempt to deterministically apply
|
||||
* when there are no lazy blocks and then just replace the whole file,
|
||||
* and otherwise never use instant apply
|
||||
*/
|
||||
onlyFullFileRewrite = false,
|
||||
}: {
|
||||
oldFile: string;
|
||||
newLazyFile: string;
|
||||
filename: string;
|
||||
onlyFullFileRewrite?: boolean;
|
||||
}): Promise<DiffLine[] | undefined> {
|
||||
const parser = await getParserForFile(filename);
|
||||
if (!parser) {
|
||||
return undefined;
|
||||
|
|
@ -135,6 +152,20 @@ export async function deterministicApplyLazyEdit(
|
|||
let newTree = parser.parse(newLazyFile);
|
||||
let reconstructedNewFile: string | undefined = undefined;
|
||||
|
||||
if (onlyFullFileRewrite) {
|
||||
if (!isLazyText(newTree.rootNode.text)) {
|
||||
const diff = myersDiff(oldFile, newLazyFile);
|
||||
|
||||
if (shouldRejectDiff(diff)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return diff;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// If there is no lazy block anywhere, we add our own to the outsides
|
||||
// so that large chunks of the file don't get removed
|
||||
if (!findInAst(newTree.rootNode, isLazyBlock)) {
|
||||
|
|
@ -198,11 +229,6 @@ export async function deterministicApplyLazyEdit(
|
|||
return diff;
|
||||
}
|
||||
|
||||
const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/;
|
||||
export function isLazyLine(text: string): boolean {
|
||||
return LAZY_COMMENT_REGEX.test(text);
|
||||
}
|
||||
|
||||
function isLazyBlock(node: Parser.SyntaxNode): boolean {
|
||||
// Special case for "{/* ... existing code ... */}"
|
||||
if (
|
||||
|
|
@ -213,7 +239,7 @@ function isLazyBlock(node: Parser.SyntaxNode): boolean {
|
|||
return true;
|
||||
}
|
||||
|
||||
return node.type.includes("comment") && isLazyLine(node.text);
|
||||
return node.type.includes("comment") && isLazyText(node.text);
|
||||
}
|
||||
|
||||
function stringsWithinLevDistThreshold(
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@ export async function* streamLazyApply(
|
|||
filename: string,
|
||||
newCode: string,
|
||||
llm: ILLM,
|
||||
fastLlm: ILLM,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
|
||||
if (!promptFactory) {
|
||||
|
|
@ -39,7 +38,7 @@ export async function* streamLazyApply(
|
|||
oldCode,
|
||||
linesBefore,
|
||||
linesAfter,
|
||||
fastLlm,
|
||||
llm,
|
||||
)) {
|
||||
yield line;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,12 @@
|
|||
import { ChatMessage, DiffLine, ILLM, Prediction } from "../";
|
||||
import {
|
||||
ChatMessage,
|
||||
DiffLine,
|
||||
ILLM,
|
||||
Prediction,
|
||||
RuleWithSource,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
} from "../";
|
||||
import {
|
||||
filterCodeBlockLines,
|
||||
filterEnglishLinesAtEnd,
|
||||
|
|
@ -10,7 +18,9 @@ import {
|
|||
} from "../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamDiff } from "../diff/streamDiff";
|
||||
import { streamLines } from "../diff/util";
|
||||
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
|
||||
import { gptEditPrompt } from "../llm/templates/edit";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
|
||||
function constructPrompt(
|
||||
|
|
@ -47,16 +57,27 @@ function modelIsInept(model: string): boolean {
|
|||
return !(model.includes("gpt") || model.includes("claude"));
|
||||
}
|
||||
|
||||
export async function* streamDiffLines(
|
||||
prefix: string,
|
||||
highlighted: string,
|
||||
suffix: string,
|
||||
llm: ILLM,
|
||||
input: string,
|
||||
language: string | undefined,
|
||||
onlyOneInsertion: boolean,
|
||||
overridePrompt: ChatMessage[] | undefined,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
export async function* streamDiffLines({
|
||||
prefix,
|
||||
highlighted,
|
||||
suffix,
|
||||
llm,
|
||||
input,
|
||||
language,
|
||||
onlyOneInsertion,
|
||||
overridePrompt,
|
||||
rules,
|
||||
}: {
|
||||
prefix: string;
|
||||
highlighted: string;
|
||||
suffix: string;
|
||||
llm: ILLM;
|
||||
input: string;
|
||||
language: string | undefined;
|
||||
onlyOneInsertion: boolean;
|
||||
overridePrompt: ChatMessage[] | undefined;
|
||||
rules: RuleWithSource[];
|
||||
}): AsyncGenerator<DiffLine> {
|
||||
void Telemetry.capture(
|
||||
"inlineEdit",
|
||||
{
|
||||
|
|
@ -78,9 +99,56 @@ export async function* streamDiffLines(
|
|||
oldLines = [];
|
||||
}
|
||||
|
||||
const prompt =
|
||||
let prompt =
|
||||
overridePrompt ??
|
||||
constructPrompt(prefix, highlighted, suffix, llm, input, language);
|
||||
|
||||
// Rules will be included with edit prompt
|
||||
// If any rules are present this will result in using chat instead of legacy completion
|
||||
const lastUserMessage =
|
||||
typeof prompt === "string"
|
||||
? ({
|
||||
role: "user",
|
||||
content: prompt,
|
||||
} as UserChatMessage)
|
||||
: (findLast(
|
||||
prompt,
|
||||
(msg) => msg.role === "user" || msg.role === "tool",
|
||||
) as UserChatMessage | ToolResultChatMessage | undefined);
|
||||
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
rules,
|
||||
userMessage: lastUserMessage,
|
||||
baseSystemMessage: undefined,
|
||||
});
|
||||
|
||||
if (systemMessage) {
|
||||
if (typeof prompt === "string") {
|
||||
// Removed system prompt because it was causing it to be used for Apply
|
||||
// We should bring it back only for Edit
|
||||
prompt = [
|
||||
// {
|
||||
// role: "system",
|
||||
// content: systemMessage,
|
||||
// },
|
||||
{
|
||||
role: "user",
|
||||
content: prompt,
|
||||
},
|
||||
];
|
||||
} else {
|
||||
const curSysMsg = prompt.find((msg) => msg.role === "system");
|
||||
if (curSysMsg) {
|
||||
curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content;
|
||||
} else {
|
||||
// prompt.unshift({
|
||||
// role: "system",
|
||||
// content: systemMessage,
|
||||
// });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const inept = modelIsInept(llm.model);
|
||||
|
||||
const prediction: Prediction = {
|
||||
|
|
|
|||
239
core/index.d.ts
vendored
239
core/index.d.ts
vendored
|
|
@ -1,6 +1,12 @@
|
|||
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
|
||||
import {
|
||||
DataDestination,
|
||||
ModelRole,
|
||||
PromptTemplates,
|
||||
} from "@continuedev/config-yaml";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { LLMConfigurationStatuses } from "./llm/constants";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
|
|
@ -75,39 +81,19 @@ export type PromptTemplateFunction = (
|
|||
|
||||
export type PromptTemplate = string | PromptTemplateFunction;
|
||||
|
||||
export interface ILLM extends LLMOptions {
|
||||
type RequiredLLMOptions =
|
||||
| "uniqueId"
|
||||
| "contextLength"
|
||||
| "embeddingId"
|
||||
| "maxEmbeddingChunkSize"
|
||||
| "maxEmbeddingBatchSize"
|
||||
| "completionOptions";
|
||||
|
||||
export interface ILLM
|
||||
extends Omit<LLMOptions, RequiredLLMOptions>,
|
||||
Required<Pick<LLMOptions, RequiredLLMOptions>> {
|
||||
get providerName(): string;
|
||||
|
||||
uniqueId: string;
|
||||
model: string;
|
||||
|
||||
title?: string;
|
||||
systemMessage?: string;
|
||||
contextLength: number;
|
||||
maxStopWords?: number;
|
||||
completionOptions: CompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
cacheBehavior?: CacheBehavior;
|
||||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
|
||||
deployment?: string;
|
||||
apiVersion?: string;
|
||||
apiType?: string;
|
||||
region?: string;
|
||||
projectId?: string;
|
||||
|
||||
// Embedding options
|
||||
embeddingId: string;
|
||||
maxEmbeddingChunkSize: number;
|
||||
maxEmbeddingBatchSize: number;
|
||||
|
||||
complete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
|
|
@ -161,6 +147,8 @@ export interface ILLM extends LLMOptions {
|
|||
otherData: Record<string, string>,
|
||||
canPutWordsInModelsMouth?: boolean,
|
||||
): string | ChatMessage[];
|
||||
|
||||
getConfigurationStatus(): LLMConfigurationStatuses;
|
||||
}
|
||||
|
||||
export interface ModelInstaller {
|
||||
|
|
@ -169,6 +157,10 @@ export interface ModelInstaller {
|
|||
signal: AbortSignal,
|
||||
progressReporter?: (task: string, increment: number, total: number) => void,
|
||||
): Promise<any>;
|
||||
|
||||
isInstallingModel(
|
||||
modelName: string
|
||||
): Promise<boolean>;
|
||||
}
|
||||
|
||||
export type ContextProviderType = "normal" | "query" | "submenu";
|
||||
|
|
@ -411,6 +403,7 @@ export interface ContextItem {
|
|||
icon?: string;
|
||||
uri?: ContextItemUri;
|
||||
hidden?: boolean;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export interface ContextItemWithId extends ContextItem {
|
||||
|
|
@ -443,6 +436,7 @@ export type ToolStatus =
|
|||
| "generating"
|
||||
| "generated"
|
||||
| "calling"
|
||||
| "errored"
|
||||
| "done"
|
||||
| "canceled";
|
||||
|
||||
|
|
@ -482,20 +476,108 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions {
|
|||
|
||||
export type ToastType = "info" | "error" | "warning";
|
||||
|
||||
export interface LLMInteractionBase {
|
||||
interactionId: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartChat extends LLMInteractionBase {
|
||||
kind: "startChat";
|
||||
messages: ChatMessage[];
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartComplete extends LLMInteractionBase {
|
||||
kind: "startComplete";
|
||||
prompt: string;
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartFim extends LLMInteractionBase {
|
||||
kind: "startFim";
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionChunk extends LLMInteractionBase {
|
||||
kind: "chunk";
|
||||
chunk: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionMessage extends LLMInteractionBase {
|
||||
kind: "message";
|
||||
message: ChatMessage;
|
||||
}
|
||||
|
||||
export interface LLMInteractionEnd extends LLMInteractionBase {
|
||||
promptTokens: number;
|
||||
generatedTokens: number;
|
||||
thinkingTokens: number;
|
||||
}
|
||||
|
||||
export interface LLMInteractionSuccess extends LLMInteractionEnd {
|
||||
kind: "success";
|
||||
}
|
||||
|
||||
export interface LLMInteractionCancel extends LLMInteractionEnd {
|
||||
kind: "cancel";
|
||||
}
|
||||
|
||||
export interface LLMInteractionError extends LLMInteractionEnd {
|
||||
kind: "error";
|
||||
name: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type LLMInteractionItem =
|
||||
| LLMInteractionStartChat
|
||||
| LLMInteractionStartComplete
|
||||
| LLMInteractionStartFim
|
||||
| LLMInteractionChunk
|
||||
| LLMInteractionMessage
|
||||
| LLMInteractionSuccess
|
||||
| LLMInteractionCancel
|
||||
| LLMInteractionError;
|
||||
|
||||
// When we log a LLM interaction, we want to add the interactionId and timestamp
|
||||
// in the logger code, so we need a type that omits these members from *each*
|
||||
// member of the union. This can be done by using the distributive behavior of
|
||||
// conditional types in Typescript.
|
||||
//
|
||||
// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
|
||||
// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s
|
||||
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
|
||||
? Omit<T, K>
|
||||
: never;
|
||||
|
||||
export type LLMInteractionItemDetails = DistributiveOmit<
|
||||
LLMInteractionItem,
|
||||
"interactionId" | "timestamp"
|
||||
>;
|
||||
|
||||
export interface ILLMInteractionLog {
|
||||
logItem(item: LLMInteractionItemDetails): void;
|
||||
}
|
||||
|
||||
export interface ILLMLogger {
|
||||
createInteractionLog(): ILLMInteractionLog;
|
||||
}
|
||||
|
||||
export interface LLMOptions {
|
||||
model: string;
|
||||
|
||||
title?: string;
|
||||
uniqueId?: string;
|
||||
systemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
contextLength?: number;
|
||||
maxStopWords?: number;
|
||||
completionOptions?: CompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
template?: TemplateType;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
promptTemplates?: Partial<Record<keyof PromptTemplates, PromptTemplate>>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
|
||||
|
|
@ -627,7 +709,6 @@ export interface IdeSettings {
|
|||
remoteConfigServerUrl: string | undefined;
|
||||
remoteConfigSyncPeriod: number;
|
||||
userToken: string;
|
||||
enableControlServerBeta: boolean;
|
||||
continueTestEnvironment: "none" | "production" | "staging" | "local";
|
||||
pauseCodebaseIndexOnStart: boolean;
|
||||
}
|
||||
|
|
@ -709,6 +790,8 @@ export interface IDE {
|
|||
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
|
||||
getFileResults(pattern: string): Promise<string[]>;
|
||||
|
||||
subprocess(command: string, cwd?: string): Promise<[string, string]>;
|
||||
|
||||
getProblems(fileUri?: string | undefined): Promise<Problem[]>;
|
||||
|
|
@ -891,6 +974,11 @@ export interface ToolExtras {
|
|||
llm: ILLM;
|
||||
fetch: FetchFunction;
|
||||
tool: Tool;
|
||||
toolCallId?: string;
|
||||
onPartialOutput?: (params: {
|
||||
toolCallId: string;
|
||||
contextItems: ContextItem[];
|
||||
}) => void;
|
||||
}
|
||||
|
||||
export interface Tool {
|
||||
|
|
@ -907,6 +995,7 @@ export interface Tool {
|
|||
isCurrently?: string;
|
||||
hasAlready?: string;
|
||||
readonly: boolean;
|
||||
isInstant?: boolean;
|
||||
uri?: string;
|
||||
faviconUrl?: string;
|
||||
group: string;
|
||||
|
|
@ -952,9 +1041,8 @@ export interface ModelDescription {
|
|||
model: string;
|
||||
apiKey?: string;
|
||||
|
||||
// continueProperties
|
||||
apiKeyLocation?: string;
|
||||
apiBase?: string;
|
||||
apiKeyLocation?: string;
|
||||
orgScopeId?: string | null;
|
||||
|
||||
onPremProxyUrl?: string | null;
|
||||
|
|
@ -963,15 +1051,16 @@ export interface ModelDescription {
|
|||
maxStopWords?: number;
|
||||
template?: TemplateType;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
systemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: { [key: string]: string };
|
||||
cacheBehavior?: CacheBehavior;
|
||||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
configurationStatus?: LLMConfigurationStatuses;
|
||||
}
|
||||
|
||||
export interface EmbedOptions {
|
||||
export interface JSONEmbedOptions {
|
||||
apiBase?: string;
|
||||
apiKey?: string;
|
||||
model?: string;
|
||||
|
|
@ -992,7 +1081,7 @@ export interface EmbedOptions {
|
|||
projectId?: string;
|
||||
}
|
||||
|
||||
export interface EmbeddingsProviderDescription extends EmbedOptions {
|
||||
export interface EmbeddingsProviderDescription extends JSONEmbedOptions {
|
||||
provider: string;
|
||||
}
|
||||
|
||||
|
|
@ -1131,6 +1220,7 @@ export type EditStatus =
|
|||
| "done";
|
||||
|
||||
export type ApplyStateStatus =
|
||||
| "not-started" // Apply state created but not necessarily streaming
|
||||
| "streaming" // Changes are being applied to the file
|
||||
| "done" // All changes have been applied, awaiting user to accept/reject
|
||||
| "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed"
|
||||
|
|
@ -1141,6 +1231,7 @@ export interface ApplyState {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
toolCallId?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
|
|
@ -1215,11 +1306,39 @@ export interface AnalyticsConfig {
|
|||
clientKey?: string;
|
||||
}
|
||||
|
||||
export interface JSONModelDescription {
|
||||
title: string;
|
||||
provider: string;
|
||||
model: string;
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
|
||||
contextLength?: number;
|
||||
maxStopWords?: number;
|
||||
template?: TemplateType;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
systemMessage?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
cacheBehavior?: CacheBehavior;
|
||||
|
||||
region?: string;
|
||||
profile?: string;
|
||||
modelArn?: string;
|
||||
apiType?: "openai" | "azure";
|
||||
apiVersion?: string;
|
||||
deployment?: string;
|
||||
projectId?: string;
|
||||
accountId?: string;
|
||||
aiGatewaySlug?: string;
|
||||
useLegacyCompletionsEndpoint?: boolean;
|
||||
deploymentId?: string;
|
||||
}
|
||||
|
||||
// config.json
|
||||
export interface SerializedContinueConfig {
|
||||
env?: string[];
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
models: JSONModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
|
|
@ -1230,7 +1349,7 @@ export interface SerializedContinueConfig {
|
|||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: EmbeddingsProviderDescription;
|
||||
tabAutocompleteModel?: ModelDescription | ModelDescription[];
|
||||
tabAutocompleteModel?: JSONModelDescription | JSONModelDescription[];
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
ui?: ContinueUIConfig;
|
||||
reranker?: RerankerDescription;
|
||||
|
|
@ -1250,11 +1369,11 @@ export type ContinueRcJson = Partial<SerializedContinueConfig> & {
|
|||
export interface Config {
|
||||
/** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://docs.continue.dev/telemetry */
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
/** Each entry in this array will originally be a ModelDescription, the same object from your config.json, but you may add CustomLLMs.
|
||||
/** Each entry in this array will originally be a JSONModelDescription, the same object from your config.json, but you may add CustomLLMs.
|
||||
* A CustomLLM requires you only to define an AsyncGenerator that calls the LLM and yields string updates. You can choose to define either `streamCompletion` or `streamChat` (or both).
|
||||
* Continue will do the rest of the work to construct prompt templates, handle context items, prune context, etc.
|
||||
*/
|
||||
models: (CustomLLM | ModelDescription)[];
|
||||
models: (CustomLLM | JSONModelDescription)[];
|
||||
/** A system message to be followed by all of your models */
|
||||
systemMessage?: string;
|
||||
/** The default completion options for all models */
|
||||
|
|
@ -1278,8 +1397,8 @@ export interface Config {
|
|||
/** The model that Continue will use for tab autocompletions. */
|
||||
tabAutocompleteModel?:
|
||||
| CustomLLM
|
||||
| ModelDescription
|
||||
| (CustomLLM | ModelDescription)[];
|
||||
| JSONModelDescription
|
||||
| (CustomLLM | JSONModelDescription)[];
|
||||
/** Options for tab autocomplete */
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
/** UI styles customization */
|
||||
|
|
@ -1296,8 +1415,7 @@ export interface Config {
|
|||
// in the actual Continue source code
|
||||
export interface ContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ILLM[];
|
||||
systemMessage?: string;
|
||||
// systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
slashCommands: SlashCommand[];
|
||||
|
|
@ -1312,7 +1430,7 @@ export interface ContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: string[];
|
||||
rules: RuleWithSource[];
|
||||
modelsByRole: Record<ModelRole, ILLM[]>;
|
||||
selectedModelByRole: Record<ModelRole, ILLM | null>;
|
||||
data?: DataDestination[];
|
||||
|
|
@ -1320,8 +1438,7 @@ export interface ContinueConfig {
|
|||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
// systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
slashCommands: SlashCommandDescription[];
|
||||
|
|
@ -1335,7 +1452,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: string[];
|
||||
rules: RuleWithSource[];
|
||||
usePlatform: boolean;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
modelsByRole: Record<ModelRole, ModelDescription[]>;
|
||||
|
|
@ -1382,4 +1499,20 @@ export type PackageDocsResult = {
|
|||
export interface TerminalOptions {
|
||||
reuseTerminal?: boolean;
|
||||
terminalName?: string;
|
||||
waitForCompletion?: boolean;
|
||||
}
|
||||
|
||||
export interface RuleWithSource {
|
||||
name?: string;
|
||||
slug?: string;
|
||||
source:
|
||||
| "default"
|
||||
| "model-chat-options"
|
||||
| "rules-block"
|
||||
| "json-systemMessage"
|
||||
| ".continuerules";
|
||||
globs?: string | string[];
|
||||
rule: string;
|
||||
description?: string;
|
||||
ruleFile?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceIn
|
|||
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
|
||||
|
||||
import { LLMError } from "../llm/index.js";
|
||||
import { getRootCause } from "../util/errors.js";
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
|
||||
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
|
||||
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
|
||||
|
|
@ -350,6 +352,10 @@ export class CodebaseIndexer {
|
|||
): IndexingProgressUpdate {
|
||||
console.log("error when indexing: ", err);
|
||||
if (err instanceof Error) {
|
||||
const cause = getRootCause(err);
|
||||
if (cause instanceof LLMError) {
|
||||
throw cause;
|
||||
}
|
||||
return this.errorToProgressUpdate(err);
|
||||
}
|
||||
return {
|
||||
|
|
@ -361,7 +367,8 @@ export class CodebaseIndexer {
|
|||
}
|
||||
|
||||
private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
|
||||
let errMsg: string = `${err}`;
|
||||
const cause = getRootCause(err);
|
||||
let errMsg: string = `${cause}`;
|
||||
let shouldClearIndexes = false;
|
||||
|
||||
// Check if any of the error regexes match
|
||||
|
|
|
|||
|
|
@ -1,55 +0,0 @@
|
|||
import { ILLM } from "../index.js";
|
||||
import Bedrock from "../llm/llms/Bedrock.js";
|
||||
import Cohere from "../llm/llms/Cohere.js";
|
||||
import DeepInfra from "../llm/llms/DeepInfra.js";
|
||||
import FreeTrial from "../llm/llms/FreeTrial.js";
|
||||
import FunctionNetwork from "../llm/llms/FunctionNetwork.js";
|
||||
import Gemini from "../llm/llms/Gemini.js";
|
||||
import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js";
|
||||
import LMStudio from "../llm/llms/LMStudio.js";
|
||||
import Mistral from "../llm/llms/Mistral.js";
|
||||
import NCompass from "../llm/llms/NCompass.js";
|
||||
import Nebius from "../llm/llms/Nebius.js";
|
||||
import Nvidia from "../llm/llms/Nvidia.js";
|
||||
import Ollama from "../llm/llms/Ollama.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import OVHcloud from "../llm/llms/OVHcloud.js";
|
||||
import SageMaker from "../llm/llms/SageMaker.js";
|
||||
import Scaleway from "../llm/llms/Scaleway.js";
|
||||
import SiliconFlow from "../llm/llms/SiliconFlow.js";
|
||||
import ContinueProxy from "../llm/llms/stubs/ContinueProxy.js";
|
||||
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider.js";
|
||||
import VertexAI from "../llm/llms/VertexAI.js";
|
||||
import Voyage from "../llm/llms/Voyage.js";
|
||||
import WatsonX from "../llm/llms/WatsonX.js";
|
||||
|
||||
type EmbeddingsProviderConstructor = new (...args: any[]) => ILLM;
|
||||
|
||||
export const allEmbeddingsProviders: Record<
|
||||
string,
|
||||
EmbeddingsProviderConstructor
|
||||
> = {
|
||||
sagemaker: SageMaker,
|
||||
bedrock: Bedrock,
|
||||
ollama: Ollama,
|
||||
"transformers.js": TransformersJsEmbeddingsProvider,
|
||||
openai: OpenAI,
|
||||
cohere: Cohere,
|
||||
"free-trial": FreeTrial,
|
||||
"function-network": FunctionNetwork,
|
||||
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
|
||||
gemini: Gemini,
|
||||
"continue-proxy": ContinueProxy,
|
||||
deepinfra: DeepInfra,
|
||||
ncompass: NCompass,
|
||||
nvidia: Nvidia,
|
||||
ovhcloud: OVHcloud,
|
||||
voyage: Voyage,
|
||||
mistral: Mistral,
|
||||
nebius: Nebius,
|
||||
vertexai: VertexAI,
|
||||
watsonx: WatsonX,
|
||||
lmstudio: LMStudio,
|
||||
siliconflow: SiliconFlow,
|
||||
scaleway: Scaleway,
|
||||
};
|
||||
|
|
@ -3,6 +3,7 @@
|
|||
// */
|
||||
// import { ConfigHandler } from "../../config/ConfigHandler.js";
|
||||
// import { SiteIndexingConfig } from "../../index.js";
|
||||
// import { LLMLogger } from "../../llm/logger.js";
|
||||
// import FileSystemIde from "../../util/filesystem.js";
|
||||
// import { editConfigJson } from "../../util/paths.js";
|
||||
|
||||
|
|
@ -38,7 +39,6 @@
|
|||
// const ideSettingsPromise = Promise.resolve({
|
||||
// remoteConfigSyncPeriod: 60,
|
||||
// userToken: "",
|
||||
// enableControlServerBeta: false,
|
||||
// continueTestEnvironment: "none" as const,
|
||||
// pauseCodebaseIndexOnStart: false,
|
||||
// ideSettings: {} as any,
|
||||
|
|
@ -48,7 +48,7 @@
|
|||
// configHandler = new ConfigHandler(
|
||||
// ide,
|
||||
// ideSettingsPromise,
|
||||
// async () => {},
|
||||
// new LLMLogger(),
|
||||
// Promise.resolve(undefined),
|
||||
// );
|
||||
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
|
|||
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
|
||||
|
||||
import type * as LanceType from "vectordb";
|
||||
import { LLMError } from "../../llm";
|
||||
import { DocsCache, SiteIndexingResults } from "./DocsCache";
|
||||
|
||||
// Purposefully lowercase because lancedb converts
|
||||
|
|
@ -64,6 +65,48 @@ export type AddParams = {
|
|||
favicon?: string;
|
||||
};
|
||||
|
||||
const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
newFailedDocs.push(siteIndexingConfig);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
||||
const removeFromFailedGlobalContext = (
|
||||
siteIndexingConfig: SiteIndexingConfig,
|
||||
) => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
||||
const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
return failedDocs.find((d) =>
|
||||
siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
};
|
||||
|
||||
const siteIndexingConfigsAreEqual = (
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
) => {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.faviconUrl === config2.faviconUrl &&
|
||||
config1.title === config2.title &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
);
|
||||
};
|
||||
|
||||
/*
|
||||
General process:
|
||||
- On config update:
|
||||
|
|
@ -379,6 +422,7 @@ export default class DocsService {
|
|||
return false;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line max-statements
|
||||
async indexAndAdd(
|
||||
siteIndexingConfig: SiteIndexingConfig,
|
||||
forceReindex: boolean = false,
|
||||
|
|
@ -433,12 +477,7 @@ export default class DocsService {
|
|||
|
||||
// If not force-reindexing and has failed with same config, don't reattempt
|
||||
if (!forceReindex) {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const hasFailed = failedDocs.find((d) =>
|
||||
this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
if (hasFailed) {
|
||||
if (hasIndexingFailed(siteIndexingConfig)) {
|
||||
console.log(
|
||||
`Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`,
|
||||
);
|
||||
|
|
@ -469,29 +508,20 @@ export default class DocsService {
|
|||
try {
|
||||
await provider.embed(["continue-test-run"]);
|
||||
} catch (e) {
|
||||
if (e instanceof LLMError) {
|
||||
// Report the error to the IDE
|
||||
this.messenger?.request("reportError", e);
|
||||
}
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `Failed to test embeddings connection. ${e}`,
|
||||
status: "failed",
|
||||
progress: 1,
|
||||
});
|
||||
console.error("Failed to test embeddings connection", e);
|
||||
return;
|
||||
}
|
||||
|
||||
const markFailedInGlobalContext = () => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
newFailedDocs.push(siteIndexingConfig);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
||||
const removeFromFailedGlobalContext = () => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
||||
try {
|
||||
this.docsIndexingQueue.add(startUrl);
|
||||
|
||||
|
|
@ -630,7 +660,7 @@ export default class DocsService {
|
|||
});
|
||||
|
||||
// void this.ide.showToast("info", `Failed to index ${startUrl}`);
|
||||
markFailedInGlobalContext();
|
||||
markFailedInGlobalContext(siteIndexingConfig);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -690,7 +720,7 @@ export default class DocsService {
|
|||
providers: ["docs"],
|
||||
});
|
||||
|
||||
removeFromFailedGlobalContext();
|
||||
removeFromFailedGlobalContext(siteIndexingConfig);
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`Error indexing docs at: ${siteIndexingConfig.startUrl}`,
|
||||
|
|
@ -711,7 +741,7 @@ export default class DocsService {
|
|||
status: "failed",
|
||||
progress: 1,
|
||||
});
|
||||
markFailedInGlobalContext();
|
||||
markFailedInGlobalContext(siteIndexingConfig);
|
||||
} finally {
|
||||
this.docsIndexingQueue.delete(startUrl);
|
||||
}
|
||||
|
|
@ -973,10 +1003,7 @@ export default class DocsService {
|
|||
(d) => d.startUrl === doc.startUrl,
|
||||
);
|
||||
|
||||
if (
|
||||
oldConfigDoc &&
|
||||
!this.siteIndexingConfigsAreEqual(oldConfigDoc, doc)
|
||||
) {
|
||||
if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
|
||||
changedDocs.push(doc);
|
||||
} else {
|
||||
if (forceReindex) {
|
||||
|
|
@ -1163,24 +1190,11 @@ export default class DocsService {
|
|||
);
|
||||
}
|
||||
|
||||
private siteIndexingConfigsAreEqual(
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
) {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.faviconUrl === config2.faviconUrl &&
|
||||
config1.title === config2.title &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
);
|
||||
}
|
||||
|
||||
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
|
||||
// Handles the case where a user has manually added the doc to config.json
|
||||
// so it already exists in the file
|
||||
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
|
||||
this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
|
||||
siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
|
||||
);
|
||||
|
||||
if (!doesEquivalentDocExist) {
|
||||
|
|
|
|||
|
|
@ -158,18 +158,21 @@ async function getAddRemoveForTag(
|
|||
const updateLastUpdated: PathAndCacheKey[] = [];
|
||||
|
||||
// First, group items by path and find latest timestamp for each
|
||||
const pathGroups = new Map<string, {
|
||||
latest: { lastUpdated: number, cacheKey: string },
|
||||
allVersions: Array<{ cacheKey: string }>
|
||||
}>();
|
||||
const pathGroups = new Map<
|
||||
string,
|
||||
{
|
||||
latest: { lastUpdated: number; cacheKey: string };
|
||||
allVersions: Array<{ cacheKey: string }>;
|
||||
}
|
||||
>();
|
||||
|
||||
for (const item of saved) {
|
||||
const { lastUpdated, path, cacheKey } = item;
|
||||
|
||||
|
||||
if (!pathGroups.has(path)) {
|
||||
pathGroups.set(path, {
|
||||
latest: { lastUpdated, cacheKey },
|
||||
allVersions: [{ cacheKey }]
|
||||
allVersions: [{ cacheKey }],
|
||||
});
|
||||
} else {
|
||||
const group = pathGroups.get(path)!;
|
||||
|
|
@ -530,6 +533,6 @@ export function truncateToLastNBytes(input: string, maxBytes: number): string {
|
|||
return input.substring(startIndex, input.length);
|
||||
}
|
||||
|
||||
export function truncateSqliteLikePattern(input: string) {
|
||||
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH);
|
||||
export function truncateSqliteLikePattern(input: string, safety: number = 100) {
|
||||
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ describe("walkDir functions", () => {
|
|||
);
|
||||
});
|
||||
|
||||
it("should handle onlyDirs option", async () => {
|
||||
it("should handle include option", async () => {
|
||||
addToTestDir([
|
||||
"src/",
|
||||
["src/file1.ts", "content1"],
|
||||
|
|
@ -109,7 +109,7 @@ describe("walkDir functions", () => {
|
|||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
onlyDirs: true,
|
||||
include: "dirs",
|
||||
},
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -10,10 +10,11 @@ import {
|
|||
} from "./ignore";
|
||||
|
||||
export interface WalkerOptions {
|
||||
onlyDirs?: boolean;
|
||||
include?: "dirs" | "files" | "both";
|
||||
returnRelativeUrisPaths?: boolean;
|
||||
source?: string;
|
||||
overrideDefaultIgnores?: Ignore;
|
||||
recursive?: boolean;
|
||||
}
|
||||
|
||||
type Entry = [string, FileType];
|
||||
|
|
@ -195,7 +196,7 @@ class DFSWalker {
|
|||
if (this.entryIsDirectory(entry)) {
|
||||
relPath = `${relPath}/`;
|
||||
} else {
|
||||
if (this.options.onlyDirs) {
|
||||
if (this.options.include === "dirs") {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
|
@ -221,19 +222,22 @@ class DFSWalker {
|
|||
}
|
||||
|
||||
if (this.entryIsDirectory(entry)) {
|
||||
stack.push({
|
||||
walkableEntry,
|
||||
ignoreContexts,
|
||||
});
|
||||
if (this.options.onlyDirs) {
|
||||
// when onlyDirs is enabled the walker will only return directory names
|
||||
if (this.options.recursive) {
|
||||
stack.push({
|
||||
walkableEntry,
|
||||
ignoreContexts,
|
||||
});
|
||||
}
|
||||
if (this.options.include !== "files") {
|
||||
// if yielding dirs or both, walker includes relative paths
|
||||
const trailingSlash = this.options.include === "dirs" ? "" : "/";
|
||||
if (this.options.returnRelativeUrisPaths) {
|
||||
yield walkableEntry.relativeUriPath;
|
||||
yield walkableEntry.relativeUriPath + trailingSlash;
|
||||
} else {
|
||||
yield walkableEntry.uri;
|
||||
yield walkableEntry.uri + trailingSlash;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} else if (this.options.include !== "dirs") {
|
||||
if (this.options.returnRelativeUrisPaths) {
|
||||
yield walkableEntry.relativeUriPath;
|
||||
} else {
|
||||
|
|
@ -257,8 +261,9 @@ class DFSWalker {
|
|||
}
|
||||
|
||||
const defaultOptions: WalkerOptions = {
|
||||
onlyDirs: false,
|
||||
include: "files",
|
||||
returnRelativeUrisPaths: false,
|
||||
recursive: true,
|
||||
};
|
||||
|
||||
export async function* walkDirAsync(
|
||||
|
|
|
|||
|
|
@ -96,6 +96,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
|
|||
"pixtral",
|
||||
"llama3.2",
|
||||
"llama-3.2",
|
||||
"llama4"
|
||||
];
|
||||
|
||||
function modelSupportsTools(modelDescription: ModelDescription) {
|
||||
|
|
@ -177,7 +178,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
|
|||
lower.includes("pplx") ||
|
||||
lower.includes("gemini") ||
|
||||
lower.includes("grok") ||
|
||||
lower.includes("moonshot")
|
||||
lower.includes("moonshot") ||
|
||||
lower.includes("mercury")
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
const DEFAULT_MAX_TOKENS = 4096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 8096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 8192;
|
||||
const DEFAULT_TEMPERATURE = 0.5;
|
||||
|
||||
const DEFAULT_ARGS = {
|
||||
|
|
@ -7,38 +7,21 @@ const DEFAULT_ARGS = {
|
|||
temperature: DEFAULT_TEMPERATURE,
|
||||
};
|
||||
|
||||
const GPT_4_CTX_LEN = 128_000;
|
||||
|
||||
const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
|
||||
"gpt-3.5-turbo": 4096,
|
||||
"gpt-3.5-turbo-0613": 4096,
|
||||
"gpt-3.5-turbo-16k": 16_384,
|
||||
"gpt-35-turbo-16k": 16_384,
|
||||
"gpt-35-turbo-0613": 4096,
|
||||
"gpt-35-turbo": 4096,
|
||||
"gpt-4": 4096,
|
||||
"gpt-4-32k": 32_000,
|
||||
"gpt-4-turbo-preview": 32_000,
|
||||
"gpt-4o": GPT_4_CTX_LEN,
|
||||
"gpt-4o-mini": GPT_4_CTX_LEN,
|
||||
"gpt-4-vision": GPT_4_CTX_LEN,
|
||||
"gpt-4-0125-preview": GPT_4_CTX_LEN,
|
||||
"gpt-4-1106-preview": GPT_4_CTX_LEN,
|
||||
};
|
||||
|
||||
const TOKEN_BUFFER_FOR_SAFETY = 350;
|
||||
const PROXY_URL = "http://localhost:65433";
|
||||
|
||||
const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
|
||||
const DEFAULT_MAX_BATCH_SIZE = 64;
|
||||
|
||||
export enum LLMConfigurationStatuses {
|
||||
VALID = "valid",
|
||||
MISSING_API_KEY = "missing-api-key",
|
||||
}
|
||||
|
||||
export {
|
||||
CONTEXT_LENGTH_FOR_MODEL,
|
||||
DEFAULT_ARGS,
|
||||
DEFAULT_CONTEXT_LENGTH,
|
||||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
PROXY_URL,
|
||||
TOKEN_BUFFER_FOR_SAFETY,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,24 +1,73 @@
|
|||
import { ChatHistoryItem, ChatMessage, MessagePart } from "../";
|
||||
import {
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
RuleWithSource,
|
||||
TextMessagePart,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
} from "../";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { normalizeToMessageParts } from "../util/messageContent";
|
||||
import { isUserOrToolMsg } from "./messages";
|
||||
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
|
||||
|
||||
const DEFAULT_SYSTEM_MESSAGE = `<important_rules>
|
||||
Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'.
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
Always include the language and file name in the info string when you write code blocks.
|
||||
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
|
||||
|
||||
When addressing code modification requests, present a concise code snippet that
|
||||
emphasizes only the necessary changes and uses abbreviated placeholders for
|
||||
unmodified sections. For example:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... rest of code here ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of code here ...
|
||||
|
||||
{{ another modification }}
|
||||
|
||||
// ... rest of code here ...
|
||||
\`\`\`
|
||||
|
||||
In existing files, you should always restate the function or class that the snippet belongs to:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... rest of code here ...
|
||||
|
||||
function exampleFunction() {
|
||||
// ... rest of code here ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of code here ...
|
||||
}
|
||||
|
||||
// ... rest of code here ...
|
||||
\`\`\`
|
||||
|
||||
Since users have access to their complete file, they prefer reading only the
|
||||
relevant modifications. It's perfectly acceptable to omit unmodified portions
|
||||
at the beginning, middle, or end of files using these "lazy" comments. Only
|
||||
provide the complete file when explicitly requested. Include a concise explanation
|
||||
of changes unless the user specifically asks for code only.
|
||||
</important_rules>`;
|
||||
|
||||
const CANCELED_TOOL_CALL_MESSAGE =
|
||||
"This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool.";
|
||||
|
||||
export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] {
|
||||
export function constructMessages(
|
||||
history: ChatHistoryItem[],
|
||||
baseChatSystemMessage: string | undefined,
|
||||
rules: RuleWithSource[],
|
||||
): ChatMessage[] {
|
||||
const filteredHistory = history.filter(
|
||||
(item) => item.message.role !== "system",
|
||||
);
|
||||
const msgs: ChatMessage[] = [];
|
||||
|
||||
msgs.push({
|
||||
role: "system",
|
||||
content: DEFAULT_SYSTEM_MESSAGE,
|
||||
});
|
||||
|
||||
for (let i = 0; i < filteredHistory.length; i++) {
|
||||
const historyItem = filteredHistory[i];
|
||||
|
||||
|
|
@ -26,26 +75,43 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] {
|
|||
// Gather context items for user messages
|
||||
let content = normalizeToMessageParts(historyItem.message);
|
||||
|
||||
const ctxItems = historyItem.contextItems.map((ctxItem) => {
|
||||
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
|
||||
});
|
||||
const ctxItems = historyItem.contextItems
|
||||
.map((ctxItem) => {
|
||||
return {
|
||||
type: "text",
|
||||
text: `${ctxItem.content}\n`,
|
||||
} as TextMessagePart;
|
||||
})
|
||||
.filter((part) => !!part.text.trim());
|
||||
|
||||
content = [...ctxItems, ...content];
|
||||
msgs.push({
|
||||
...historyItem.message,
|
||||
content,
|
||||
});
|
||||
} else if (historyItem.toolCallState?.status === "canceled") {
|
||||
// Canceled tool call
|
||||
msgs.push({
|
||||
...historyItem.message,
|
||||
content: CANCELED_TOOL_CALL_MESSAGE,
|
||||
});
|
||||
} else {
|
||||
msgs.push(historyItem.message);
|
||||
}
|
||||
}
|
||||
|
||||
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
|
||||
| UserChatMessage
|
||||
| ToolResultChatMessage
|
||||
| undefined;
|
||||
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
rules,
|
||||
userMessage: lastUserMsg,
|
||||
});
|
||||
|
||||
if (systemMessage.trim()) {
|
||||
msgs.unshift({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
|
||||
// Remove the "id" from all of the messages
|
||||
return msgs.map((msg) => {
|
||||
const { id, ...rest } = msg as any;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// @ts-nocheck
|
||||
// Generated by continue
|
||||
import { ChatMessage, MessagePart } from "../index.js";
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
|
||||
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
|
||||
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
|
||||
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
|
|
@ -9,8 +9,14 @@ import {
|
|||
LlamaAsyncEncoder,
|
||||
} from "./asyncEncoder.js";
|
||||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
import {
|
||||
addSpaceToAnyEmptyMessages,
|
||||
chatMessageIsEmpty,
|
||||
flattenMessages,
|
||||
isUserOrToolMsg,
|
||||
messageHasToolCallId,
|
||||
} from "./messages.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
|
|
@ -118,29 +124,49 @@ function countTokens(
|
|||
}
|
||||
}
|
||||
|
||||
function messageHasToolCalls(msg: ChatMessage): boolean {
|
||||
return msg.role === "assistant" && !!msg.toolCalls;
|
||||
}
|
||||
// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10
|
||||
function countToolsTokens(tools: Tool[], modelName: string): number {
|
||||
const count = (value: string) =>
|
||||
encodingForModel(modelName).encode(value).length;
|
||||
|
||||
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
|
||||
const flattened: ChatMessage[] = [];
|
||||
let numTokens = 12;
|
||||
|
||||
for (let i = 0; i < msgs.length; i++) {
|
||||
const msg = msgs[i];
|
||||
|
||||
if (
|
||||
flattened.length > 0 &&
|
||||
flattened[flattened.length - 1].role === msg.role &&
|
||||
!messageHasToolCalls(msg) &&
|
||||
!messageHasToolCalls(flattened[flattened.length - 1])
|
||||
) {
|
||||
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
|
||||
} else {
|
||||
flattened.push(msg);
|
||||
for (const tool of tools) {
|
||||
let functionTokens = count(tool.function.name);
|
||||
if (tool.function.description) {
|
||||
functionTokens += count(tool.function.description);
|
||||
}
|
||||
const props = tool.function.parameters?.properties;
|
||||
if (props) {
|
||||
for (const key in props) {
|
||||
functionTokens += count(key);
|
||||
const fields = props[key];
|
||||
if (fields) {
|
||||
const fieldType = fields["type"];
|
||||
const fieldDesc = fields["description"];
|
||||
const fieldEnum = fields["enum"];
|
||||
if (fieldType && typeof fieldType === "string") {
|
||||
functionTokens += 2;
|
||||
functionTokens += count(fieldType);
|
||||
}
|
||||
if (fieldDesc && typeof fieldDesc === "string") {
|
||||
functionTokens += 2;
|
||||
functionTokens += count(fieldDesc);
|
||||
}
|
||||
if (fieldEnum && Array.isArray(fieldEnum)) {
|
||||
functionTokens -= 3;
|
||||
for (const e of fieldEnum) {
|
||||
functionTokens += 3;
|
||||
functionTokens += typeof e === "string" ? count(e) : 5;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
numTokens += functionTokens;
|
||||
}
|
||||
|
||||
return flattened;
|
||||
return numTokens + 12;
|
||||
}
|
||||
|
||||
function countChatMessageTokens(
|
||||
|
|
@ -150,8 +176,38 @@ function countChatMessageTokens(
|
|||
// Doing simpler, safer version of what is here:
|
||||
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
|
||||
// every message follows <|im_start|>{role/name}\n{content}<|end|>\n
|
||||
const TOKENS_PER_MESSAGE: number = 4;
|
||||
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
|
||||
const BASE_TOKENS = 4;
|
||||
const TOOL_CALL_EXTRA_TOKENS = 10;
|
||||
const TOOL_OUTPUT_EXTRA_TOKENS = 10;
|
||||
let tokens = BASE_TOKENS;
|
||||
|
||||
if (chatMessage.content) {
|
||||
tokens += countTokens(chatMessage.content, modelName);
|
||||
}
|
||||
|
||||
if ("toolCalls" in chatMessage && chatMessage.toolCalls) {
|
||||
for (const call of chatMessage.toolCalls) {
|
||||
tokens += TOOL_CALL_EXTRA_TOKENS;
|
||||
tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this
|
||||
}
|
||||
}
|
||||
|
||||
if (chatMessage.role === "thinking") {
|
||||
if (chatMessage.redactedThinking) {
|
||||
tokens += countTokens(chatMessage.redactedThinking, modelName);
|
||||
}
|
||||
if (chatMessage.signature) {
|
||||
tokens += countTokens(chatMessage.signature, modelName);
|
||||
}
|
||||
}
|
||||
|
||||
if (chatMessage.role === "tool") {
|
||||
tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety
|
||||
if (chatMessage.toolCallId) {
|
||||
tokens += countTokens(chatMessage.toolCallId, modelName);
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function pruneLinesFromTop(
|
||||
|
|
@ -212,6 +268,20 @@ function pruneStringFromTop(
|
|||
return encoding.decode(tokens.slice(tokens.length - maxTokens));
|
||||
}
|
||||
|
||||
const MAX_TOKEN_SAFETY_BUFFER = 1000;
|
||||
const TOKEN_SAFETY_PROPORTION = 0.02;
|
||||
function getTokenCountingBufferSafety(contextLength: number) {
|
||||
return Math.min(
|
||||
MAX_TOKEN_SAFETY_BUFFER,
|
||||
contextLength * TOKEN_SAFETY_PROPORTION,
|
||||
);
|
||||
}
|
||||
|
||||
const MIN_RESPONSE_TOKENS = 1000;
|
||||
function getMinResponseTokens(maxTokens: number) {
|
||||
return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
|
||||
}
|
||||
|
||||
function pruneRawPromptFromTop(
|
||||
modelName: string,
|
||||
contextLength: number,
|
||||
|
|
@ -219,233 +289,35 @@ function pruneRawPromptFromTop(
|
|||
tokensForCompletion: number,
|
||||
): string {
|
||||
const maxTokens =
|
||||
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
|
||||
contextLength -
|
||||
tokensForCompletion -
|
||||
getTokenCountingBufferSafety(contextLength);
|
||||
return pruneStringFromTop(modelName, maxTokens, prompt);
|
||||
}
|
||||
|
||||
function pruneRawPromptFromBottom(
|
||||
modelName: string,
|
||||
contextLength: number,
|
||||
prompt: string,
|
||||
tokensForCompletion: number,
|
||||
): string {
|
||||
const maxTokens =
|
||||
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
|
||||
return pruneStringFromBottom(modelName, maxTokens, prompt);
|
||||
}
|
||||
|
||||
function summarize(message: ChatMessage): string {
|
||||
return `${renderChatMessage(message).substring(0, 100)}...`;
|
||||
}
|
||||
|
||||
function pruneChatHistory(
|
||||
modelName: string,
|
||||
chatHistory: ChatMessage[],
|
||||
contextLength: number,
|
||||
tokensForCompletion: number,
|
||||
): ChatMessage[] {
|
||||
let totalTokens =
|
||||
tokensForCompletion +
|
||||
chatHistory.reduce((acc, message) => {
|
||||
return acc + countChatMessageTokens(modelName, message);
|
||||
}, 0);
|
||||
|
||||
// 0. Prune any messages that take up more than 1/3 of the context length
|
||||
const longestMessages = [...chatHistory];
|
||||
longestMessages.sort((a, b) => b.content.length - a.content.length);
|
||||
|
||||
const longerThanOneThird = longestMessages.filter(
|
||||
(message: ChatMessage) =>
|
||||
countTokens(message.content, modelName) > contextLength / 3,
|
||||
);
|
||||
const distanceFromThird = longerThanOneThird.map(
|
||||
(message: ChatMessage) =>
|
||||
countTokens(message.content, modelName) - contextLength / 3,
|
||||
);
|
||||
|
||||
for (let i = 0; i < longerThanOneThird.length; i++) {
|
||||
// Prune line-by-line from the top
|
||||
const message = longerThanOneThird[i];
|
||||
const content = renderChatMessage(message);
|
||||
const deltaNeeded = totalTokens - contextLength;
|
||||
const delta = Math.min(deltaNeeded, distanceFromThird[i]);
|
||||
message.content = pruneStringFromTop(
|
||||
modelName,
|
||||
countTokens(message.content, modelName) - delta,
|
||||
content,
|
||||
);
|
||||
totalTokens -= delta;
|
||||
}
|
||||
|
||||
// 1. Replace beyond last 5 messages with summary
|
||||
let i = 0;
|
||||
while (totalTokens > contextLength && i < chatHistory.length - 5) {
|
||||
const message = chatHistory[0];
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
totalTokens += countTokens(summarize(message), modelName);
|
||||
message.content = summarize(message);
|
||||
i++;
|
||||
}
|
||||
|
||||
// 2. Remove entire messages until the last 5
|
||||
while (
|
||||
chatHistory.length > 5 &&
|
||||
totalTokens > contextLength &&
|
||||
chatHistory.length > 0
|
||||
) {
|
||||
const message = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
}
|
||||
|
||||
// 3. Truncate message in the last 5, except last 1
|
||||
i = 0;
|
||||
while (
|
||||
totalTokens > contextLength &&
|
||||
chatHistory.length > 0 &&
|
||||
i < chatHistory.length - 1
|
||||
) {
|
||||
const message = chatHistory[i];
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
totalTokens += countTokens(summarize(message), modelName);
|
||||
message.content = summarize(message);
|
||||
i++;
|
||||
}
|
||||
|
||||
// 4. Remove entire messages in the last 5, except last 1
|
||||
while (totalTokens > contextLength && chatHistory.length > 1) {
|
||||
// If tool call/response detected prune both (can't have response with no call)
|
||||
// TODO prune lines from tool response before pruning both messages
|
||||
if (
|
||||
chatHistory.length > 2 &&
|
||||
messageHasToolCalls(chatHistory[0]) &&
|
||||
chatHistory[1].role === "tool"
|
||||
) {
|
||||
const firstMessage = chatHistory.shift()!;
|
||||
const secondMessage = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(firstMessage.content, modelName);
|
||||
totalTokens -= countTokens(secondMessage.content, modelName);
|
||||
} else {
|
||||
const message = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Truncate last message
|
||||
if (totalTokens > contextLength && chatHistory.length > 0) {
|
||||
const message = chatHistory[0];
|
||||
message.content = pruneRawPromptFromTop(
|
||||
modelName,
|
||||
contextLength,
|
||||
renderChatMessage(message),
|
||||
tokensForCompletion,
|
||||
);
|
||||
totalTokens = contextLength;
|
||||
}
|
||||
return chatHistory;
|
||||
}
|
||||
|
||||
function messageIsEmpty(message: ChatMessage): boolean {
|
||||
if (typeof message.content === "string") {
|
||||
return message.content.trim() === "";
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content.every(
|
||||
(item) => item.type === "text" && item.text?.trim() === "",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] {
|
||||
return messages.map((message) => {
|
||||
if (messageIsEmpty(message)) {
|
||||
message.content = " ";
|
||||
}
|
||||
return message;
|
||||
});
|
||||
}
|
||||
|
||||
function chatMessageIsEmpty(message: ChatMessage): boolean {
|
||||
switch (message.role) {
|
||||
case "system":
|
||||
case "user":
|
||||
return (
|
||||
typeof message.content === "string" && message.content.trim() === ""
|
||||
);
|
||||
case "assistant":
|
||||
return (
|
||||
typeof message.content === "string" &&
|
||||
message.content.trim() === "" &&
|
||||
!message.toolCalls
|
||||
);
|
||||
case "thinking":
|
||||
case "tool":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function compileChatMessages(
|
||||
modelName: string,
|
||||
msgs: ChatMessage[] | undefined,
|
||||
contextLength: number,
|
||||
maxTokens: number,
|
||||
supportsImages: boolean,
|
||||
prompt: string | undefined = undefined,
|
||||
functions: any[] | undefined = undefined,
|
||||
systemMessage: string | undefined = undefined,
|
||||
): ChatMessage[] {
|
||||
let msgsCopy = msgs
|
||||
? msgs
|
||||
.map((msg) => ({ ...msg }))
|
||||
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
|
||||
: [];
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
||||
if (prompt) {
|
||||
const promptMsg: ChatMessage = {
|
||||
role: "user",
|
||||
content: prompt,
|
||||
};
|
||||
msgsCopy.push(promptMsg);
|
||||
}
|
||||
|
||||
if (
|
||||
(systemMessage && systemMessage.trim() !== "") ||
|
||||
msgs?.[0]?.role === "system"
|
||||
) {
|
||||
let content = "";
|
||||
if (msgs?.[0]?.role === "system") {
|
||||
content = renderChatMessage(msgs?.[0]);
|
||||
}
|
||||
if (systemMessage && systemMessage.trim() !== "") {
|
||||
const shouldAddNewLines = content !== "";
|
||||
if (shouldAddNewLines) {
|
||||
content += "\n\n";
|
||||
}
|
||||
content += systemMessage;
|
||||
}
|
||||
const systemChatMsg: ChatMessage = {
|
||||
role: "system",
|
||||
content,
|
||||
};
|
||||
// Insert as second to last
|
||||
// Later moved to top, but want second-priority to last user message
|
||||
msgsCopy.splice(-1, 0, systemChatMsg);
|
||||
}
|
||||
|
||||
let functionTokens = 0;
|
||||
if (functions) {
|
||||
for (const func of functions) {
|
||||
functionTokens += countTokens(JSON.stringify(func), modelName);
|
||||
}
|
||||
}
|
||||
|
||||
if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) {
|
||||
throw new Error(
|
||||
`maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`,
|
||||
);
|
||||
}
|
||||
/*
|
||||
Goal: reconcile chat messages with available context length
|
||||
Guidelines:
|
||||
- Always keep last user message, system message, and tools
|
||||
- Never allow tool output without the corresponding tool call
|
||||
- Remove older messages first
|
||||
*/
|
||||
function compileChatMessages({
|
||||
modelName,
|
||||
msgs,
|
||||
contextLength,
|
||||
maxTokens,
|
||||
supportsImages,
|
||||
tools,
|
||||
}: {
|
||||
modelName: string;
|
||||
msgs: ChatMessage[];
|
||||
contextLength: number;
|
||||
maxTokens: number;
|
||||
supportsImages: boolean;
|
||||
tools?: Tool[];
|
||||
}): ChatMessage[] {
|
||||
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
|
||||
|
||||
// If images not supported, convert MessagePart[] to string
|
||||
if (!supportsImages) {
|
||||
|
|
@ -457,20 +329,118 @@ function compileChatMessages(
|
|||
}
|
||||
}
|
||||
|
||||
const history = pruneChatHistory(
|
||||
modelName,
|
||||
msgsCopy,
|
||||
contextLength,
|
||||
functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY,
|
||||
);
|
||||
// Extract system message
|
||||
const systemMsg = msgsCopy.find((msg) => msg.role === "system");
|
||||
msgsCopy = msgsCopy.filter((msg) => msg.role !== "system");
|
||||
|
||||
if (history.length >= 2 && history[history.length - 2].role === "system") {
|
||||
const movedSystemMessage = history.splice(-2, 1)[0];
|
||||
history.unshift(movedSystemMessage);
|
||||
// Remove any empty messages or non-user/tool trailing messages
|
||||
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
||||
while (msgsCopy.length > 1) {
|
||||
if (isUserOrToolMsg(msgsCopy.at(-1))) {
|
||||
break;
|
||||
}
|
||||
msgsCopy.pop();
|
||||
}
|
||||
|
||||
const flattenedHistory = flattenMessages(history);
|
||||
const lastUserOrToolMsg = msgsCopy.pop();
|
||||
if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
|
||||
throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
|
||||
}
|
||||
|
||||
let lastToolCallsMsg: ChatMessage | undefined = undefined;
|
||||
if (lastUserOrToolMsg.role === "tool") {
|
||||
lastToolCallsMsg = msgsCopy.pop();
|
||||
if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
|
||||
throw new Error(
|
||||
`Error parsing chat history: tool call found to match tool output for id ${lastUserOrToolMsg.toolCallId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
|
||||
if (lastToolCallsMsg) {
|
||||
lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
|
||||
}
|
||||
|
||||
// System message
|
||||
let systemMsgTokens = 0;
|
||||
if (systemMsg) {
|
||||
systemMsgTokens = countChatMessageTokens(modelName, systemMsg);
|
||||
}
|
||||
|
||||
// Tools
|
||||
let toolTokens = 0;
|
||||
if (tools) {
|
||||
toolTokens = countToolsTokens(tools, modelName);
|
||||
}
|
||||
|
||||
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
|
||||
const minOutputTokens = getMinResponseTokens(maxTokens);
|
||||
|
||||
let inputTokensAvailable = contextLength;
|
||||
|
||||
// Leave space for output/safety
|
||||
inputTokensAvailable -= countingSafetyBuffer;
|
||||
inputTokensAvailable -= minOutputTokens;
|
||||
|
||||
// Non-negotiable messages
|
||||
inputTokensAvailable -= toolTokens;
|
||||
inputTokensAvailable -= systemMsgTokens;
|
||||
inputTokensAvailable -= lastMessagesTokens;
|
||||
|
||||
// Make sure there's enough context for the non-excludable items
|
||||
if (inputTokensAvailable < 0) {
|
||||
throw new Error(
|
||||
`Not enough context available to include the system message, last user message, and tools.
|
||||
There must be at least ${minOutputTokens} tokens remaining for output.
|
||||
Request had the following token counts:
|
||||
- contextLength: ${contextLength}
|
||||
- counting safety buffer: ${countingSafetyBuffer}
|
||||
- tools: ~${toolTokens}
|
||||
- system message: ~${systemMsgTokens}
|
||||
- last user or tool + tool call message tokens: ~${lastMessagesTokens}
|
||||
- max output tokens: ${maxTokens}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Now remove messages till we're under the limit
|
||||
let currentTotal = 0;
|
||||
const historyWithTokens = msgsCopy.map((message) => {
|
||||
const tokens = countChatMessageTokens(modelName, message);
|
||||
currentTotal += tokens;
|
||||
return {
|
||||
...message,
|
||||
tokens,
|
||||
};
|
||||
});
|
||||
|
||||
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
|
||||
const message = historyWithTokens.shift()!;
|
||||
currentTotal -= message.tokens;
|
||||
|
||||
// At this point make sure no latent tool response without corresponding call
|
||||
while (historyWithTokens[0]?.role === "tool") {
|
||||
const message = historyWithTokens.shift()!;
|
||||
currentTotal -= message.tokens;
|
||||
}
|
||||
}
|
||||
|
||||
// Now reassemble
|
||||
const reassembled: ChatMessage[] = [];
|
||||
if (systemMsg) {
|
||||
reassembled.push(systemMsg);
|
||||
}
|
||||
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
|
||||
if (lastToolCallsMsg) {
|
||||
reassembled.push(lastToolCallsMsg);
|
||||
}
|
||||
reassembled.push(lastUserOrToolMsg);
|
||||
|
||||
// Flatten the messages (combines adjacent similar messages)
|
||||
const flattenedHistory = flattenMessages(reassembled);
|
||||
return flattenedHistory;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ChatMessage, LLMOptions } from "..";
|
||||
|
||||
import { BaseLLM } from ".";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
class DummyLLM extends BaseLLM {
|
||||
static providerName = "openai";
|
||||
|
|
@ -30,11 +31,10 @@ describe("BaseLLM", () => {
|
|||
const templatMessagesFunction = (messages: ChatMessage[]) => {
|
||||
return messages[0]?.content.toString() ?? "";
|
||||
};
|
||||
const writeLogFunction = async () => {};
|
||||
const llmLogger = new LLMLogger();
|
||||
const options: LLMOptions = {
|
||||
model: "gpt-3.5-turbo",
|
||||
uniqueId: "testId",
|
||||
systemMessage: "Test System Message",
|
||||
contextLength: 1024,
|
||||
completionOptions: {
|
||||
model: "some-model",
|
||||
|
|
@ -43,7 +43,7 @@ describe("BaseLLM", () => {
|
|||
requestOptions: {},
|
||||
promptTemplates: {},
|
||||
templateMessages: templatMessagesFunction,
|
||||
writeLog: writeLogFunction,
|
||||
logger: llmLogger,
|
||||
llmRequestHook: () => {},
|
||||
apiKey: "testApiKey",
|
||||
aiGatewaySlug: "testSlug",
|
||||
|
|
@ -61,13 +61,12 @@ describe("BaseLLM", () => {
|
|||
expect(instance.title).toBeDefined();
|
||||
expect(instance.uniqueId).toBe("testId");
|
||||
expect(instance.model).toBe("gpt-3.5-turbo");
|
||||
expect(instance.systemMessage).toBe("Test System Message");
|
||||
expect(instance.contextLength).toBe(1024);
|
||||
expect(instance.completionOptions.maxTokens).toBe(150);
|
||||
expect(instance.requestOptions).toEqual({});
|
||||
expect(instance.promptTemplates).toEqual({});
|
||||
expect(instance.templateMessages).toEqual(templatMessagesFunction);
|
||||
expect(instance.writeLog).toBe(writeLogFunction);
|
||||
expect(instance.logger).toBe(llmLogger);
|
||||
expect(instance.apiKey).toBe("testApiKey");
|
||||
expect(instance.aiGatewaySlug).toBe("testSlug");
|
||||
expect(instance.apiBase).toBe("https://api.example.com/");
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ import {
|
|||
Chunk,
|
||||
CompletionOptions,
|
||||
ILLM,
|
||||
ILLMInteractionLog,
|
||||
ILLMLogger,
|
||||
LLMFullCompletionOptions,
|
||||
LLMOptions,
|
||||
ModelCapability,
|
||||
|
|
@ -38,12 +40,12 @@ import {
|
|||
modelSupportsImages,
|
||||
} from "./autodetect.js";
|
||||
import {
|
||||
CONTEXT_LENGTH_FOR_MODEL,
|
||||
DEFAULT_ARGS,
|
||||
DEFAULT_CONTEXT_LENGTH,
|
||||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
LLMConfigurationStatuses,
|
||||
} from "./constants.js";
|
||||
import {
|
||||
compileChatMessages,
|
||||
|
|
@ -69,9 +71,11 @@ export class LLMError extends Error {
|
|||
}
|
||||
|
||||
export function isModelInstaller(provider: any): provider is ModelInstaller {
|
||||
return provider && typeof provider.installModel === "function";
|
||||
return provider && typeof provider.installModel === "function" && typeof provider.isInstallingModel === "function";;
|
||||
}
|
||||
|
||||
type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
|
||||
|
||||
export abstract class BaseLLM implements ILLM {
|
||||
static providerName: string;
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
|
||||
|
|
@ -121,7 +125,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
model: string;
|
||||
|
||||
title?: string;
|
||||
systemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
contextLength: number;
|
||||
maxStopWords?: number | undefined;
|
||||
completionOptions: CompletionOptions;
|
||||
|
|
@ -129,7 +133,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
template?: TemplateType;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
|
||||
|
|
@ -188,7 +192,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
this.title = options.title;
|
||||
this.uniqueId = options.uniqueId ?? "None";
|
||||
this.systemMessage = options.systemMessage;
|
||||
this.baseChatSystemMessage = options.baseChatSystemMessage;
|
||||
this.contextLength =
|
||||
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
|
||||
this.maxStopWords = options.maxStopWords ?? this.maxStopWords;
|
||||
|
|
@ -219,7 +223,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
options.template,
|
||||
) ??
|
||||
undefined;
|
||||
this.writeLog = options.writeLog;
|
||||
this.logger = options.logger;
|
||||
this.llmRequestHook = options.llmRequestHook;
|
||||
this.apiKey = options.apiKey;
|
||||
|
||||
|
|
@ -259,6 +263,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
|
||||
}
|
||||
|
||||
getConfigurationStatus() {
|
||||
return LLMConfigurationStatuses.VALID;
|
||||
}
|
||||
|
||||
protected createOpenAiAdapter() {
|
||||
return constructLlmApi({
|
||||
provider: this.providerName as any,
|
||||
|
|
@ -272,88 +280,29 @@ export abstract class BaseLLM implements ILLM {
|
|||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
private _compileChatMessages(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
functions?: any[],
|
||||
) {
|
||||
let contextLength = this.contextLength;
|
||||
if (
|
||||
options.model !== this.model &&
|
||||
options.model in CONTEXT_LENGTH_FOR_MODEL
|
||||
) {
|
||||
contextLength =
|
||||
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
|
||||
}
|
||||
|
||||
return compileChatMessages(
|
||||
options.model,
|
||||
messages,
|
||||
contextLength,
|
||||
options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
this.supportsImages(),
|
||||
undefined,
|
||||
functions,
|
||||
this.systemMessage,
|
||||
);
|
||||
}
|
||||
|
||||
private _getSystemMessage(): string | undefined {
|
||||
// TODO: Merge with config system message
|
||||
return this.systemMessage;
|
||||
}
|
||||
|
||||
private _templatePromptLikeMessages(prompt: string): string {
|
||||
if (!this.templateMessages) {
|
||||
return prompt;
|
||||
}
|
||||
|
||||
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
|
||||
// NOTE system message no longer supported here
|
||||
|
||||
const systemMessage = this._getSystemMessage();
|
||||
if (systemMessage) {
|
||||
msgs.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
|
||||
|
||||
return this.templateMessages(msgs);
|
||||
}
|
||||
|
||||
private _compilePromptForLog(
|
||||
prompt: string,
|
||||
completionOptions: CompletionOptions,
|
||||
): string {
|
||||
const completionOptionsLog = JSON.stringify(
|
||||
{
|
||||
contextLength: this.contextLength,
|
||||
...completionOptions,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
|
||||
let requestOptionsLog = "";
|
||||
if (this.requestOptions) {
|
||||
requestOptionsLog = JSON.stringify(this.requestOptions, null, 2);
|
||||
}
|
||||
|
||||
return (
|
||||
"##### Completion options #####\n" +
|
||||
completionOptionsLog +
|
||||
(requestOptionsLog
|
||||
? "\n\n##### Request options #####\n" + requestOptionsLog
|
||||
: "") +
|
||||
"\n\n##### Prompt #####\n" +
|
||||
prompt
|
||||
);
|
||||
}
|
||||
|
||||
private _logTokensGenerated(
|
||||
private _logEnd(
|
||||
model: string,
|
||||
prompt: string,
|
||||
completion: string,
|
||||
) {
|
||||
thinking: string | undefined,
|
||||
interaction: ILLMInteractionLog | undefined,
|
||||
error?: any,
|
||||
): InteractionStatus {
|
||||
let promptTokens = this.countTokens(prompt);
|
||||
let generatedTokens = this.countTokens(completion);
|
||||
let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
|
||||
|
||||
void Telemetry.capture(
|
||||
"tokens_generated",
|
||||
|
|
@ -382,6 +331,37 @@ export abstract class BaseLLM implements ILLM {
|
|||
generatedTokens: generatedTokens,
|
||||
},
|
||||
});
|
||||
|
||||
if (error !== undefined) {
|
||||
if (error === "cancel" || error.name === "AbortError") {
|
||||
interaction?.logItem({
|
||||
kind: "cancel",
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
});
|
||||
return "cancelled";
|
||||
} else {
|
||||
console.log(error);
|
||||
interaction?.logItem({
|
||||
kind: "error",
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
});
|
||||
return "error";
|
||||
}
|
||||
} else {
|
||||
interaction?.logItem({
|
||||
kind: "success",
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
});
|
||||
return "success";
|
||||
}
|
||||
}
|
||||
|
||||
fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
|
|
@ -462,11 +442,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
//if e instance of LLMError, rethrow
|
||||
if (e instanceof LLMError) {
|
||||
throw e;
|
||||
}
|
||||
throw new Error(e.message);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
return withExponentialBackoff<Response>(
|
||||
|
|
@ -541,52 +517,89 @@ export abstract class BaseLLM implements ILLM {
|
|||
): AsyncGenerator<string> {
|
||||
const { completionOptions, logEnabled } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
? this.logger?.createInteractionLog()
|
||||
: undefined;
|
||||
let status: InteractionStatus = "in_progress";
|
||||
|
||||
const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
|
||||
if (logEnabled) {
|
||||
if (this.writeLog) {
|
||||
await this.writeLog(
|
||||
this._compilePromptForLog(fimLog, completionOptions),
|
||||
);
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "startFim",
|
||||
prefix,
|
||||
suffix,
|
||||
options: completionOptions,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, fimLog);
|
||||
}
|
||||
}
|
||||
|
||||
let completion = "";
|
||||
|
||||
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
|
||||
const stream = this.openaiAdapter.fimStream(
|
||||
toFimBody(prefix, suffix, completionOptions),
|
||||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
const content = renderChatMessage(result);
|
||||
completion += content;
|
||||
yield content;
|
||||
try {
|
||||
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
|
||||
const stream = this.openaiAdapter.fimStream(
|
||||
toFimBody(prefix, suffix, completionOptions),
|
||||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
const content = renderChatMessage(result);
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: content,
|
||||
});
|
||||
completion += content;
|
||||
yield content;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for await (const chunk of this._streamFim(
|
||||
prefix,
|
||||
suffix,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk,
|
||||
});
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for await (const chunk of this._streamFim(
|
||||
prefix,
|
||||
suffix,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
fimLog,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
fimLog,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status === "in_progress") {
|
||||
this._logEnd(
|
||||
completionOptions.model,
|
||||
fimLog,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this._logTokensGenerated(completionOptions.model, fimLog, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
}
|
||||
|
||||
return {
|
||||
prompt: fimLog,
|
||||
completion,
|
||||
|
|
@ -601,6 +614,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
) {
|
||||
const { completionOptions, logEnabled, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
? this.logger?.createInteractionLog()
|
||||
: undefined;
|
||||
let status: InteractionStatus = "in_progress";
|
||||
|
||||
let prompt = pruneRawPromptFromTop(
|
||||
completionOptions.model,
|
||||
|
|
@ -614,11 +631,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
|
||||
if (logEnabled) {
|
||||
if (this.writeLog) {
|
||||
await this.writeLog(
|
||||
this._compilePromptForLog(prompt, completionOptions),
|
||||
);
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "startComplete",
|
||||
prompt,
|
||||
options: completionOptions,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
}
|
||||
|
|
@ -646,6 +663,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
)) {
|
||||
const content = chunk.choices[0]?.text ?? "";
|
||||
completion += content;
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: content,
|
||||
});
|
||||
yield content;
|
||||
}
|
||||
}
|
||||
|
|
@ -656,14 +677,40 @@ export abstract class BaseLLM implements ILLM {
|
|||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk,
|
||||
});
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
} finally {
|
||||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
if (status === "in_progress") {
|
||||
this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -682,6 +729,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
) {
|
||||
const { completionOptions, logEnabled, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
? this.logger?.createInteractionLog()
|
||||
: undefined;
|
||||
let status: InteractionStatus = "in_progress";
|
||||
|
||||
let prompt = pruneRawPromptFromTop(
|
||||
completionOptions.model,
|
||||
|
|
@ -695,34 +746,65 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
|
||||
if (logEnabled) {
|
||||
if (this.writeLog) {
|
||||
await this.writeLog(
|
||||
this._compilePromptForLog(prompt, completionOptions),
|
||||
);
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "startComplete",
|
||||
prompt: prompt,
|
||||
options: completionOptions,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
}
|
||||
}
|
||||
|
||||
let completion: string;
|
||||
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
|
||||
const result = await this.openaiAdapter.completionNonStream(
|
||||
{
|
||||
...toCompleteBody(prompt, completionOptions),
|
||||
stream: false,
|
||||
},
|
||||
signal,
|
||||
let completion: string = "";
|
||||
|
||||
try {
|
||||
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
|
||||
const result = await this.openaiAdapter.completionNonStream(
|
||||
{
|
||||
...toCompleteBody(prompt, completionOptions),
|
||||
stream: false,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
completion = result.choices[0].text;
|
||||
} else {
|
||||
completion = await this._complete(prompt, signal, completionOptions);
|
||||
}
|
||||
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: completion,
|
||||
});
|
||||
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
);
|
||||
completion = result.choices[0].text;
|
||||
} else {
|
||||
completion = await this._complete(prompt, signal, completionOptions);
|
||||
}
|
||||
|
||||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status === "in_progress") {
|
||||
this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return completion;
|
||||
|
|
@ -767,20 +849,31 @@ export abstract class BaseLLM implements ILLM {
|
|||
): AsyncGenerator<ChatMessage, PromptLog> {
|
||||
let { completionOptions, logEnabled } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
? this.logger?.createInteractionLog()
|
||||
: undefined;
|
||||
let status: InteractionStatus = "in_progress";
|
||||
|
||||
completionOptions = this._modifyCompletionOptions(completionOptions);
|
||||
|
||||
const messages = this._compileChatMessages(completionOptions, _messages);
|
||||
const messages = compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: _messages,
|
||||
contextLength: this.contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
|
||||
const prompt = this.templateMessages
|
||||
? this.templateMessages(messages)
|
||||
: this._formatChatMessages(messages);
|
||||
if (logEnabled) {
|
||||
if (this.writeLog) {
|
||||
await this.writeLog(
|
||||
this._compilePromptForLog(prompt, completionOptions),
|
||||
);
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "startChat",
|
||||
messages,
|
||||
options: completionOptions,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
}
|
||||
|
|
@ -788,7 +881,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
let citations: null | string[] = null;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -798,6 +890,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: chunk,
|
||||
});
|
||||
yield { role: "assistant", content: chunk };
|
||||
}
|
||||
} else {
|
||||
|
|
@ -827,15 +923,12 @@ export abstract class BaseLLM implements ILLM {
|
|||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
completion += result.content;
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: result,
|
||||
});
|
||||
yield result;
|
||||
}
|
||||
if (
|
||||
!citations &&
|
||||
(chunk as any).citations &&
|
||||
Array.isArray((chunk as any).citations)
|
||||
) {
|
||||
citations = (chunk as any).citations;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
@ -846,44 +939,56 @@ export abstract class BaseLLM implements ILLM {
|
|||
)) {
|
||||
if (chunk.role === "assistant") {
|
||||
completion += chunk.content;
|
||||
yield chunk;
|
||||
} else if (chunk.role === "thinking") {
|
||||
thinking += chunk.content;
|
||||
}
|
||||
|
||||
if (chunk.role === "thinking") {
|
||||
thinking += chunk.content;
|
||||
yield chunk;
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: chunk,
|
||||
});
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
if (thinking) {
|
||||
await this.writeLog(`Thinking:\n${thinking}\n\n`);
|
||||
}
|
||||
/*
|
||||
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
|
||||
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
|
||||
and you must include the complete unmodified block back to the API. This is critical
|
||||
for maintaining the model's reasoning flow and conversation integrity.
|
||||
|
||||
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
|
||||
requests when not using tools, so it's the simplest option to always add to history.
|
||||
*/
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
|
||||
if (citations) {
|
||||
await this.writeLog(
|
||||
`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`,
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status === "in_progress") {
|
||||
this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
}
|
||||
/*
|
||||
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
|
||||
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
|
||||
and you must include the complete unmodified block back to the API. This is critical
|
||||
for maintaining the model's reasoning flow and conversation integrity.
|
||||
|
||||
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
|
||||
requests when not using tools, so it's the simplest option to always add to history.
|
||||
*/
|
||||
|
||||
return {
|
||||
modelTitle: this.title ?? completionOptions.model,
|
||||
|
|
|
|||
|
|
@ -226,7 +226,11 @@ describe("LLM", () => {
|
|||
apiKey: process.env.MISTRAL_API_KEY,
|
||||
model: "codestral-latest",
|
||||
}),
|
||||
{ testFim: true, skip: false },
|
||||
{
|
||||
testFim: true,
|
||||
skip: false,
|
||||
testToolCall: true,
|
||||
},
|
||||
);
|
||||
testLLM(
|
||||
new Azure({
|
||||
|
|
|
|||
|
|
@ -30,15 +30,17 @@ class Anthropic extends BaseLLM {
|
|||
description: tool.function.description,
|
||||
input_schema: tool.function.parameters,
|
||||
})),
|
||||
thinking: options.reasoning ? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
} : undefined,
|
||||
thinking: options.reasoning
|
||||
? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
}
|
||||
: undefined,
|
||||
tool_choice: options.toolChoice
|
||||
? {
|
||||
type: "tool",
|
||||
name: options.toolChoice.function.name,
|
||||
}
|
||||
type: "tool",
|
||||
name: options.toolChoice.function.name,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
|
|
@ -70,19 +72,23 @@ class Anthropic extends BaseLLM {
|
|||
} else if (message.role === "thinking" && !message.redactedThinking) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [{
|
||||
type: "thinking",
|
||||
thinking: message.content,
|
||||
signature: message.signature
|
||||
}]
|
||||
content: [
|
||||
{
|
||||
type: "thinking",
|
||||
thinking: message.content,
|
||||
signature: message.signature,
|
||||
},
|
||||
],
|
||||
};
|
||||
} else if (message.role === "thinking" && message.redactedThinking) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [{
|
||||
type: "redacted_thinking",
|
||||
data: message.redactedThinking
|
||||
}]
|
||||
content: [
|
||||
{
|
||||
type: "redacted_thinking",
|
||||
data: message.redactedThinking,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -172,11 +178,12 @@ class Anthropic extends BaseLLM {
|
|||
);
|
||||
}
|
||||
|
||||
const shouldCacheSystemMessage =
|
||||
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const systemMessage: string = stripImages(
|
||||
const systemMessage = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content ?? "",
|
||||
);
|
||||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
|
||||
const msgs = this.convertMessages(messages);
|
||||
const response = await this.fetch(new URL("messages", this.apiBase), {
|
||||
|
|
@ -195,12 +202,12 @@ class Anthropic extends BaseLLM {
|
|||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: this.systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
{
|
||||
type: "text",
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
signal,
|
||||
|
|
@ -240,7 +247,11 @@ class Anthropic extends BaseLLM {
|
|||
// handle redacted thinking
|
||||
if (value.content_block.type === "redacted_thinking") {
|
||||
console.log("redacted thinking", value.content_block.data);
|
||||
yield { role: "thinking", content: "", redactedThinking: value.content_block.data };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: value.content_block.data,
|
||||
};
|
||||
}
|
||||
break;
|
||||
case "content_block_delta":
|
||||
|
|
@ -253,7 +264,11 @@ class Anthropic extends BaseLLM {
|
|||
yield { role: "thinking", content: value.delta.thinking };
|
||||
break;
|
||||
case "signature_delta":
|
||||
yield { role: "thinking", content: "", signature: value.delta.signature };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
signature: value.delta.signature,
|
||||
};
|
||||
break;
|
||||
case "input_json_delta":
|
||||
if (!lastToolUseId || !lastToolUseName) {
|
||||
|
|
|
|||
|
|
@ -2,8 +2,9 @@ import {
|
|||
BedrockRuntimeClient,
|
||||
ContentBlock,
|
||||
ConverseStreamCommand,
|
||||
ConverseStreamCommandOutput,
|
||||
InvokeModelCommand,
|
||||
Message
|
||||
Message,
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
|
|
@ -11,11 +12,12 @@ import {
|
|||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
|
||||
import { getSecureID } from "../utils/getSecureID.js";
|
||||
|
||||
interface ModelConfig {
|
||||
formatPayload: (text: string) => any;
|
||||
|
|
@ -31,6 +33,14 @@ interface ToolUseState {
|
|||
input: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for prompt caching metrics
|
||||
*/
|
||||
interface PromptCachingMetrics {
|
||||
cacheReadInputTokens: number;
|
||||
cacheWriteInputTokens: number;
|
||||
}
|
||||
|
||||
class Bedrock extends BaseLLM {
|
||||
static providerName = "bedrock";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
|
|
@ -41,8 +51,16 @@ class Bedrock extends BaseLLM {
|
|||
};
|
||||
|
||||
private _currentToolResponse: Partial<ToolUseState> | null = null;
|
||||
private _promptCachingMetrics: PromptCachingMetrics = {
|
||||
cacheReadInputTokens: 0,
|
||||
cacheWriteInputTokens: 0,
|
||||
};
|
||||
|
||||
public requestOptions: { region?: string; credentials?: any; headers?: Record<string, string> };
|
||||
public requestOptions: {
|
||||
region?: string;
|
||||
credentials?: any;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
|
@ -108,12 +126,17 @@ class Bedrock extends BaseLLM {
|
|||
},
|
||||
);
|
||||
|
||||
const input = this._generateConverseInput(messages, { ...options, stream: true });
|
||||
const input = this._generateConverseInput(messages, {
|
||||
...options,
|
||||
stream: true,
|
||||
});
|
||||
const command = new ConverseStreamCommand(input);
|
||||
|
||||
let response;
|
||||
let response: ConverseStreamCommandOutput;
|
||||
try {
|
||||
response = await client.send(command, { abortSignal: signal });
|
||||
response = (await client.send(command, {
|
||||
abortSignal: signal,
|
||||
})) as ConverseStreamCommandOutput;
|
||||
} catch (error: unknown) {
|
||||
console.error(error);
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
|
|
@ -124,51 +147,82 @@ class Bedrock extends BaseLLM {
|
|||
throw new Error("No stream received from Bedrock API");
|
||||
}
|
||||
|
||||
// Reset cache metrics for new request
|
||||
this._promptCachingMetrics = {
|
||||
cacheReadInputTokens: 0,
|
||||
cacheWriteInputTokens: 0,
|
||||
};
|
||||
|
||||
try {
|
||||
for await (const chunk of response.stream) {
|
||||
if (chunk.metadata?.usage) {
|
||||
console.log(`${JSON.stringify(chunk.metadata.usage)}`);
|
||||
}
|
||||
|
||||
if (chunk.contentBlockDelta?.delta) {
|
||||
|
||||
const delta: any = chunk.contentBlockDelta.delta
|
||||
const delta: any = chunk.contentBlockDelta.delta;
|
||||
|
||||
// Handle text content
|
||||
if (chunk.contentBlockDelta.delta.text) {
|
||||
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: chunk.contentBlockDelta.delta.text,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle text content
|
||||
if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) {
|
||||
yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent.text };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: (chunk.contentBlockDelta.delta as any).reasoningContent
|
||||
.text,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle signature for thinking
|
||||
if (delta.reasoningContent?.signature) {
|
||||
yield { role: "thinking", content: "", signature: delta.reasoningContent.signature };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
signature: delta.reasoningContent.signature,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle redacted thinking
|
||||
if (delta.redactedReasoning?.data) {
|
||||
yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: delta.redactedReasoning.data,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
|
||||
if (
|
||||
chunk.contentBlockDelta.delta.toolUse?.input &&
|
||||
this._currentToolResponse
|
||||
) {
|
||||
// Append the new input to the existing string
|
||||
if (this._currentToolResponse.input === undefined) {
|
||||
this._currentToolResponse.input = "";
|
||||
}
|
||||
this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input;
|
||||
this._currentToolResponse.input +=
|
||||
chunk.contentBlockDelta.delta.toolUse.input;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.contentBlockStart?.start) {
|
||||
const start: any = chunk.contentBlockStart.start
|
||||
const start: any = chunk.contentBlockStart.start;
|
||||
if (start.redactedReasoning) {
|
||||
yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: start.redactedReasoning.data,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -177,7 +231,7 @@ class Bedrock extends BaseLLM {
|
|||
this._currentToolResponse = {
|
||||
toolUseId: toolUse.toolUseId,
|
||||
name: toolUse.name,
|
||||
input: ""
|
||||
input: "",
|
||||
};
|
||||
}
|
||||
continue;
|
||||
|
|
@ -188,14 +242,16 @@ class Bedrock extends BaseLLM {
|
|||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: this._currentToolResponse.toolUseId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: this._currentToolResponse.name,
|
||||
arguments: this._currentToolResponse.input
|
||||
}
|
||||
}],
|
||||
toolCalls: [
|
||||
{
|
||||
id: this._currentToolResponse.toolUseId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: this._currentToolResponse.name,
|
||||
arguments: this._currentToolResponse.input,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
this._currentToolResponse = null;
|
||||
}
|
||||
|
|
@ -207,13 +263,16 @@ class Bedrock extends BaseLLM {
|
|||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`);
|
||||
throw new Error(
|
||||
`AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Error processing Bedrock stream: ${error.message}`);
|
||||
}
|
||||
throw new Error("Error processing Bedrock stream: Unknown error occurred");
|
||||
throw new Error(
|
||||
"Error processing Bedrock stream: Unknown error occurred",
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -226,24 +285,48 @@ class Bedrock extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
): any {
|
||||
const systemMessage = stripImages(
|
||||
messages.find((m) => m.role === "system")?.content ?? "",
|
||||
);
|
||||
const convertedMessages = this._convertMessages(messages);
|
||||
|
||||
const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
|
||||
const shouldCacheSystemMessage =
|
||||
!!systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const enablePromptCaching =
|
||||
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
|
||||
|
||||
// Add header for prompt caching
|
||||
if (enablePromptCaching) {
|
||||
this.requestOptions.headers = {
|
||||
...this.requestOptions.headers,
|
||||
"x-amzn-bedrock-enablepromptcaching": "true",
|
||||
};
|
||||
}
|
||||
|
||||
const supportsTools =
|
||||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
|
||||
return {
|
||||
modelId: options.model,
|
||||
messages: convertedMessages,
|
||||
system: this.systemMessage ? [{ text: this.systemMessage }] : undefined,
|
||||
toolConfig: supportsTools && options.tools ? {
|
||||
tools: options.tools.map(tool => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters
|
||||
system: systemMessage
|
||||
? shouldCacheSystemMessage
|
||||
? [{ text: systemMessage }, { cachePoint: { type: "default" } }]
|
||||
: [{ text: systemMessage }]
|
||||
: undefined,
|
||||
toolConfig:
|
||||
supportsTools && options.tools
|
||||
? {
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
}
|
||||
}
|
||||
}))
|
||||
} : undefined,
|
||||
: undefined,
|
||||
inferenceConfig: {
|
||||
maxTokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
|
|
@ -261,20 +344,29 @@ class Bedrock extends BaseLLM {
|
|||
.slice(0, 4),
|
||||
},
|
||||
additionalModelRequestFields: {
|
||||
"thinking": options.reasoning ? {
|
||||
"type": "enabled",
|
||||
"budget_tokens": options.reasoningBudgetTokens
|
||||
} : undefined,
|
||||
}
|
||||
thinking: options.reasoning
|
||||
? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private _convertMessage(message: ChatMessage): Message | null {
|
||||
private _convertMessage(
|
||||
message: ChatMessage,
|
||||
addCaching: boolean = false,
|
||||
): Message | null {
|
||||
// Handle system messages explicitly
|
||||
if (message.role === "system") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cachePoint = addCaching
|
||||
? { cachePoint: { type: "default" } }
|
||||
: undefined;
|
||||
|
||||
// Tool response handling
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
|
|
@ -285,12 +377,12 @@ class Bedrock extends BaseLLM {
|
|||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: message.content || ""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
text: message.content || "",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -303,8 +395,8 @@ class Bedrock extends BaseLLM {
|
|||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
}
|
||||
}))
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -312,84 +404,117 @@ class Bedrock extends BaseLLM {
|
|||
if (message.redactedThinking) {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
redactedContent: new Uint8Array(Buffer.from(message.redactedThinking))
|
||||
}
|
||||
redactedContent: new Uint8Array(
|
||||
Buffer.from(message.redactedThinking),
|
||||
),
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content]
|
||||
content: [content],
|
||||
};
|
||||
} else {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: (message.content as string) || "",
|
||||
signature: message.signature
|
||||
}
|
||||
|
||||
}
|
||||
signature: message.signature,
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content]
|
||||
content: [content],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Standard text message
|
||||
if (typeof message.content === "string") {
|
||||
if (addCaching) {
|
||||
message.content += getSecureID();
|
||||
}
|
||||
const content: any[] = [{ text: message.content }];
|
||||
if (addCaching) {
|
||||
content.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
return {
|
||||
role: message.role,
|
||||
content: [{ text: message.content }]
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
// Improved multimodal content handling
|
||||
if (Array.isArray(message.content)) {
|
||||
const content: any[] = [];
|
||||
|
||||
// Process all parts first
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "text") {
|
||||
if (addCaching) {
|
||||
part.text += getSecureID();
|
||||
}
|
||||
content.push({ text: part.text });
|
||||
} else if (part.type === "imageUrl" && part.imageUrl) {
|
||||
try {
|
||||
const [mimeType, base64Data] = part.imageUrl.url.split(",");
|
||||
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
|
||||
content.push({
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Buffer.from(base64Data, "base64"),
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process image: ${error}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Add cache point as a separate block at the end if needed
|
||||
if (addCaching && content.length > 0) {
|
||||
content.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
|
||||
return {
|
||||
role: message.role,
|
||||
content: message.content.map(part => {
|
||||
if (part.type === "text") {
|
||||
return { text: part.text };
|
||||
}
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
try {
|
||||
const [mimeType, base64Data] = part.imageUrl.url.split(",");
|
||||
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
|
||||
return {
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Buffer.from(base64Data, "base64")
|
||||
}
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process image: ${error}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}).filter(Boolean)
|
||||
content,
|
||||
} as Message;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private _convertMessages(messages: ChatMessage[]): any[] {
|
||||
const filteredmessages = messages.filter(
|
||||
(m) => m.role !== "system" && !!m.content,
|
||||
);
|
||||
const lastTwoUserMsgIndices = filteredmessages
|
||||
.map((msg, index) => (msg.role === "user" ? index : -1))
|
||||
.filter((index) => index !== -1)
|
||||
.slice(-2);
|
||||
|
||||
const converted = filteredmessages
|
||||
.map((message, filteredMsgIdx) => {
|
||||
// Add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
|
||||
const addCaching =
|
||||
this.cacheBehavior?.cacheConversation &&
|
||||
lastTwoUserMsgIndices.includes(filteredMsgIdx);
|
||||
|
||||
const converted = messages
|
||||
.map((message) => {
|
||||
try {
|
||||
return this._convertMessage(message);
|
||||
return this._convertMessage(message, addCaching);
|
||||
} catch (error) {
|
||||
console.error(`Failed to convert message: ${error}`);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
return converted;
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
|
|
@ -453,7 +578,6 @@ class Bedrock extends BaseLLM {
|
|||
return modelConfig.extractEmbeddings(responseBody);
|
||||
}
|
||||
|
||||
|
||||
private _getModelConfig() {
|
||||
const modelConfigs: { [key: string]: ModelConfig } = {
|
||||
cohere: {
|
||||
|
|
@ -491,7 +615,11 @@ class Bedrock extends BaseLLM {
|
|||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
credentials,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
|
||||
// Base payload for both models
|
||||
|
|
@ -530,11 +658,15 @@ class Bedrock extends BaseLLM {
|
|||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`);
|
||||
throw new Error(
|
||||
`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
|
||||
}
|
||||
throw new Error("Error in BedrockReranker.rerank: Unknown error occurred");
|
||||
throw new Error(
|
||||
"Error in BedrockReranker.rerank: Unknown error occurred",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
CompletionOptions,
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamJSON } from "../stream.js";
|
||||
|
||||
|
|
@ -67,6 +67,11 @@ class Cohere extends BaseLLM {
|
|||
...this.requestOptions?.headers,
|
||||
};
|
||||
|
||||
let preamble: string | undefined = undefined;
|
||||
const systemMessage = messages.find((m) => m.role === "system")?.content;
|
||||
if (systemMessage) {
|
||||
preamble = stripImages(systemMessage);
|
||||
}
|
||||
const resp = await this.fetch(new URL("chat", this.apiBase), {
|
||||
method: "POST",
|
||||
headers,
|
||||
|
|
@ -74,7 +79,7 @@ class Cohere extends BaseLLM {
|
|||
...this._convertArgs(options),
|
||||
message: messages.pop()?.content,
|
||||
chat_history: this._convertMessages(messages),
|
||||
preamble: this.systemMessage,
|
||||
preamble,
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
|
|
|||
227
core/llm/llms/Docker.ts
Normal file
227
core/llm/llms/Docker.ts
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
import { Mutex } from "async-mutex";
|
||||
import { spawn } from "child_process";
|
||||
import { LLMOptions, ModelInstaller } from "../../index.js";
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
/**
|
||||
* Docker Model Runner provider
|
||||
*
|
||||
* Integrates with Docker Desktop's Model Runner feature (currently in beta)
|
||||
* that allows running local AI models through Docker.
|
||||
*
|
||||
* Docker Model Runner provides an OpenAI-compatible API endpoint, making it
|
||||
* easy to integrate with existing OpenAI-compatible code.
|
||||
*
|
||||
* More information at: https://docs.docker.com/desktop/features/model-runner/
|
||||
*/
|
||||
class Docker extends OpenAI implements ModelInstaller {
|
||||
static providerName = "docker";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:12434/engines/v1",
|
||||
model: "gemma3-4B-F4", // Default model
|
||||
};
|
||||
|
||||
private modelMap: Record<string, string> = {
|
||||
// Map of "continue model name" to Docker model name
|
||||
// Models can be pulled using: docker model pull <model_name>
|
||||
"llama3.3-70b": "ai/llama3.3:70B-Q4_K_M",
|
||||
"smollm2-360M-F4": "ai/smollm2:360M-Q4_K_M",
|
||||
"smollm2-360M-F16": "ai/ai/smollm2:360M-F16",
|
||||
"qwen2.5-7B-F16": "ai/qwen2.5:7B-F16",
|
||||
"qwen2.5-7B-F4": "ai/qwen2.5:7B-Q4_K_M",
|
||||
"phi4-14B-F16": "ai/phi4:14B-F16",
|
||||
"phi4-14B-F4": "ai/phi4:14B-Q4_K_M",
|
||||
"mistral-7B-F16": "ai/mistral:7B-F16",
|
||||
"mistral-7B-F4": "ai/mistral:7B-Q4_K_M",
|
||||
"mistral-nemo-12B": "ai/mistral-nemo:12B-Q4_K_M",
|
||||
"gemma3-4B-F16": "ai/gemma3:4B-F16",
|
||||
"gemma3-4B-F4": "ai/gemma3:4B-Q4_K_M",
|
||||
"llama3.2-3B-F16": "ai/llama3.2:3B-F16",
|
||||
"llama3.2-3B-F4": "ai/llama3.2:3B-Q4_K_M",
|
||||
"llama3.2-1B-F16": "ai/llama3.2:1B-F16",
|
||||
"llama3.2-1B-F8": "ai/llama3.2:1B-Q8_0",
|
||||
"qwq-32B-F16": "ai/qwq:32B-F16",
|
||||
"qwq-32B-F4": "ai/qwq:32B-Q4_K_M",
|
||||
"deepseek-r1-distill-llama-70B-F4":
|
||||
"ai/deepseek-r1-distill-llama:70B-Q4_K_M",
|
||||
"deepseek-r1-distill-llama-8B-F16": "ai/deepseek-r1-distill-llama:8B-F16",
|
||||
"deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M",
|
||||
};
|
||||
|
||||
private static modelsBeingInstalled: Set<string> = new Set();
|
||||
private static modelsBeingInstalledMutex = new Mutex();
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
||||
// Handle model name mapping
|
||||
if (this.model && this.modelMap[this.model]) {
|
||||
this.model = this.modelMap[this.model];
|
||||
}
|
||||
|
||||
// Check if Docker Model Runner is active and enable it if needed
|
||||
this.ensureModelRunnerEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if Docker Model Runner is running at the expected port
|
||||
* and enables it if not running
|
||||
*/
|
||||
private async ensureModelRunnerEnabled(): Promise<void> {
|
||||
try {
|
||||
// Check if the Model Runner service is running on the expected port
|
||||
const isRunning = await this.isPortBound(12434);
|
||||
|
||||
if (!isRunning) {
|
||||
console.log(
|
||||
"Docker Model Runner not detected. Attempting to enable it...",
|
||||
);
|
||||
await this.executeDockerCommand([
|
||||
"desktop",
|
||||
"enable",
|
||||
"model-runner",
|
||||
"--tcp",
|
||||
"12434",
|
||||
]);
|
||||
console.log("Docker Model Runner has been enabled on port 12434");
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to enable Docker Model Runner:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a port is currently bound/in use
|
||||
*/
|
||||
private async isPortBound(port: number): Promise<boolean> {
|
||||
try {
|
||||
await this.fetch(`http://localhost:${port}`, {
|
||||
method: "HEAD",
|
||||
signal: AbortSignal.timeout(1000),
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async executeDockerCommand(
|
||||
args: string[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn("docker", args, { shell: true });
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
proc.stdout.on("data", (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr.on("data", (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ stdout, stderr });
|
||||
} else {
|
||||
reject(
|
||||
new Error(`Docker command failed with code ${code}: ${stderr}`),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (signal) {
|
||||
signal.addEventListener("abort", () => {
|
||||
proc.kill();
|
||||
reject(new Error("Docker command was aborted"));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async listModels(): Promise<string[]> {
|
||||
try {
|
||||
// Execute docker model ls and parse the output
|
||||
const { stdout } = await this.executeDockerCommand([
|
||||
"model",
|
||||
"ls",
|
||||
"--format",
|
||||
"{{.Repository}}/{{.Tag}}",
|
||||
]);
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
} catch (error) {
|
||||
console.error("Failed to list Docker models:", error);
|
||||
return Object.values(this.modelMap);
|
||||
}
|
||||
}
|
||||
|
||||
async installModel(
|
||||
modelName: string,
|
||||
signal: AbortSignal,
|
||||
progressReporter?: (task: string, increment: number, total: number) => void,
|
||||
): Promise<any> {
|
||||
const targetModel = this.modelMap[modelName] || modelName;
|
||||
|
||||
const release = await Docker.modelsBeingInstalledMutex.acquire();
|
||||
try {
|
||||
if (Docker.modelsBeingInstalled.has(modelName)) {
|
||||
throw new Error(`Model '${modelName}' is already being installed.`);
|
||||
}
|
||||
Docker.modelsBeingInstalled.add(modelName);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
|
||||
try {
|
||||
// Report starting the installation
|
||||
progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100);
|
||||
|
||||
// Pull the model
|
||||
const { stdout, stderr } = await this.executeDockerCommand(
|
||||
["model", "pull", targetModel],
|
||||
signal,
|
||||
);
|
||||
|
||||
// Report completion
|
||||
progressReporter?.(
|
||||
`Docker model ${targetModel} installed successfully`,
|
||||
100,
|
||||
100,
|
||||
);
|
||||
|
||||
return { success: true, stdout, stderr };
|
||||
} catch (error) {
|
||||
console.error(`Failed to install Docker model ${targetModel}:`, error);
|
||||
// Fix: Type check the error before accessing message property
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
throw new Error(
|
||||
`Failed to install Docker model ${targetModel}: ${errorMessage}`,
|
||||
);
|
||||
} finally {
|
||||
const release = await Docker.modelsBeingInstalledMutex.acquire();
|
||||
try {
|
||||
Docker.modelsBeingInstalled.delete(modelName);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async isInstallingModel(modelName: string): Promise<boolean> {
|
||||
const release = await Docker.modelsBeingInstalledMutex.acquire();
|
||||
try {
|
||||
return Docker.modelsBeingInstalled.has(modelName);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Docker;
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
import {
|
||||
AssistantChatMessage,
|
||||
ChatMessage,
|
||||
|
|
@ -7,17 +8,18 @@ import {
|
|||
TextMessagePart,
|
||||
ToolCallDelta,
|
||||
} from "../../index.js";
|
||||
import { findLast } from "../../util/findLast.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
import {
|
||||
GeminiChatContent,
|
||||
GeminiChatContentPart,
|
||||
GeminiChatRequestBody,
|
||||
GeminiChatResponse,
|
||||
GeminiGenerationConfig,
|
||||
GeminiToolFunctionDeclaration,
|
||||
} from "./gemini-types.js";
|
||||
convertContinueToolToGeminiFunction,
|
||||
} from "./gemini-types";
|
||||
|
||||
class Gemini extends BaseLLM {
|
||||
static providerName = "gemini";
|
||||
|
|
@ -155,14 +157,8 @@ class Gemini extends BaseLLM {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
// Ensure this.apiBase is used if available, otherwise use default
|
||||
const apiBase =
|
||||
this.apiBase ||
|
||||
Gemini.defaultOptions?.apiBase ||
|
||||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
|
||||
const isV1API = apiBase.includes("/v1/");
|
||||
const isV1API = this.apiBase?.includes("/v1/");
|
||||
|
||||
// Conditionally apply removeSystemMessage
|
||||
const convertedMsgs = isV1API
|
||||
? this.removeSystemMessage(messages)
|
||||
: messages;
|
||||
|
|
@ -204,20 +200,27 @@ class Gemini extends BaseLLM {
|
|||
options: CompletionOptions,
|
||||
isV1API: boolean,
|
||||
): GeminiChatRequestBody {
|
||||
const toolCallIdToNameMap = new Map<string, string>();
|
||||
messages.forEach((msg) => {
|
||||
if (msg.role === "assistant" && msg.toolCalls) {
|
||||
msg.toolCalls.forEach((call) => {
|
||||
if (call.id && call.function?.name) {
|
||||
toolCallIdToNameMap.set(call.id, call.function.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
const systemMessage = messages.find(
|
||||
(msg) => msg.role === "system",
|
||||
)?.content;
|
||||
|
||||
const body: GeminiChatRequestBody = {
|
||||
contents: messages
|
||||
.filter((msg) => !(msg.role === "system" && isV1API))
|
||||
.map((msg) => {
|
||||
if (msg.role === "tool") {
|
||||
let fn_name = "";
|
||||
const lastToolCallMessage = findLast(
|
||||
messages,
|
||||
(msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name,
|
||||
) as AssistantChatMessage;
|
||||
if (lastToolCallMessage) {
|
||||
fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!;
|
||||
}
|
||||
if (!fn_name) {
|
||||
let functionName = toolCallIdToNameMap.get(msg.toolCallId);
|
||||
if (!functionName) {
|
||||
console.warn(
|
||||
"Sending tool call response for unidentified tool call",
|
||||
);
|
||||
|
|
@ -227,7 +230,8 @@ class Gemini extends BaseLLM {
|
|||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: fn_name || "unknown",
|
||||
id: msg.toolCallId,
|
||||
name: functionName || "unknown",
|
||||
response: {
|
||||
output: msg.content, // "output" key is opinionated - not all functions will output objects
|
||||
},
|
||||
|
|
@ -236,28 +240,35 @@ class Gemini extends BaseLLM {
|
|||
],
|
||||
};
|
||||
}
|
||||
const assistantMsg = {
|
||||
role:
|
||||
msg.role === "assistant" ? ("model" as const) : ("user" as const),
|
||||
if (msg.role === "assistant") {
|
||||
const assistantMsg: GeminiChatContent = {
|
||||
role: "model",
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
if (msg.toolCalls) {
|
||||
msg.toolCalls.forEach((toolCall) => {
|
||||
if (toolCall.function?.name && toolCall.function?.arguments) {
|
||||
assistantMsg.parts.push({
|
||||
functionCall: {
|
||||
name: toolCall.function.name,
|
||||
args: JSON.parse(toolCall.function.arguments),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
return assistantMsg;
|
||||
}
|
||||
return {
|
||||
role: "user",
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
if (msg.role === "assistant" && msg.toolCalls) {
|
||||
msg.toolCalls.forEach((toolCall) => {
|
||||
if (toolCall.function?.name && toolCall.function?.arguments) {
|
||||
assistantMsg.parts.push({
|
||||
functionCall: {
|
||||
name: toolCall.function.name,
|
||||
args: JSON.parse(toolCall.function.arguments),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return assistantMsg;
|
||||
}),
|
||||
};
|
||||
if (options) {
|
||||
|
|
@ -266,8 +277,10 @@ class Gemini extends BaseLLM {
|
|||
|
||||
// https://ai.google.dev/gemini-api/docs/api-versions
|
||||
if (!isV1API) {
|
||||
if (this.systemMessage) {
|
||||
body.systemInstruction = { parts: [{ text: this.systemMessage }] };
|
||||
if (systemMessage) {
|
||||
body.systemInstruction = {
|
||||
parts: [{ text: stripImages(systemMessage) }],
|
||||
};
|
||||
}
|
||||
// Convert and add tools if present
|
||||
if (options.tools?.length) {
|
||||
|
|
@ -276,77 +289,12 @@ class Gemini extends BaseLLM {
|
|||
// Same difference
|
||||
const functions: GeminiToolFunctionDeclaration[] = [];
|
||||
options.tools.forEach((tool) => {
|
||||
if (tool.function.description && tool.function.name) {
|
||||
const fn: GeminiToolFunctionDeclaration = {
|
||||
description: tool.function.description,
|
||||
name: tool.function.name,
|
||||
};
|
||||
|
||||
if (
|
||||
tool.function.parameters &&
|
||||
"type" in tool.function.parameters
|
||||
// && typeof tool.function.parameters.type === "string"
|
||||
) {
|
||||
// const paramType = "TYPE_UNSPECIFIED"
|
||||
// | "STRING"
|
||||
// | "NUMBER"
|
||||
// | "INTEGER"
|
||||
// | "BOOLEAN"
|
||||
// | "ARRAY"
|
||||
// | "OBJECT"
|
||||
|
||||
if (tool.function.parameters.type === "object") {
|
||||
// Gemini can't take an empty object
|
||||
// So if empty object param is present just don't add parameters
|
||||
if (
|
||||
JSON.stringify(tool.function.parameters.properties) === "{}"
|
||||
) {
|
||||
functions.push(fn);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Helper function to recursively clean JSON Schema objects
|
||||
const cleanJsonSchema = (schema: any): any => {
|
||||
if (!schema || typeof schema !== "object") return schema;
|
||||
|
||||
if (Array.isArray(schema)) {
|
||||
return schema.map(cleanJsonSchema);
|
||||
}
|
||||
|
||||
const {
|
||||
$schema,
|
||||
additionalProperties,
|
||||
default: defaultValue,
|
||||
...rest
|
||||
} = schema;
|
||||
|
||||
// Recursively clean nested properties
|
||||
if (rest.properties) {
|
||||
rest.properties = Object.entries(rest.properties).reduce(
|
||||
(acc, [key, value]) => ({
|
||||
...acc,
|
||||
[key]: cleanJsonSchema(value),
|
||||
}),
|
||||
{},
|
||||
);
|
||||
}
|
||||
|
||||
// Clean items in arrays
|
||||
if (rest.items) {
|
||||
rest.items = cleanJsonSchema(rest.items);
|
||||
}
|
||||
|
||||
return rest;
|
||||
};
|
||||
|
||||
// Clean the parameters and convert type to uppercase
|
||||
const cleanedParams = cleanJsonSchema(tool.function.parameters);
|
||||
fn.parameters = {
|
||||
...cleanedParams,
|
||||
type: tool.function.parameters.type.toUpperCase(),
|
||||
};
|
||||
}
|
||||
functions.push(fn);
|
||||
try {
|
||||
functions.push(convertContinueToolToGeminiFunction(tool));
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
if (functions.length) {
|
||||
|
|
@ -397,75 +345,39 @@ class Gemini extends BaseLLM {
|
|||
// Check for existence of each level before accessing the final 'text' property
|
||||
const content = data?.candidates?.[0]?.content;
|
||||
if (content) {
|
||||
const supportedParts: MessagePart[] = [];
|
||||
const textParts: MessagePart[] = [];
|
||||
const toolCalls: ToolCallDelta[] = [];
|
||||
|
||||
// Process all parts first to maintain order
|
||||
const processedParts: Array<{
|
||||
type: "content" | "tool" | "toolCall";
|
||||
data: any;
|
||||
}> = [];
|
||||
|
||||
for (const part of content.parts) {
|
||||
if ("text" in part) {
|
||||
supportedParts.push({ type: "text", text: part.text });
|
||||
} else if ("inlineData" in part) {
|
||||
supportedParts.push({
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: `data:image/jpeg;base64,${part.inlineData.data}`,
|
||||
},
|
||||
});
|
||||
textParts.push({ type: "text", text: part.text });
|
||||
} else if ("functionCall" in part) {
|
||||
// Queue function call
|
||||
processedParts.push({
|
||||
type: "toolCall",
|
||||
data: {
|
||||
type: "function",
|
||||
id: "", // Not supported by gemini
|
||||
function: {
|
||||
name: part.functionCall.name,
|
||||
arguments:
|
||||
typeof part.functionCall.args === "string"
|
||||
? part.functionCall.args
|
||||
: JSON.stringify(part.functionCall.args),
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if ("functionResponse" in part) {
|
||||
// Queue function response
|
||||
processedParts.push({
|
||||
type: "tool",
|
||||
data: {
|
||||
role: "tool",
|
||||
content: part.functionResponse.response.output as string,
|
||||
toolCallId: part.functionResponse.name,
|
||||
toolCalls.push({
|
||||
type: "function",
|
||||
id: part.functionCall.id ?? uuidv4(),
|
||||
function: {
|
||||
name: part.functionCall.name,
|
||||
arguments:
|
||||
typeof part.functionCall.args === "string"
|
||||
? part.functionCall.args
|
||||
: JSON.stringify(part.functionCall.args),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Note: function responses shouldn't be streamed, images not supported
|
||||
console.warn("Unsupported gemini part type received", part);
|
||||
}
|
||||
}
|
||||
|
||||
// If we have supported content parts, yield them first
|
||||
if (supportedParts.length) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: supportedParts,
|
||||
};
|
||||
const assistantMessage: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: textParts.length ? textParts : "",
|
||||
};
|
||||
if (toolCalls.length > 0) {
|
||||
assistantMessage.toolCalls = toolCalls;
|
||||
}
|
||||
|
||||
// Then process tool calls and responses in order
|
||||
for (const part of processedParts) {
|
||||
if (part.type === "toolCall") {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [part.data],
|
||||
};
|
||||
} else if (part.type === "tool") {
|
||||
yield part.data;
|
||||
}
|
||||
if (textParts.length || toolCalls.length) {
|
||||
yield assistantMessage;
|
||||
}
|
||||
} else {
|
||||
// Handle the case where the expected data structure is not found
|
||||
|
|
@ -489,10 +401,8 @@ class Gemini extends BaseLLM {
|
|||
`models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
|
||||
this.apiBase,
|
||||
);
|
||||
// This feels hacky to repeat code from above function but was the quickest
|
||||
// way to ensure system message re-formatting isn't done if user has specified v1
|
||||
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
|
||||
const isV1API = apiBase.includes("/v1/");
|
||||
|
||||
const isV1API = !!this.apiBase?.includes("/v1/");
|
||||
|
||||
// Convert chat messages to contents
|
||||
const body = this.prepareBody(messages, options, isV1API);
|
||||
|
|
|
|||
72
core/llm/llms/Inception.ts
Normal file
72
core/llm/llms/Inception.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
/**
|
||||
* Inception Labs provider
|
||||
*
|
||||
* Integrates with Inception Labs' OpenAI-compatible API endpoints.
|
||||
* Provides access to Mercury models for autocomplete and other tasks.
|
||||
*
|
||||
* Different models use different API endpoints:
|
||||
* - mercury-editor-mini-experimental: zaragoza.api.inceptionlabs.ai
|
||||
* - mercury-editor-small-experimental: copenhagen.api.inceptionlabs.ai
|
||||
*
|
||||
* More information at: https://docs.inceptionlabs.ai/
|
||||
*/
|
||||
class Inception extends OpenAI {
|
||||
static providerName = "inception";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.inceptionlabs.ai/v1/",
|
||||
model: "mercury-coder-small",
|
||||
completionOptions: {
|
||||
temperature: 0.0,
|
||||
presencePenalty: 1.5,
|
||||
stop: ["<|endoftext|>"],
|
||||
model: "mercury-editor-small-experimental", // Added model to fix TypeScript error
|
||||
},
|
||||
};
|
||||
|
||||
supportsFim(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
async *_streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const endpoint = new URL("completions", this.apiBase);
|
||||
const resp = await this.fetch(endpoint, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: options.model,
|
||||
prompt: prefix,
|
||||
suffix: suffix.trim() === "" ? "<|endoftext|>" : suffix,
|
||||
max_tokens: options.maxTokens ?? 150, // Only want this for /fim, not chat
|
||||
temperature: options.temperature,
|
||||
top_p: options.topP,
|
||||
frequency_penalty: options.frequencyPenalty,
|
||||
presence_penalty: options.presencePenalty,
|
||||
stop: [...(options.stop ?? []), "\n\n", "\n \n"],
|
||||
stream: true,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
for await (const chunk of streamSse(resp)) {
|
||||
if (!chunk.choices[0]) {
|
||||
continue;
|
||||
}
|
||||
yield chunk.choices[0].text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Inception;
|
||||
|
|
@ -35,7 +35,7 @@ class LlamaCpp extends BaseLLM {
|
|||
...this.requestOptions?.headers,
|
||||
};
|
||||
|
||||
const resp = await this.fetch(new URL("completion", this.apiBase), {
|
||||
const resp = await this.fetch(new URL("completions", this.apiBase), {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { Mutex } from "async-mutex";
|
||||
import { JSONSchema7, JSONSchema7Object } from "json-schema";
|
||||
|
||||
import {
|
||||
|
|
@ -138,6 +139,9 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
maxEmbeddingBatchSize: 64,
|
||||
};
|
||||
|
||||
private static modelsBeingInstalled: Set<string> = new Set();
|
||||
private static modelsBeingInstalledMutex = new Mutex();
|
||||
|
||||
private fimSupported: boolean = false;
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
|
|
@ -592,33 +596,62 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
if (!modelInfo) {
|
||||
throw new Error(`'${modelName}' not found in the Ollama registry!`);
|
||||
}
|
||||
const response = await fetch(this.getEndpoint("api/pull"), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({ name: modelName }),
|
||||
signal,
|
||||
});
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
//TODO: generate proper progress based on modelInfo size
|
||||
while (true) {
|
||||
const { done, value } = (await reader?.read()) || {
|
||||
done: true,
|
||||
value: undefined,
|
||||
};
|
||||
if (done) {
|
||||
break;
|
||||
const release = await Ollama.modelsBeingInstalledMutex.acquire();
|
||||
try {
|
||||
if (Ollama.modelsBeingInstalled.has(modelName)) {
|
||||
throw new Error(`Model '${modelName}' is already being installed.`);
|
||||
}
|
||||
Ollama.modelsBeingInstalled.add(modelName);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
|
||||
const chunk = new TextDecoder().decode(value);
|
||||
const lines = chunk.split("\n").filter(Boolean);
|
||||
for (const line of lines) {
|
||||
const data = JSON.parse(line);
|
||||
progressReporter?.(data.status, data.completed, data.total);
|
||||
try {
|
||||
const response = await fetch(this.getEndpoint("api/pull"), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({ name: modelName }),
|
||||
signal,
|
||||
});
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
//TODO: generate proper progress based on modelInfo size
|
||||
while (true) {
|
||||
const { done, value } = (await reader?.read()) || {
|
||||
done: true,
|
||||
value: undefined,
|
||||
};
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
const chunk = new TextDecoder().decode(value);
|
||||
const lines = chunk.split("\n").filter(Boolean);
|
||||
for (const line of lines) {
|
||||
const data = JSON.parse(line);
|
||||
progressReporter?.(data.status, data.completed, data.total);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
const release = await Ollama.modelsBeingInstalledMutex.acquire();
|
||||
try {
|
||||
Ollama.modelsBeingInstalled.delete(modelName);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async isInstallingModel(modelName: string): Promise<boolean> {
|
||||
const release = await Ollama.modelsBeingInstalledMutex.acquire();
|
||||
try {
|
||||
return Ollama.modelsBeingInstalled.has(modelName);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,7 +102,12 @@ class OpenAI extends BaseLLM {
|
|||
}
|
||||
|
||||
protected supportsPrediction(model: string): boolean {
|
||||
const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"];
|
||||
const SUPPORTED_MODELS = [
|
||||
"gpt-4o-mini",
|
||||
"gpt-4o",
|
||||
"mistral-large",
|
||||
"Fast-Apply",
|
||||
];
|
||||
return SUPPORTED_MODELS.some((m) => model.includes(m));
|
||||
}
|
||||
|
||||
|
|
@ -288,7 +293,10 @@ class OpenAI extends BaseLLM {
|
|||
// To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs
|
||||
// In practice, setting this to true and asking for multiple tool calls
|
||||
// leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}'
|
||||
body.parallel_tool_calls = false;
|
||||
// o3 does not support this
|
||||
if (!body.model.startsWith("o3")) {
|
||||
body.parallel_tool_calls = false;
|
||||
}
|
||||
}
|
||||
|
||||
return body;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { LLMOptions } from "../..";
|
||||
import { LLMConfigurationStatuses } from "../constants";
|
||||
import { LlmApiRequestType } from "../openaiTypeConverters";
|
||||
|
||||
import OpenAI from "./OpenAI";
|
||||
|
|
@ -9,4 +10,16 @@ export class Relace extends OpenAI {
|
|||
apiBase: "https://instantapply.endpoint.relace.run/v1/",
|
||||
};
|
||||
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"];
|
||||
|
||||
protected supportsPrediction(model: string): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
getConfigurationStatus() {
|
||||
if (!this.apiKey) {
|
||||
return LLMConfigurationStatuses.MISSING_API_KEY;
|
||||
}
|
||||
|
||||
return LLMConfigurationStatuses.VALID;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue