Merge branch 'main' into fix-docs-2
This commit is contained in:
commit
93233e26f7
342 changed files with 15154 additions and 6007 deletions
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
|
||||
46
.github/workflows/jetbrains-release.yaml
vendored
46
.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
|
||||
|
|
|
|||
225
.github/workflows/pr_checks.yaml
vendored
225
.github/workflows/pr_checks.yaml
vendored
|
|
@ -31,6 +31,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 +116,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 +137,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 +157,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 +182,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 +225,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 +267,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 +290,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 +315,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 +360,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 +393,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
|
||||
|
|
@ -285,7 +419,7 @@ jobs:
|
|||
|
||||
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 +431,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 +465,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 +485,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 +509,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 +529,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: |
|
||||
|
|
@ -394,6 +561,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 +602,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
|
||||
|
|
@ -476,7 +655,7 @@ jobs:
|
|||
path: extensions/vscode/e2e/storage/screenshots
|
||||
|
||||
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 +675,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 +698,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 +707,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:
|
||||
|
|
@ -627,11 +828,11 @@ jobs:
|
|||
- 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
|
||||
1
.node-version
Normal file
1
.node-version
Normal file
|
|
@ -0,0 +1 @@
|
|||
20.11.0
|
||||
|
|
@ -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>
|
||||
|
||||
|
|
|
|||
9
binary/package-lock.json
generated
9
binary/package-lock.json
generated
|
|
@ -44,11 +44,11 @@
|
|||
"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",
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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 }],
|
||||
"complexity": ["error", { "max": 36 }],
|
||||
"max-lines-per-function": ["error", { "max": 472 }],
|
||||
"max-statements": ["error", { "max": 114 }],
|
||||
"max-depth": ["error", { "max": 6 }],
|
||||
"max-nested-callbacks": ["error", { "max": 4 }],
|
||||
"max-params": ["error", { "max": 11 }]
|
||||
"max-params": ["error", { "max": 8 }]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 =
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,4 +1,4 @@
|
|||
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
import {
|
||||
ControlPlaneClient,
|
||||
|
|
@ -11,374 +11,306 @@ import {
|
|||
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 {
|
||||
LOCAL_ONBOARDING_CHAT_MODEL,
|
||||
LOCAL_ONBOARDING_PROVIDER_TITLE,
|
||||
} from "./onboarding.js";
|
||||
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.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() {
|
||||
private workspaceDirs: string[] | null = null;
|
||||
async getWorkspaceId() {
|
||||
if (!this.workspaceDirs) {
|
||||
this.workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
}
|
||||
return this.workspaceDirs.join("&");
|
||||
}
|
||||
|
||||
async getProfileKey(orgId: string) {
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return `${workspaceId}:::${orgId}`;
|
||||
}
|
||||
|
||||
private async cascadeInit() {
|
||||
this.workspaceDirs = null; // forces workspace dirs reload
|
||||
|
||||
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,
|
||||
);
|
||||
const fallback = firstNonPersonal ?? orgs[0];
|
||||
// note, ignoring case of zero orgs since should never happen
|
||||
|
||||
let selectedOrg: OrgWithProfiles;
|
||||
if (!currentSelection) {
|
||||
selectedOrg = fallback;
|
||||
} else {
|
||||
const match = orgs.find((org) => org.id === currentSelection);
|
||||
if (match) {
|
||||
selectedOrg = match;
|
||||
} else {
|
||||
selectedOrg = fallback;
|
||||
}
|
||||
}
|
||||
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
...selectedOrgs,
|
||||
[workspaceId]: selectedOrg.id,
|
||||
});
|
||||
|
||||
this.organizations = orgs;
|
||||
this.currentOrg = selectedOrg;
|
||||
this.currentProfile = selectedOrg.currentProfile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
|
||||
private async getOrgs(): Promise<OrgWithProfiles[]> {
|
||||
const userId = await this.controlPlaneClient.userId;
|
||||
if (userId) {
|
||||
const orgDescs = await this.controlPlaneClient.listOrganizations();
|
||||
if (await useHub(this.ideSettingsPromise)) {
|
||||
const personalHubOrg = await this.getPersonalHubOrg();
|
||||
const hubOrgs = await Promise.all(
|
||||
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
|
||||
);
|
||||
return [...hubOrgs, personalHubOrg];
|
||||
} else {
|
||||
// Should only ever be one teams org. Will be removed soon anyways
|
||||
return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org)));
|
||||
}
|
||||
} else {
|
||||
return [await this.getLocalOrg()];
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async getNonPersonalHubOrg(
|
||||
org: OrganizationDescription,
|
||||
): Promise<OrgWithProfiles> {
|
||||
const profiles = await this.getHubProfiles(org.id);
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
private PERSONAL_ORG_DESC: OrganizationDescription = {
|
||||
iconUrl: "",
|
||||
id: "personal",
|
||||
name: "Personal",
|
||||
slug: undefined,
|
||||
};
|
||||
private async getPersonalHubOrg() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
const hubProfiles = await this.getHubProfiles(null);
|
||||
const profiles = [...hubProfiles, ...allLocalProfiles];
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
|
||||
}
|
||||
|
||||
private async getLocalOrg() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles);
|
||||
}
|
||||
|
||||
async getTeamsOrg(org: OrganizationDescription): Promise<OrgWithProfiles> {
|
||||
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.llmLogger,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
|
||||
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
|
||||
});
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
private async rectifyProfilesForOrg(
|
||||
org: OrganizationDescription,
|
||||
profiles: ProfileLifecycleManager[],
|
||||
): Promise<OrgWithProfiles> {
|
||||
const profileKey = await this.getProfileKey(org.id);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
async getAllLocalProfiles() {
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
const assistantFiles = await getAllAssistantFiles(this.ide);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
this.llmLogger,
|
||||
assistant,
|
||||
);
|
||||
});
|
||||
return profiles.map(
|
||||
const localAssistantProfiles = profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
);
|
||||
return [this.globalLocalProfileManager, ...localAssistantProfiles];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
//////////////////
|
||||
// External actions that can cause a cascading config refresh
|
||||
// Should not be used internally
|
||||
//////////////////
|
||||
async refreshAll() {
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
get inactiveProfiles() {
|
||||
return (this.profiles ?? []).filter(
|
||||
(p) => p.profileDescription.id !== this.selectedProfileId,
|
||||
);
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.selectedProfileId;
|
||||
const profile = this.profiles?.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
} 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];
|
||||
} else {
|
||||
// Organization
|
||||
profiles = hubProfiles;
|
||||
}
|
||||
}
|
||||
|
||||
await this.updateAvailableProfiles(profiles);
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
} 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),
|
||||
);
|
||||
|
||||
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
|
||||
});
|
||||
|
||||
await this.updateAvailableProfiles(profiles);
|
||||
} catch (e: any) {
|
||||
console.error("Failed to load profiles: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getPersistedSelectedProfileId(): Promise<string | null> {
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const lastSelectedIds =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
return lastSelectedIds[workspaceId] ?? null;
|
||||
}
|
||||
|
||||
async getSelectedOrgId(): Promise<string | null> {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return selectedOrgs[workspaceId] ?? null;
|
||||
}
|
||||
|
||||
async setSelectedOrgId(orgId: string | null) {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
selectedOrgs[await this.getWorkspaceId()] = orgId;
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
|
||||
this.didSelectOrganization?.(orgId);
|
||||
}
|
||||
|
||||
async setSelectedProfile(profileId: string | null) {
|
||||
this.selectedProfileId = profileId;
|
||||
const result = await this.loadConfig();
|
||||
this.notifyConfigListeners(result);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
selectedProfiles[await this.getWorkspaceId()] = profileId;
|
||||
this.globalContext.update(
|
||||
"lastSelectedProfileForWorkspace",
|
||||
selectedProfiles,
|
||||
);
|
||||
}
|
||||
|
||||
// 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("&");
|
||||
}
|
||||
|
||||
// Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed
|
||||
updateIdeSettings(ideSettings: IdeSettings) {
|
||||
// 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 +318,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 +420,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 +438,6 @@ export class ConfigHandler {
|
|||
);
|
||||
}
|
||||
|
||||
listProfiles(): ProfileDescription[] | null {
|
||||
return this.profiles?.map((p) => p.profileDescription) ?? null;
|
||||
}
|
||||
|
||||
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
|
|
@ -482,28 +451,36 @@ export class ConfigHandler {
|
|||
);
|
||||
}
|
||||
|
||||
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");
|
||||
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}`);
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
// 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>;
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
||||
|
|
@ -27,6 +26,7 @@ import {
|
|||
IdeSettings,
|
||||
IdeType,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
LLMOptions,
|
||||
ModelDescription,
|
||||
RerankerDescription,
|
||||
|
|
@ -37,7 +37,6 @@ import {
|
|||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
} from "../commands/index";
|
||||
import { AllRerankers } from "../context/allRerankers";
|
||||
import { MCPManagerSingleton } from "../context/mcp";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
|
||||
|
|
@ -45,9 +44,8 @@ import CustomContextProviderClass from "../context/providers/CustomContextProvid
|
|||
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";
|
||||
|
|
@ -72,7 +70,11 @@ 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(
|
||||
|
|
@ -216,17 +218,27 @@ 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
|
||||
|
|
@ -238,7 +250,7 @@ async function intermediateToFinalConfig(
|
|||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
config.systemMessage,
|
||||
);
|
||||
|
|
@ -260,7 +272,7 @@ async function intermediateToFinalConfig(
|
|||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
copyOf(config.completionOptions),
|
||||
config.systemMessage,
|
||||
);
|
||||
|
|
@ -280,7 +292,7 @@ async function intermediateToFinalConfig(
|
|||
} else {
|
||||
const llm = new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, writeLog } as any,
|
||||
options: { ...desc.options, logger: llmLogger } as any,
|
||||
});
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
|
|
@ -289,7 +301,11 @@ async function intermediateToFinalConfig(
|
|||
(modelName) =>
|
||||
new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, model: modelName, writeLog },
|
||||
options: {
|
||||
...desc.options,
|
||||
model: modelName,
|
||||
logger: llmLogger,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
@ -343,7 +359,7 @@ async function intermediateToFinalConfig(
|
|||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
config.systemMessage,
|
||||
);
|
||||
|
|
@ -420,38 +436,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 +474,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 +491,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,
|
||||
...params,
|
||||
};
|
||||
return new cls(llmOptions);
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Unknown reranking provider ${name}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -499,7 +513,6 @@ async function intermediateToFinalConfig(
|
|||
const continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
models,
|
||||
tools: [...allTools],
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: config.slashCommands ?? [],
|
||||
|
|
@ -539,7 +552,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 +571,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) {
|
||||
|
|
@ -598,10 +611,12 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
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,7 +626,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(
|
||||
|
|
@ -831,7 +845,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>> {
|
||||
|
|
@ -925,15 +939,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],
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
ContinueConfig,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
SerializedContinueConfig,
|
||||
} from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
|
@ -27,7 +28,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
private readonly controlPlaneClient: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
private llmLogger: ILLMLogger,
|
||||
private readonly onReload: () => void,
|
||||
) {
|
||||
this.description = {
|
||||
|
|
@ -61,18 +62,18 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
)) as any);
|
||||
const serializedConfig: SerializedContinueConfig = settings;
|
||||
|
||||
return await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
serializedConfig,
|
||||
undefined,
|
||||
undefined,
|
||||
this.workspaceId,
|
||||
undefined,
|
||||
null,
|
||||
);
|
||||
return await doLoadConfig({
|
||||
ide: this.ide,
|
||||
ideSettingsPromise: this.ideSettingsPromise,
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
llmLogger: this.llmLogger,
|
||||
overrideConfigJson: serializedConfig,
|
||||
overrideConfigYaml: undefined,
|
||||
platformConfigMetadata: undefined,
|
||||
profileId: this.workspaceId,
|
||||
overrideConfigYamlByPath: undefined,
|
||||
orgScopeId: 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,18 @@ 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,
|
||||
overrideConfigJson: undefined,
|
||||
overrideConfigYaml: undefined,
|
||||
platformConfigMetadata: undefined,
|
||||
profileId: this.description.id,
|
||||
overrideConfigYamlByPath: this.overrideAssistantFile?.path,
|
||||
orgScopeId: null,
|
||||
});
|
||||
|
||||
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,21 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
};
|
||||
}
|
||||
|
||||
const results = await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
undefined,
|
||||
this.configResult.config,
|
||||
{
|
||||
const results = await doLoadConfig({
|
||||
ide: this.ide,
|
||||
ideSettingsPromise: this.ideSettingsPromise,
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
llmLogger: this.llmLogger,
|
||||
overrideConfigJson: undefined,
|
||||
overrideConfigYaml: this.configResult.config,
|
||||
platformConfigMetadata: {
|
||||
ownerSlug: this.ownerSlug,
|
||||
packageSlug: this.packageSlug,
|
||||
},
|
||||
this.description.id,
|
||||
undefined,
|
||||
this.orgScopeId,
|
||||
);
|
||||
profileId: this.description.id,
|
||||
overrideConfigYamlByPath: undefined,
|
||||
orgScopeId: this.orgScopeId,
|
||||
});
|
||||
|
||||
return {
|
||||
config: results.config,
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
ContinueRcJson,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
SerializedContinueConfig,
|
||||
Tool,
|
||||
} from "../../";
|
||||
|
|
@ -35,18 +36,29 @@ import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
|
|||
|
||||
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
|
||||
|
||||
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>> {
|
||||
export default async function doLoadConfig({
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
overrideConfigJson,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
profileId,
|
||||
overrideConfigYamlByPath,
|
||||
orgScopeId,
|
||||
}: {
|
||||
ide: IDE;
|
||||
ideSettingsPromise: Promise<IdeSettings>;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
llmLogger: ILLMLogger;
|
||||
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 +81,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,
|
||||
);
|
||||
});
|
||||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
configLoadInterrupted = result.configLoadInterrupted;
|
||||
|
|
@ -92,7 +103,7 @@ export default async function doLoadConfig(
|
|||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigJson,
|
||||
);
|
||||
|
|
@ -160,6 +171,7 @@ export default async function doLoadConfig(
|
|||
const serverContextProvider = new MCPContextProvider({
|
||||
submenuItems,
|
||||
mcpId: server.id,
|
||||
serverName: server.name,
|
||||
});
|
||||
newConfig.contextProviders.push(serverContextProvider);
|
||||
}
|
||||
|
|
@ -256,7 +268,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;
|
||||
|
|
@ -433,6 +433,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 +534,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;
|
||||
|
|
|
|||
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",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -7,6 +7,7 @@ import {
|
|||
IDE,
|
||||
ILLM,
|
||||
ModelDescription,
|
||||
PromptTemplate,
|
||||
} from "../";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigFile } from "../util/paths";
|
||||
|
|
@ -94,7 +95,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 +170,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];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
FQSN,
|
||||
isAssistantUnrolledNonNullable,
|
||||
ModelRole,
|
||||
PlatformClient,
|
||||
RegistryClient,
|
||||
|
|
@ -12,7 +13,6 @@ import {
|
|||
unrollAssistantFromContent,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
|
||||
import {
|
||||
ContinueConfig,
|
||||
|
|
@ -20,16 +20,15 @@ import {
|
|||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
} from "../..";
|
||||
import { slashFromCustomCommand } from "../../commands";
|
||||
import { AllRerankers } from "../../context/allRerankers";
|
||||
import { MCPManagerSingleton } from "../../context/mcp";
|
||||
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";
|
||||
|
|
@ -92,7 +91,15 @@ async function loadConfigYaml(
|
|||
renderSecrets: true,
|
||||
},
|
||||
));
|
||||
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 +117,32 @@ 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({
|
||||
config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
allowFreeTrial = true,
|
||||
}: {
|
||||
config: AssistantUnrolled;
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
allowFreeTrial: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
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 +154,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,7 +162,38 @@ async function configYamlToContinueConfig(
|
|||
rerank: null,
|
||||
summarize: null,
|
||||
},
|
||||
data: config.data,
|
||||
};
|
||||
|
||||
// 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,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
continueConfig.data = config.data;
|
||||
continueConfig.rules = config.rules;
|
||||
continueConfig.docs = config.docs?.map((doc) => ({
|
||||
title: doc.name,
|
||||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
}));
|
||||
continueConfig.experimental = {
|
||||
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: mcpServer.command,
|
||||
args: mcpServer.args ?? [],
|
||||
env: mcpServer.env,
|
||||
},
|
||||
})),
|
||||
};
|
||||
|
||||
// Prompt files -
|
||||
|
|
@ -211,19 +240,15 @@ async function configYamlToContinueConfig(
|
|||
for (const model of config.models ?? []) {
|
||||
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
|
||||
try {
|
||||
const llms = await llmsFromModelConfig(
|
||||
const llms = await llmsFromModelConfig({
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
continueConfig.systemMessage,
|
||||
);
|
||||
|
||||
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
|
||||
continueConfig.models.push(...llms);
|
||||
}
|
||||
config: continueConfig,
|
||||
});
|
||||
|
||||
if (model.roles?.includes("chat")) {
|
||||
continueConfig.modelsByRole.chat.push(...llms);
|
||||
|
|
@ -246,59 +271,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 +313,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 +328,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",
|
||||
);
|
||||
}
|
||||
|
|
@ -407,19 +399,31 @@ 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>> {
|
||||
export async function loadContinueConfigFromYaml({
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
// workOsAccessToken,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
configYamlPath,
|
||||
orgScopeId,
|
||||
}: {
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
// 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(
|
||||
|
|
@ -445,16 +449,16 @@ export async function loadContinueConfigFromYaml(
|
|||
}
|
||||
|
||||
const { config: continueConfig, errors: localErrors } =
|
||||
await configYamlToContinueConfig(
|
||||
configYamlResult.config,
|
||||
await configYamlToContinueConfig({
|
||||
config: configYamlResult.config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
workOsAccessToken,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
);
|
||||
allowFreeTrial: true,
|
||||
});
|
||||
|
||||
try {
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,12 @@
|
|||
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";
|
||||
|
|
@ -13,22 +19,29 @@ 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,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM | undefined> {
|
||||
const cls = getModelClass(model);
|
||||
|
||||
if (!cls) {
|
||||
|
|
@ -39,7 +52,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 +60,13 @@ async function modelConfigToBaseLLM(
|
|||
model.defaultCompletionOptions?.maxTokens ??
|
||||
cls.defaultOptions?.completionOptions?.maxTokens,
|
||||
},
|
||||
writeLog,
|
||||
logger: llmLogger,
|
||||
uniqueId,
|
||||
title: model.name,
|
||||
systemMessage,
|
||||
systemMessage: config.systemMessage,
|
||||
rules: config.rules,
|
||||
promptTemplates: model.promptTemplates,
|
||||
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
|
||||
capabilities: {
|
||||
tools: model.capabilities?.includes("tool_use"),
|
||||
uploadImage: model.capabilities?.includes("image_input"),
|
||||
|
|
@ -127,16 +142,25 @@ 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,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
llm: BaseLLM;
|
||||
model: ModelConfig;
|
||||
ide: IDE;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const detectedModels = await Promise.all(
|
||||
|
|
@ -146,18 +170,18 @@ async function autodetectModels(
|
|||
return undefined;
|
||||
}
|
||||
|
||||
return await modelConfigToBaseLLM(
|
||||
{
|
||||
return await modelConfigToBaseLLM({
|
||||
model: {
|
||||
...model,
|
||||
model: modelName,
|
||||
name: modelName,
|
||||
},
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
config,
|
||||
});
|
||||
}),
|
||||
);
|
||||
return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[];
|
||||
|
|
@ -167,38 +191,46 @@ 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,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
ide: IDE;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM({
|
||||
model,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
config,
|
||||
});
|
||||
if (!baseLlm) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (model.model === AUTODETECT) {
|
||||
const models = await autodetectModels(
|
||||
baseLlm,
|
||||
const models = await autodetectModels({
|
||||
llm: baseLlm,
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
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,
|
||||
};
|
||||
|
|
@ -35,7 +35,7 @@ class FolderContextProvider extends BaseContextProvider {
|
|||
const folders = await walkDirs(
|
||||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
include: "dirs",
|
||||
source: "load submenu items - folder",
|
||||
},
|
||||
workspaceDirs,
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { MCPManagerSingleton } from "../mcp";
|
|||
|
||||
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: [],
|
||||
};
|
||||
|
|
|
|||
687
core/core.ts
687
core/core.ts
|
|
@ -5,11 +5,6 @@ import { v4 as uuidv4 } from "uuid";
|
|||
import { CompletionProvider } from "./autocomplete/CompletionProvider";
|
||||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
|
||||
import {
|
||||
setupBestConfig,
|
||||
setupLocalConfig,
|
||||
setupQuickstartConfig,
|
||||
} from "./config/onboarding";
|
||||
import { addModel, deleteModel } from "./config/util";
|
||||
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
|
||||
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
|
||||
|
|
@ -19,9 +14,9 @@ import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
|||
import { getControlPlaneEnv } from "./control-plane/env";
|
||||
import { DevDataSqliteDb } from "./data/devdataSqlite";
|
||||
import { DataLogger } from "./data/log";
|
||||
import { streamDiffLines } from "./edit/streamDiffLines";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
|
||||
import DocsService from "./indexing/docs/DocsService";
|
||||
import { countTokens } from "./llm/countTokens";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
|
||||
import { callTool } from "./tools/callTool";
|
||||
|
|
@ -36,6 +31,9 @@ import { TTS } from "./util/tts";
|
|||
|
||||
import {
|
||||
DiffLine,
|
||||
IdeSettings,
|
||||
ModelDescription,
|
||||
RangeInFile,
|
||||
type ContextItemId,
|
||||
type IDE,
|
||||
type IndexingProgressUpdate,
|
||||
|
|
@ -43,13 +41,51 @@ import {
|
|||
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
|
||||
import {
|
||||
setupBestConfig,
|
||||
setupLocalConfig,
|
||||
setupQuickstartConfig,
|
||||
} from "./config/onboarding";
|
||||
import { MCPManagerSingleton } from "./context/mcp";
|
||||
import { streamDiffLines } from "./edit/streamDiffLines";
|
||||
import { shouldIgnore } from "./indexing/shouldIgnore";
|
||||
import { walkDirCache } from "./indexing/walkDir";
|
||||
import { LLMLogger } from "./llm/logger";
|
||||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
||||
async function* streamDiffLinesGenerator(
|
||||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
const data = msg.data;
|
||||
const llm = (await configHandler.loadConfig()).config?.selectedModelByRole
|
||||
.chat;
|
||||
|
||||
if (!llm) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
for await (const diffLine of streamDiffLines(
|
||||
data.prefix,
|
||||
data.highlighted,
|
||||
data.suffix,
|
||||
llm,
|
||||
data.input,
|
||||
data.language,
|
||||
false,
|
||||
undefined,
|
||||
)) {
|
||||
if (abortedMessageIds.has(msg.messageId)) {
|
||||
abortedMessageIds.delete(msg.messageId);
|
||||
break;
|
||||
}
|
||||
yield diffLine;
|
||||
}
|
||||
}
|
||||
|
||||
export class Core {
|
||||
configHandler: ConfigHandler;
|
||||
codebaseIndexerPromise: Promise<CodebaseIndexer>;
|
||||
|
|
@ -58,6 +94,7 @@ export class Core {
|
|||
codebaseIndexingState: IndexingProgressUpdate;
|
||||
private docsService: DocsService;
|
||||
private globalContext = new GlobalContext();
|
||||
llmLogger = new LLMLogger();
|
||||
|
||||
private readonly indexingPauseToken = new PauseToken(
|
||||
this.globalContext.get("indexingPaused") === true,
|
||||
|
|
@ -85,7 +122,6 @@ export class Core {
|
|||
constructor(
|
||||
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
private readonly ide: IDE,
|
||||
private readonly onWrite: (text: string) => Promise<void> = async () => {},
|
||||
) {
|
||||
// Ensure .continue directory is created
|
||||
migrateV1DevDataFiles();
|
||||
|
|
@ -106,13 +142,8 @@ export class Core {
|
|||
this.configHandler = new ConfigHandler(
|
||||
this.ide,
|
||||
ideSettingsPromise,
|
||||
this.onWrite,
|
||||
this.llmLogger,
|
||||
sessionInfoPromise,
|
||||
(orgId: string | null) => {
|
||||
void messenger.request("didSelectOrganization", {
|
||||
orgId,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
this.docsService = DocsService.createSingleton(
|
||||
|
|
@ -121,10 +152,7 @@ export class Core {
|
|||
this.messenger,
|
||||
);
|
||||
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.onConnectionsRefreshed = async () => {
|
||||
// This ensures that it triggers a NEW load after waiting for config promise to finish
|
||||
await this.configHandler.loadConfig();
|
||||
MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => {
|
||||
await this.configHandler.reloadConfig();
|
||||
};
|
||||
|
||||
|
|
@ -133,7 +161,11 @@ export class Core {
|
|||
this.messenger.send("configUpdate", {
|
||||
result: serializedResult,
|
||||
profileId:
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null,
|
||||
this.configHandler.currentProfile?.profileDescription.id || null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
usingContinueForTeams: (await ideSettingsPromise)
|
||||
.enableControlServerBeta,
|
||||
});
|
||||
|
||||
// update additional submenu context providers registered via VSCode API
|
||||
|
|
@ -146,14 +178,6 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
this.configHandler.onDidChangeAvailableProfiles(
|
||||
(profiles, selectedProfileId) =>
|
||||
this.messenger.send("didChangeAvailableProfiles", {
|
||||
profiles,
|
||||
selectedProfileId,
|
||||
}),
|
||||
);
|
||||
|
||||
// Dev Data Logger
|
||||
const dataLogger = DataLogger.getInstance();
|
||||
dataLogger.core = this;
|
||||
|
|
@ -219,6 +243,10 @@ export class Core {
|
|||
(..._) => Promise.resolve([]),
|
||||
);
|
||||
|
||||
this.registerMessageHandlers(ideSettingsPromise);
|
||||
}
|
||||
|
||||
private registerMessageHandlers(ideSettingsPromise: Promise<IdeSettings>) {
|
||||
const on = this.messenger.on.bind(this.messenger);
|
||||
|
||||
// Note, VsCode's in-process messenger doesn't do anything with this
|
||||
|
|
@ -308,15 +336,8 @@ export class Core {
|
|||
this.configHandler.updateIdeSettings(msg.data);
|
||||
});
|
||||
|
||||
on("config/listProfiles", async (msg) => {
|
||||
const profiles = this.configHandler.listProfiles();
|
||||
const selectedProfileId =
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null;
|
||||
return { profiles, selectedProfileId };
|
||||
});
|
||||
|
||||
on("config/refreshProfiles", async (msg) => {
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
await this.configHandler.refreshAll();
|
||||
});
|
||||
|
||||
on("config/updateSharedConfig", async (msg) => {
|
||||
|
|
@ -344,12 +365,8 @@ export class Core {
|
|||
await this.messenger.request("openUrl", url);
|
||||
});
|
||||
|
||||
on("controlPlane/listOrganizations", async (msg) => {
|
||||
return await this.configHandler.listOrganizations();
|
||||
});
|
||||
|
||||
on("mcp/reloadServer", async (msg) => {
|
||||
mcpManager.refreshConnection(msg.data.id);
|
||||
MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
});
|
||||
// Context providers
|
||||
on("context/addDocs", async (msg) => {
|
||||
|
|
@ -381,94 +398,7 @@ export class Core {
|
|||
return items || [];
|
||||
});
|
||||
|
||||
on("context/getContextItems", async (msg) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const { name, query, fullInput, selectedCode, selectedModelTitle } =
|
||||
msg.data;
|
||||
|
||||
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
|
||||
const provider =
|
||||
config.contextProviders?.find(
|
||||
(provider) => provider.description.title === name,
|
||||
) ??
|
||||
[
|
||||
// user doesn't need these in their config.json for the shortcuts to work
|
||||
// option+enter
|
||||
new CurrentFileContextProvider({}),
|
||||
// cmd+enter
|
||||
new CodebaseContextProvider({}),
|
||||
].find((provider) => provider.description.title === name);
|
||||
if (!provider) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const id: ContextItemId = {
|
||||
providerTitle: provider.description.title,
|
||||
itemId: uuidv4(),
|
||||
};
|
||||
|
||||
const items = await provider.getContextItems(query, {
|
||||
config,
|
||||
llm,
|
||||
embeddingsProvider: config.selectedModelByRole.embed,
|
||||
fullInput,
|
||||
ide,
|
||||
selectedCode,
|
||||
reranker: config.selectedModelByRole.rerank,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
});
|
||||
|
||||
void Telemetry.capture(
|
||||
"useContextProvider",
|
||||
{
|
||||
name: provider.description.title,
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
return items.map((item) => ({
|
||||
...item,
|
||||
id,
|
||||
}));
|
||||
} catch (e) {
|
||||
let knownError = false;
|
||||
|
||||
if (e instanceof Error) {
|
||||
// After removing transformers JS embeddings provider from jetbrains
|
||||
// Should no longer see this error
|
||||
// if (e.message.toLowerCase().includes("embeddings provider")) {
|
||||
// knownError = true;
|
||||
// const toastOption = "See Docs";
|
||||
// void this.ide
|
||||
// .showToast(
|
||||
// "error",
|
||||
// `Set up an embeddings model to use @${name}`,
|
||||
// toastOption,
|
||||
// )
|
||||
// .then((userSelection) => {
|
||||
// if (userSelection === toastOption) {
|
||||
// void this.ide.openUrl(
|
||||
// "https://docs.continue.dev/customize/model-roles/embeddings",
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
}
|
||||
if (!knownError) {
|
||||
void this.ide.showToast(
|
||||
"error",
|
||||
`Error getting context items from ${name}: ${e}`,
|
||||
);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
});
|
||||
on("context/getContextItems", this.getContextItems.bind(this));
|
||||
|
||||
on("context/getSymbolsForFiles", async (msg) => {
|
||||
const { uris } = msg.data;
|
||||
|
|
@ -480,6 +410,10 @@ export class Core {
|
|||
result: await this.configHandler.getSerializedConfig(),
|
||||
profileId:
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
usingContinueForTeams: (await ideSettingsPromise)
|
||||
.enableControlServerBeta,
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -497,13 +431,19 @@ export class Core {
|
|||
this.configHandler,
|
||||
this.abortedMessageIds,
|
||||
msg,
|
||||
ide,
|
||||
this.ide,
|
||||
this.messenger,
|
||||
),
|
||||
);
|
||||
|
||||
on("llm/complete", async (msg) => {
|
||||
const model = await this.configHandler.llmFromTitle(msg.data.title);
|
||||
const model = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
if (!model) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
const completion = await model.complete(
|
||||
msg.data.prompt,
|
||||
new AbortController().signal,
|
||||
|
|
@ -511,31 +451,7 @@ export class Core {
|
|||
);
|
||||
return completion;
|
||||
});
|
||||
on("llm/listModels", async (msg) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const model =
|
||||
config.models.find((model) => model.title === msg.data.title) ??
|
||||
config.models.find((model) => model.title?.startsWith(msg.data.title));
|
||||
try {
|
||||
if (model) {
|
||||
return await model.listModels();
|
||||
} else {
|
||||
if (msg.data.title === "Ollama") {
|
||||
const models = await new Ollama({ model: "" }).listModels();
|
||||
return models;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.debug(`Error listing Ollama models: ${e}`);
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
on("llm/listModels", this.handleListModels);
|
||||
|
||||
// Provide messenger to utils so they can interact with GUI + state
|
||||
TTS.messenger = this.messenger;
|
||||
|
|
@ -546,9 +462,13 @@ export class Core {
|
|||
});
|
||||
|
||||
on("chatDescriber/describe", async (msg) => {
|
||||
const currentModel = await this.configHandler.llmFromTitle(
|
||||
msg.data.selectedModelTitle,
|
||||
);
|
||||
const currentModel = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
if (!currentModel) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
return await ChatDescriber.describe(currentModel, {}, msg.data.text);
|
||||
});
|
||||
|
||||
|
|
@ -568,93 +488,13 @@ export class Core {
|
|||
this.completionProvider.cancel();
|
||||
});
|
||||
|
||||
async function* streamDiffLinesGenerator(
|
||||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
const data = msg.data;
|
||||
const llm = await configHandler.llmFromTitle(msg.data.modelTitle);
|
||||
for await (const diffLine of streamDiffLines(
|
||||
data.prefix,
|
||||
data.highlighted,
|
||||
data.suffix,
|
||||
llm,
|
||||
data.input,
|
||||
data.language,
|
||||
false,
|
||||
undefined,
|
||||
)) {
|
||||
if (abortedMessageIds.has(msg.messageId)) {
|
||||
abortedMessageIds.delete(msg.messageId);
|
||||
break;
|
||||
}
|
||||
yield diffLine;
|
||||
}
|
||||
}
|
||||
|
||||
on("streamDiffLines", (msg) =>
|
||||
streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
|
||||
);
|
||||
|
||||
on("completeOnboarding", (msg) => {
|
||||
const mode = msg.data.mode;
|
||||
on("completeOnboarding", this.handleCompleteOnboarding);
|
||||
|
||||
if (mode === "Custom") {
|
||||
return;
|
||||
}
|
||||
|
||||
let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
|
||||
|
||||
switch (mode) {
|
||||
case "Local":
|
||||
editConfigYamlCallback = setupLocalConfig;
|
||||
break;
|
||||
|
||||
case "Quickstart":
|
||||
editConfigYamlCallback = setupQuickstartConfig;
|
||||
break;
|
||||
|
||||
case "Best":
|
||||
editConfigYamlCallback = setupBestConfig;
|
||||
break;
|
||||
|
||||
default:
|
||||
console.error(`Invalid mode: ${mode}`);
|
||||
editConfigYamlCallback = (config) => config;
|
||||
}
|
||||
|
||||
editConfigFile((c) => c, editConfigYamlCallback);
|
||||
|
||||
void this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("addAutocompleteModel", (msg) => {
|
||||
const model = msg.data.model;
|
||||
editConfigFile(
|
||||
(config) => {
|
||||
return {
|
||||
...config,
|
||||
tabAutocompleteModel: model,
|
||||
};
|
||||
},
|
||||
(config) => ({
|
||||
...config,
|
||||
models: [
|
||||
...(config.models ?? []),
|
||||
{
|
||||
name: model.title,
|
||||
provider: model.provider,
|
||||
model: model.model,
|
||||
apiKey: model.apiKey,
|
||||
roles: ["autocomplete"],
|
||||
apiBase: model.apiBase,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
void this.configHandler.reloadConfig();
|
||||
});
|
||||
on("addAutocompleteModel", this.handleAddAutocompleteModel);
|
||||
|
||||
on("stats/getTokensPerDay", async (msg) => {
|
||||
const rows = await DevDataSqliteDb.getTokensPerDay();
|
||||
|
|
@ -665,7 +505,6 @@ export class Core {
|
|||
return rows;
|
||||
});
|
||||
|
||||
// Codebase indexing
|
||||
on("index/forceReIndex", async ({ data }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config || config.disableIndexing) {
|
||||
|
|
@ -697,63 +536,12 @@ export class Core {
|
|||
|
||||
// File changes
|
||||
// TODO - remove remaining logic for these from IDEs where possible
|
||||
on("files/changed", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
|
||||
for (const uri of data.uris) {
|
||||
const currentProfileUri =
|
||||
this.configHandler.currentProfile?.profileDescription.uri ?? "";
|
||||
|
||||
if (URI.equal(uri, currentProfileUri)) {
|
||||
// Trigger a toast notification to provide UI feedback that config has been updated
|
||||
const showToast =
|
||||
this.globalContext.get("showConfigUpdateToast") ?? true;
|
||||
if (showToast) {
|
||||
const selection = await this.ide.showToast(
|
||||
"info",
|
||||
"Config updated",
|
||||
"Don't show again",
|
||||
);
|
||||
if (selection === "Don't show again") {
|
||||
this.globalContext.update("showConfigUpdateToast", false);
|
||||
}
|
||||
}
|
||||
await this.configHandler.reloadConfig();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE)
|
||||
) {
|
||||
await this.configHandler.reloadConfig();
|
||||
} else if (
|
||||
uri.endsWith(".continueignore") ||
|
||||
uri.endsWith(".gitignore")
|
||||
) {
|
||||
// Reindex the workspaces
|
||||
this.invoke("index/forceReIndex", {
|
||||
shouldClearIndexes: true,
|
||||
});
|
||||
} else {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (config && !config.disableIndexing) {
|
||||
// Reindex the file
|
||||
const ignore = await shouldIgnore(uri, this.ide);
|
||||
if (!ignore) {
|
||||
await this.refreshCodebaseIndexFiles([uri]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
on("files/changed", this.handleFilesChanged);
|
||||
|
||||
const refreshIfNotIgnored = async (uris: string[]) => {
|
||||
const toRefresh: string[] = [];
|
||||
for (const uri of uris) {
|
||||
const ignore = await shouldIgnore(uri, ide);
|
||||
const ignore = await shouldIgnore(uri, this.ide);
|
||||
if (!ignore) {
|
||||
toRefresh.push(uri);
|
||||
}
|
||||
|
|
@ -775,11 +563,15 @@ export class Core {
|
|||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
|
||||
let localAssistantCreated = false;
|
||||
for (const uri of data.uris) {
|
||||
if (isLocalAssistantFile(uri)) {
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
localAssistantCreated = true;
|
||||
}
|
||||
}
|
||||
if (localAssistantCreated) {
|
||||
await this.configHandler.refreshAll();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -798,11 +590,7 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
on("files/opened", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
// Do something on files opened
|
||||
}
|
||||
});
|
||||
on("files/opened", async () => {});
|
||||
|
||||
// Docs, etc. indexing
|
||||
on("indexing/reindex", async (msg) => {
|
||||
|
|
@ -817,7 +605,6 @@ export class Core {
|
|||
});
|
||||
on("indexing/setPaused", async (msg) => {
|
||||
if (msg.data.type === "docs") {
|
||||
// this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet
|
||||
}
|
||||
});
|
||||
on("docs/initStatuses", async (msg) => {
|
||||
|
|
@ -829,20 +616,14 @@ export class Core {
|
|||
//
|
||||
|
||||
on("didChangeSelectedProfile", async (msg) => {
|
||||
await this.configHandler.setSelectedProfile(msg.data.id);
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.setSelectedProfileId(msg.data.id);
|
||||
});
|
||||
|
||||
on("didChangeSelectedOrg", async (msg) => {
|
||||
await this.configHandler.setSelectedOrgId(msg.data.id);
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
if (msg.data.profileId) {
|
||||
this.invoke("didChangeSelectedProfile", {
|
||||
id: msg.data.profileId,
|
||||
});
|
||||
} else {
|
||||
await this.configHandler.reloadConfig();
|
||||
}
|
||||
await this.configHandler.setSelectedOrgId(
|
||||
msg.data.id,
|
||||
msg.data.profileId,
|
||||
);
|
||||
});
|
||||
|
||||
on("didChangeControlPlaneSessionInfo", async (msg) => {
|
||||
|
|
@ -850,6 +631,7 @@ export class Core {
|
|||
msg.data.sessionInfo,
|
||||
);
|
||||
});
|
||||
|
||||
on("auth/getAuthUrl", async (msg) => {
|
||||
const url = await getAuthUrlForTokenPage(
|
||||
ideSettingsPromise,
|
||||
|
|
@ -885,7 +667,12 @@ export class Core {
|
|||
throw new Error(`Tool ${toolCall.function.name} not found`);
|
||||
}
|
||||
|
||||
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
|
||||
const llm = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
if (!llm) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
const contextItems = await callTool(
|
||||
tool,
|
||||
|
|
@ -907,8 +694,284 @@ export class Core {
|
|||
|
||||
return { contextItems };
|
||||
});
|
||||
|
||||
on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
|
||||
if (!config) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const llm = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
if (!llm) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
const tokens = countTokens(item.content);
|
||||
|
||||
if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
private handleAddAutocompleteModel(
|
||||
msg: Message<{
|
||||
model: ModelDescription;
|
||||
}>,
|
||||
) {
|
||||
const model = msg.data.model;
|
||||
editConfigFile(
|
||||
(config) => {
|
||||
return {
|
||||
...config,
|
||||
tabAutocompleteModel: model,
|
||||
};
|
||||
},
|
||||
(config) => ({
|
||||
...config,
|
||||
models: [
|
||||
...(config.models ?? []),
|
||||
{
|
||||
name: model.title,
|
||||
provider: model.provider,
|
||||
model: model.model,
|
||||
apiKey: model.apiKey,
|
||||
roles: ["autocomplete"],
|
||||
apiBase: model.apiBase,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
void this.configHandler.reloadConfig();
|
||||
}
|
||||
|
||||
private async handleFilesChanged({
|
||||
data,
|
||||
}: Message<{
|
||||
uris?: string[];
|
||||
}>) {
|
||||
if (data?.uris?.length) {
|
||||
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
|
||||
for (const uri of data.uris) {
|
||||
const currentProfileUri =
|
||||
this.configHandler.currentProfile?.profileDescription.uri ?? "";
|
||||
|
||||
if (URI.equal(uri, currentProfileUri)) {
|
||||
// Trigger a toast notification to provide UI feedback that config has been updated
|
||||
const showToast =
|
||||
this.globalContext.get("showConfigUpdateToast") ?? true;
|
||||
if (showToast) {
|
||||
const selection = await this.ide.showToast(
|
||||
"info",
|
||||
"Config updated",
|
||||
"Don't show again",
|
||||
);
|
||||
if (selection === "Don't show again") {
|
||||
this.globalContext.update("showConfigUpdateToast", false);
|
||||
}
|
||||
}
|
||||
await this.configHandler.reloadConfig();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE)
|
||||
) {
|
||||
await this.configHandler.reloadConfig();
|
||||
} else if (
|
||||
uri.endsWith(".continueignore") ||
|
||||
uri.endsWith(".gitignore")
|
||||
) {
|
||||
// Reindex the workspaces
|
||||
this.invoke("index/forceReIndex", {
|
||||
shouldClearIndexes: true,
|
||||
});
|
||||
} else {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (config && !config.disableIndexing) {
|
||||
// Reindex the file
|
||||
const ignore = await shouldIgnore(uri, this.ide);
|
||||
if (!ignore) {
|
||||
await this.refreshCodebaseIndexFiles([uri]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async handleListModels(msg: Message<{ title: string }>) {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const model =
|
||||
config.modelsByRole.chat.find(
|
||||
(model) => model.title === msg.data.title,
|
||||
) ??
|
||||
config.modelsByRole.chat.find((model) =>
|
||||
model.title?.startsWith(msg.data.title),
|
||||
);
|
||||
|
||||
try {
|
||||
if (model) {
|
||||
return await model.listModels();
|
||||
} else {
|
||||
if (msg.data.title === "Ollama") {
|
||||
const models = await new Ollama({ model: "" }).listModels();
|
||||
return models;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.debug(`Error listing Ollama models: ${e}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleCompleteOnboarding(msg: Message<{ mode: string }>) {
|
||||
const mode = msg.data.mode;
|
||||
|
||||
if (mode === "Custom") {
|
||||
return;
|
||||
}
|
||||
|
||||
let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
|
||||
|
||||
switch (mode) {
|
||||
case "Local":
|
||||
editConfigYamlCallback = setupLocalConfig;
|
||||
break;
|
||||
|
||||
case "Quickstart":
|
||||
editConfigYamlCallback = setupQuickstartConfig;
|
||||
break;
|
||||
|
||||
case "Best":
|
||||
editConfigYamlCallback = setupBestConfig;
|
||||
break;
|
||||
|
||||
default:
|
||||
console.error(`Invalid mode: ${mode}`);
|
||||
editConfigYamlCallback = (config) => config;
|
||||
}
|
||||
|
||||
editConfigFile((c) => c, editConfigYamlCallback);
|
||||
|
||||
void this.configHandler.reloadConfig();
|
||||
}
|
||||
|
||||
private getContextItems = async (
|
||||
msg: Message<{
|
||||
name: string;
|
||||
query: string;
|
||||
fullInput: string;
|
||||
selectedCode: RangeInFile[];
|
||||
selectedModelTitle: string;
|
||||
}>,
|
||||
) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const { name, query, fullInput, selectedCode } = msg.data;
|
||||
|
||||
const llm = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
if (!llm) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
const provider =
|
||||
config.contextProviders?.find(
|
||||
(provider) => provider.description.title === name,
|
||||
) ??
|
||||
[
|
||||
// user doesn't need these in their config.json for the shortcuts to work
|
||||
// option+enter
|
||||
new CurrentFileContextProvider({}),
|
||||
// cmd+enter
|
||||
new CodebaseContextProvider({}),
|
||||
].find((provider) => provider.description.title === name);
|
||||
if (!provider) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const id: ContextItemId = {
|
||||
providerTitle: provider.description.title,
|
||||
itemId: uuidv4(),
|
||||
};
|
||||
|
||||
const items = await provider.getContextItems(query, {
|
||||
config,
|
||||
llm,
|
||||
embeddingsProvider: config.selectedModelByRole.embed,
|
||||
fullInput,
|
||||
ide: this.ide,
|
||||
selectedCode,
|
||||
reranker: config.selectedModelByRole.rerank,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
});
|
||||
|
||||
void Telemetry.capture(
|
||||
"useContextProvider",
|
||||
{
|
||||
name: provider.description.title,
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
return items.map((item) => ({
|
||||
...item,
|
||||
id,
|
||||
}));
|
||||
} catch (e) {
|
||||
let knownError = false;
|
||||
|
||||
if (e instanceof Error) {
|
||||
// After removing transformers JS embeddings provider from jetbrains
|
||||
// Should no longer see this error
|
||||
// if (e.message.toLowerCase().includes("embeddings provider")) {
|
||||
// knownError = true;
|
||||
// const toastOption = "See Docs";
|
||||
// void this.ide
|
||||
// .showToast(
|
||||
// "error",
|
||||
// `Set up an embeddings model to use @${name}`,
|
||||
// toastOption,
|
||||
// )
|
||||
// .then((userSelection) => {
|
||||
// if (userSelection === toastOption) {
|
||||
// void this.ide.openUrl(
|
||||
// "https://docs.continue.dev/customize/model-roles/embeddings",
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
}
|
||||
if (!knownError) {
|
||||
void this.ide.showToast(
|
||||
"error",
|
||||
`Error getting context items from ${name}: ${e}`,
|
||||
);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
|
||||
console.debug(
|
||||
|
|
|
|||
151
core/index.d.ts
vendored
151
core/index.d.ts
vendored
|
|
@ -1,6 +1,8 @@
|
|||
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
|
||||
import { DataDestination, ModelRole, Rule } 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 +77,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 +143,8 @@ export interface ILLM extends LLMOptions {
|
|||
otherData: Record<string, string>,
|
||||
canPutWordsInModelsMouth?: boolean,
|
||||
): string | ChatMessage[];
|
||||
|
||||
getConfigurationStatus(): LLMConfigurationStatuses;
|
||||
}
|
||||
|
||||
export interface ModelInstaller {
|
||||
|
|
@ -482,12 +466,101 @@ 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;
|
||||
|
|
@ -495,8 +568,9 @@ export interface LLMOptions {
|
|||
template?: TemplateType;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
rules?: Rule[];
|
||||
apiKey?: string;
|
||||
|
||||
// continueProperties
|
||||
|
|
@ -709,6 +783,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[]>;
|
||||
|
|
@ -964,11 +1040,13 @@ export interface ModelDescription {
|
|||
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 {
|
||||
|
|
@ -1141,6 +1219,7 @@ export interface ApplyState {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
toolCallId?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
|
|
@ -1296,7 +1375,6 @@ export interface Config {
|
|||
// in the actual Continue source code
|
||||
export interface ContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ILLM[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
|
|
@ -1312,7 +1390,7 @@ export interface ContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: string[];
|
||||
rules?: Rule[];
|
||||
modelsByRole: Record<ModelRole, ILLM[]>;
|
||||
selectedModelByRole: Record<ModelRole, ILLM | null>;
|
||||
data?: DataDestination[];
|
||||
|
|
@ -1320,7 +1398,6 @@ export interface ContinueConfig {
|
|||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
|
|
@ -1335,7 +1412,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: string[];
|
||||
rules?: Rule[];
|
||||
usePlatform: boolean;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
modelsByRole: Record<ModelRole, ModelDescription[]>;
|
||||
|
|
|
|||
|
|
@ -1,53 +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 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,
|
||||
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";
|
||||
|
||||
|
|
@ -48,7 +49,7 @@
|
|||
// configHandler = new ConfigHandler(
|
||||
// ide,
|
||||
// ideSettingsPromise,
|
||||
// async () => {},
|
||||
// new LLMLogger(),
|
||||
// Promise.resolve(undefined),
|
||||
// );
|
||||
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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 = {
|
||||
|
|
@ -32,6 +32,11 @@ 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,
|
||||
|
|
|
|||
|
|
@ -1,14 +1,41 @@
|
|||
import { ChatHistoryItem, ChatMessage, MessagePart } from "../";
|
||||
import { normalizeToMessageParts } from "../util/messageContent";
|
||||
|
||||
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'.
|
||||
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'
|
||||
|
||||
When addressing code modification requests, present a concise code snippet that
|
||||
emphasizes only the necessary changes and uses abbreviated placeholders for
|
||||
unmodified sections. For instance:
|
||||
|
||||
\`\`\`typescript /path/to/file
|
||||
// ... rest of code here ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of code here ...
|
||||
|
||||
{{ another modification }}
|
||||
|
||||
// ... 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,
|
||||
): ChatMessage[] {
|
||||
const filteredHistory = history.filter(
|
||||
(item) => item.message.role !== "system",
|
||||
);
|
||||
|
|
@ -16,7 +43,7 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] {
|
|||
|
||||
msgs.push({
|
||||
role: "system",
|
||||
content: DEFAULT_SYSTEM_MESSAGE,
|
||||
content: baseChatSystemMessage ?? DEFAULT_SYSTEM_MESSAGE,
|
||||
});
|
||||
|
||||
for (let i = 0; i < filteredHistory.length; i++) {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// @ts-nocheck
|
||||
// Generated by continue
|
||||
import { ChatMessage, MessagePart } from "../index.js";
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
|
||||
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
UserChatMessage,
|
||||
} from "../index.js";
|
||||
|
||||
import { Rule } from "@continuedev/config-yaml";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
AsyncEncoder,
|
||||
|
|
@ -11,6 +17,8 @@ import {
|
|||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
import { isRuleActive } from "./rules/isRuleActive.js";
|
||||
import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
|
|
@ -251,16 +259,35 @@ function pruneChatHistory(
|
|||
}, 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 zippedMessagesAndTokens: [ChatMessage, number][] = [];
|
||||
|
||||
const longerThanOneThird = longestMessages.filter(
|
||||
(message: ChatMessage) =>
|
||||
countTokens(message.content, modelName) > contextLength / 3,
|
||||
// Zipped ChatMessage with its token counts
|
||||
chatHistory.forEach((message) => {
|
||||
const zippedItem: [ChatMessage, number] = [
|
||||
message,
|
||||
countTokens(message.content, modelName),
|
||||
];
|
||||
zippedMessagesAndTokens.push(zippedItem);
|
||||
});
|
||||
|
||||
const zippedLongerThanOneThird = zippedMessagesAndTokens.filter(
|
||||
([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3,
|
||||
);
|
||||
const distanceFromThird = longerThanOneThird.map(
|
||||
(message: ChatMessage) =>
|
||||
countTokens(message.content, modelName) - contextLength / 3,
|
||||
|
||||
zippedLongerThanOneThird.sort(
|
||||
(
|
||||
[_messageA, tokensA]: [ChatMessage, number],
|
||||
[_messageB, tokensB]: [ChatMessage, number],
|
||||
) => {
|
||||
return tokensB - tokensA;
|
||||
},
|
||||
);
|
||||
|
||||
const longerThanOneThird = zippedLongerThanOneThird.map(
|
||||
([message, _token]: [ChatMessage, number]) => message,
|
||||
);
|
||||
const distanceFromThird = zippedLongerThanOneThird.map(
|
||||
([_message, token]: [ChatMessage, number]) => token - contextLength / 3,
|
||||
);
|
||||
|
||||
for (let i = 0; i < longerThanOneThird.length; i++) {
|
||||
|
|
@ -280,7 +307,7 @@ function pruneChatHistory(
|
|||
// 1. Replace beyond last 5 messages with summary
|
||||
let i = 0;
|
||||
while (totalTokens > contextLength && i < chatHistory.length - 5) {
|
||||
const message = chatHistory[0];
|
||||
const message = chatHistory[i];
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
totalTokens += countTokens(summarize(message), modelName);
|
||||
message.content = summarize(message);
|
||||
|
|
@ -288,11 +315,7 @@ function pruneChatHistory(
|
|||
}
|
||||
|
||||
// 2. Remove entire messages until the last 5
|
||||
while (
|
||||
chatHistory.length > 5 &&
|
||||
totalTokens > contextLength &&
|
||||
chatHistory.length > 0
|
||||
) {
|
||||
while (chatHistory.length > 5 && totalTokens > contextLength) {
|
||||
const message = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
}
|
||||
|
|
@ -384,16 +407,127 @@ function chatMessageIsEmpty(message: ChatMessage): boolean {
|
|||
}
|
||||
}
|
||||
|
||||
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[] {
|
||||
function addSystemMessage({
|
||||
messages,
|
||||
systemMessage,
|
||||
originalMessages,
|
||||
}: {
|
||||
messages: ChatMessage[];
|
||||
systemMessage: string | undefined;
|
||||
originalMessages: ChatMessage[] | undefined;
|
||||
}): ChatMessage[] {
|
||||
if (
|
||||
!(systemMessage && systemMessage.trim() !== "") &&
|
||||
originalMessages?.[0]?.role !== "system"
|
||||
) {
|
||||
return messages;
|
||||
}
|
||||
|
||||
let content = "";
|
||||
if (originalMessages?.[0]?.role === "system") {
|
||||
content = renderChatMessage(originalMessages[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
|
||||
messages.splice(-1, 0, systemChatMsg);
|
||||
return messages;
|
||||
}
|
||||
|
||||
function getMessageStringContent(message?: UserChatMessage): string {
|
||||
if (!message) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message.content;
|
||||
}
|
||||
|
||||
// Handle MessagePart array
|
||||
return message.content
|
||||
.map((part) => {
|
||||
if (part.type === "text") {
|
||||
return part.text;
|
||||
}
|
||||
|
||||
return "";
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
const getSystemMessage = ({
|
||||
userMessage,
|
||||
rules,
|
||||
currentModel,
|
||||
}: {
|
||||
userMessage?: UserChatMessage;
|
||||
rules: Rule[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const messageStringContent = getMessageStringContent(userMessage);
|
||||
const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent);
|
||||
|
||||
return rules
|
||||
.filter((rule) => {
|
||||
return isRuleActive({
|
||||
rule,
|
||||
activePaths: filePathsFromMessage,
|
||||
currentModel,
|
||||
});
|
||||
})
|
||||
.map((rule) => {
|
||||
if (typeof rule === "string") {
|
||||
return rule;
|
||||
}
|
||||
return rule.rule;
|
||||
})
|
||||
.join("\n");
|
||||
};
|
||||
|
||||
function getLastUserMessage(
|
||||
messages: ChatMessage[],
|
||||
): UserChatMessage | undefined {
|
||||
// Iterate backwards through messages to find the last user message
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].role === "user") {
|
||||
return messages[i] as UserChatMessage;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function compileChatMessages({
|
||||
modelName,
|
||||
msgs,
|
||||
contextLength,
|
||||
maxTokens,
|
||||
supportsImages,
|
||||
prompt,
|
||||
functions,
|
||||
systemMessage,
|
||||
rules,
|
||||
}: {
|
||||
modelName: string;
|
||||
msgs: ChatMessage[] | undefined;
|
||||
contextLength: number;
|
||||
maxTokens: number;
|
||||
supportsImages: boolean;
|
||||
prompt: string | undefined;
|
||||
functions: any[] | undefined;
|
||||
systemMessage: string | undefined;
|
||||
rules: Rule[];
|
||||
}): ChatMessage[] {
|
||||
let msgsCopy = msgs
|
||||
? msgs
|
||||
.map((msg) => ({ ...msg }))
|
||||
|
|
@ -410,29 +544,19 @@ function compileChatMessages(
|
|||
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);
|
||||
}
|
||||
const lastUserMessage = getLastUserMessage(msgsCopy);
|
||||
|
||||
msgsCopy = addSystemMessage({
|
||||
messages: msgsCopy,
|
||||
systemMessage:
|
||||
systemMessage ??
|
||||
getSystemMessage({
|
||||
userMessage: lastUserMessage,
|
||||
rules,
|
||||
currentModel: modelName,
|
||||
}),
|
||||
originalMessages: msgs,
|
||||
});
|
||||
|
||||
let functionTokens = 0;
|
||||
if (functions) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ChatMessage, LLMOptions } from "..";
|
||||
|
||||
import { BaseLLM } from ".";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
class DummyLLM extends BaseLLM {
|
||||
static providerName = "openai";
|
||||
|
|
@ -30,7 +31,7 @@ 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",
|
||||
|
|
@ -43,7 +44,7 @@ describe("BaseLLM", () => {
|
|||
requestOptions: {},
|
||||
promptTemplates: {},
|
||||
templateMessages: templatMessagesFunction,
|
||||
writeLog: writeLogFunction,
|
||||
logger: llmLogger,
|
||||
llmRequestHook: () => {},
|
||||
apiKey: "testApiKey",
|
||||
aiGatewaySlug: "testSlug",
|
||||
|
|
@ -67,7 +68,7 @@ describe("BaseLLM", () => {
|
|||
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/");
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ModelRole } from "@continuedev/config-yaml";
|
||||
import { ModelRole, Rule } from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import { findLlmInfo } from "@continuedev/llm-info";
|
||||
import {
|
||||
|
|
@ -16,6 +16,8 @@ import {
|
|||
Chunk,
|
||||
CompletionOptions,
|
||||
ILLM,
|
||||
ILLMInteractionLog,
|
||||
ILLMLogger,
|
||||
LLMFullCompletionOptions,
|
||||
LLMOptions,
|
||||
ModelCapability,
|
||||
|
|
@ -44,6 +46,7 @@ import {
|
|||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
LLMConfigurationStatuses,
|
||||
} from "./constants.js";
|
||||
import {
|
||||
compileChatMessages,
|
||||
|
|
@ -72,6 +75,8 @@ export function isModelInstaller(provider: any): provider is ModelInstaller {
|
|||
return provider && typeof provider.installModel === "function";
|
||||
}
|
||||
|
||||
type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
|
||||
|
||||
export abstract class BaseLLM implements ILLM {
|
||||
static providerName: string;
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
|
||||
|
|
@ -122,6 +127,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
title?: string;
|
||||
systemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
contextLength: number;
|
||||
maxStopWords?: number | undefined;
|
||||
completionOptions: CompletionOptions;
|
||||
|
|
@ -129,7 +135,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;
|
||||
|
||||
|
|
@ -143,6 +149,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
cacheBehavior?: CacheBehavior;
|
||||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
rules?: Rule[];
|
||||
|
||||
deployment?: string;
|
||||
apiVersion?: string;
|
||||
|
|
@ -189,6 +196,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 +227,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;
|
||||
|
||||
|
|
@ -242,6 +250,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.accountId = options.accountId;
|
||||
this.capabilities = options.capabilities;
|
||||
this.roles = options.roles;
|
||||
this.rules = options.rules;
|
||||
|
||||
this.deployment = options.deployment;
|
||||
this.apiVersion = options.apiVersion;
|
||||
|
|
@ -259,6 +268,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,
|
||||
|
|
@ -286,21 +299,17 @@ export abstract class BaseLLM implements ILLM {
|
|||
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
|
||||
}
|
||||
|
||||
return compileChatMessages(
|
||||
options.model,
|
||||
messages,
|
||||
return compileChatMessages({
|
||||
modelName: options.model,
|
||||
msgs: messages,
|
||||
contextLength,
|
||||
options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
this.supportsImages(),
|
||||
undefined,
|
||||
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
prompt: undefined,
|
||||
functions,
|
||||
this.systemMessage,
|
||||
);
|
||||
}
|
||||
|
||||
private _getSystemMessage(): string | undefined {
|
||||
// TODO: Merge with config system message
|
||||
return this.systemMessage;
|
||||
systemMessage: this.systemMessage,
|
||||
rules: this.rules ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
private _templatePromptLikeMessages(prompt: string): string {
|
||||
|
|
@ -310,7 +319,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
|
||||
|
||||
const systemMessage = this._getSystemMessage();
|
||||
const systemMessage = this.systemMessage;
|
||||
if (systemMessage) {
|
||||
msgs.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
|
@ -347,13 +356,17 @@ export abstract class BaseLLM implements ILLM {
|
|||
);
|
||||
}
|
||||
|
||||
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 +395,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 +506,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 +581,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 +678,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 +695,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 +727,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 +741,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 +793,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 +810,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,6 +913,10 @@ 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);
|
||||
|
||||
|
|
@ -776,11 +926,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
? 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 +938,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
let citations: null | string[] = null;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -798,6 +947,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: chunk,
|
||||
});
|
||||
yield { role: "assistant", content: chunk };
|
||||
}
|
||||
} else {
|
||||
|
|
@ -827,15 +980,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 +996,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,
|
||||
|
|
|
|||
|
|
@ -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,8 +12,9 @@ import {
|
|||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { getSecureID } from "../utils/getSecureID.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
|
||||
|
|
@ -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",
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -228,22 +287,43 @@ class Bedrock extends BaseLLM {
|
|||
): any {
|
||||
const convertedMessages = this._convertMessages(messages);
|
||||
|
||||
const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
|
||||
const shouldCacheSystemMessage =
|
||||
!!this.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: this.systemMessage
|
||||
? shouldCacheSystemMessage
|
||||
? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }]
|
||||
: [{ 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,
|
||||
},
|
||||
},
|
||||
})),
|
||||
}
|
||||
}
|
||||
}))
|
||||
} : undefined,
|
||||
: undefined,
|
||||
inferenceConfig: {
|
||||
maxTokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
|
|
@ -261,20 +341,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 +374,12 @@ class Bedrock extends BaseLLM {
|
|||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: message.content || ""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
text: message.content || "",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -303,8 +392,8 @@ class Bedrock extends BaseLLM {
|
|||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
}
|
||||
}))
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -312,84 +401,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 +575,6 @@ class Bedrock extends BaseLLM {
|
|||
return modelConfig.extractEmbeddings(responseBody);
|
||||
}
|
||||
|
||||
|
||||
private _getModelConfig() {
|
||||
const modelConfigs: { [key: string]: ModelConfig } = {
|
||||
cohere: {
|
||||
|
|
@ -491,7 +612,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 +655,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",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
197
core/llm/llms/Docker.ts
Normal file
197
core/llm/llms/Docker.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
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",
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
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}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Docker;
|
||||
70
core/llm/llms/Inception.ts
Normal file
70
core/llm/llms/Inception.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
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://copenhagen.api.inceptionlabs.ai/v1/",
|
||||
model: "mercury-editor-small-experimental",
|
||||
completionOptions: {
|
||||
temperature: 0.0,
|
||||
maxTokens: 150,
|
||||
presencePenalty: 1.5,
|
||||
stop: ["\n\n", "\n \n", "<|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,
|
||||
max_tokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
top_p: options.topP,
|
||||
frequency_penalty: options.frequencyPenalty,
|
||||
presence_penalty: options.presencePenalty,
|
||||
stop: options.stop,
|
||||
stream: true,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
for await (const chunk of streamSse(resp)) {
|
||||
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,4 +1,5 @@
|
|||
import { LLMOptions } from "../..";
|
||||
import { LLMConfigurationStatuses } from "../constants";
|
||||
import { LlmApiRequestType } from "../openaiTypeConverters";
|
||||
|
||||
import OpenAI from "./OpenAI";
|
||||
|
|
@ -9,4 +10,12 @@ export class Relace extends OpenAI {
|
|||
apiBase: "https://instantapply.endpoint.relace.run/v1/",
|
||||
};
|
||||
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"];
|
||||
|
||||
getConfigurationStatus() {
|
||||
if (!this.apiKey) {
|
||||
return LLMConfigurationStatuses.MISSING_API_KEY;
|
||||
}
|
||||
|
||||
return LLMConfigurationStatuses.VALID;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
|
|
@ -52,6 +52,41 @@ class SiliconFlow extends OpenAI {
|
|||
yield chunk.choices[0].text;
|
||||
}
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || query.trim() === "") {
|
||||
console.warn("[SiliconFlow] rerank: query is empty");
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!chunks || chunks.length === 0) {
|
||||
console.warn("[SiliconFlow] rerank: chunks is empty");
|
||||
return [];
|
||||
}
|
||||
|
||||
const endpoint = new URL("rerank", this.apiBase);
|
||||
const resp = await this.fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: this.model,
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
const results = data.results.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
||||
export default SiliconFlow;
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ class WatsonX extends BaseLLM {
|
|||
if (this.apiBase?.includes("cloud.ibm.com")) {
|
||||
// watsonx SaaS
|
||||
const wxToken = await (
|
||||
await fetch(
|
||||
await this.fetch(
|
||||
`https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
|
||||
{
|
||||
method: "POST",
|
||||
|
|
@ -48,7 +48,7 @@ class WatsonX extends BaseLLM {
|
|||
// Using username/password auth
|
||||
const userPass = this.apiKey?.split(":");
|
||||
const wxToken = await (
|
||||
await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
|
||||
await this.fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
|
@ -61,7 +61,7 @@ class WatsonX extends BaseLLM {
|
|||
})
|
||||
).json();
|
||||
const wxTokenExpiry = await (
|
||||
await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
|
||||
await this.fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import {
|
|||
BaseCompletionOptions,
|
||||
IdeSettings,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
LLMOptions,
|
||||
ModelDescription,
|
||||
} from "../..";
|
||||
|
|
@ -18,6 +19,7 @@ import Cloudflare from "./Cloudflare";
|
|||
import Cohere from "./Cohere";
|
||||
import DeepInfra from "./DeepInfra";
|
||||
import Deepseek from "./Deepseek";
|
||||
import Docker from "./Docker";
|
||||
import Fireworks from "./Fireworks";
|
||||
import Flowise from "./Flowise";
|
||||
import FreeTrial from "./FreeTrial";
|
||||
|
|
@ -26,6 +28,7 @@ import Gemini from "./Gemini";
|
|||
import Groq from "./Groq";
|
||||
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
|
||||
import HuggingFaceTGI from "./HuggingFaceTGI";
|
||||
import Inception from "./Inception";
|
||||
import Kindo from "./Kindo";
|
||||
import LlamaCpp from "./LlamaCpp";
|
||||
import Llamafile from "./Llamafile";
|
||||
|
|
@ -87,6 +90,7 @@ export const LLMClasses = [
|
|||
ContinueProxy,
|
||||
Cloudflare,
|
||||
Deepseek,
|
||||
Docker,
|
||||
Msty,
|
||||
Azure,
|
||||
WatsonX,
|
||||
|
|
@ -104,6 +108,7 @@ export const LLMClasses = [
|
|||
SiliconFlow,
|
||||
Scaleway,
|
||||
Relace,
|
||||
Inception,
|
||||
];
|
||||
|
||||
export async function llmFromDescription(
|
||||
|
|
@ -111,7 +116,7 @@ export async function llmFromDescription(
|
|||
readFile: (filepath: string) => Promise<string>,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
llmLogger: ILLMLogger,
|
||||
completionOptions?: BaseCompletionOptions,
|
||||
systemMessage?: string,
|
||||
): Promise<BaseLLM | undefined> {
|
||||
|
|
@ -141,7 +146,7 @@ export async function llmFromDescription(
|
|||
cls.defaultOptions?.completionOptions?.maxTokens,
|
||||
},
|
||||
systemMessage,
|
||||
writeLog,
|
||||
logger: llmLogger,
|
||||
uniqueId,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,15 @@
|
|||
import { ContinueProperties } from "@continuedev/config-yaml";
|
||||
import {
|
||||
ContinueProperties,
|
||||
decodeSecretLocation,
|
||||
SecretType,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { Telemetry } from "../../../util/posthog.js";
|
||||
import OpenAI from "../OpenAI.js";
|
||||
|
||||
import type { Chunk, LLMOptions } from "../../../index.js";
|
||||
import { LLMConfigurationStatuses } from "../../constants.js";
|
||||
|
||||
class ContinueProxy extends OpenAI {
|
||||
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
|
||||
|
|
@ -49,6 +54,19 @@ class ContinueProxy extends OpenAI {
|
|||
};
|
||||
}
|
||||
|
||||
getConfigurationStatus() {
|
||||
if (!this.apiKeyLocation) {
|
||||
return LLMConfigurationStatuses.VALID;
|
||||
}
|
||||
|
||||
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
|
||||
if (secretLocation.secretType === SecretType.NotFound) {
|
||||
return LLMConfigurationStatuses.MISSING_API_KEY;
|
||||
}
|
||||
|
||||
return LLMConfigurationStatuses.VALID;
|
||||
}
|
||||
|
||||
protected _getHeaders() {
|
||||
const headers: any = super._getHeaders();
|
||||
headers["x-continue-unique-id"] = Telemetry.uniqueId;
|
||||
|
|
|
|||
315
core/llm/logFormatter.test.ts
Normal file
315
core/llm/logFormatter.test.ts
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
import { Buffer } from "buffer";
|
||||
import { Writable } from "stream";
|
||||
import { LLMLogFormatter } from "./logFormatter";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
class MemoryWritable extends Writable {
|
||||
data: Buffer[] = [];
|
||||
constructor() {
|
||||
super();
|
||||
this.data = [];
|
||||
}
|
||||
|
||||
_write(
|
||||
chunk: Buffer,
|
||||
encoding: BufferEncoding,
|
||||
callback: (error?: Error | null) => void,
|
||||
): void {
|
||||
this.data.push(chunk);
|
||||
callback();
|
||||
}
|
||||
|
||||
getText() {
|
||||
const decoder = new TextDecoder();
|
||||
return decoder.decode(Buffer.concat(this.data as any));
|
||||
}
|
||||
}
|
||||
|
||||
describe("LLMLogFormatter", () => {
|
||||
it("should format log items correctly", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output);
|
||||
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765432100,
|
||||
kind: "startChat",
|
||||
options: {
|
||||
model: "granite3.2-dense:8b",
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content: "You are a helpful assistant",
|
||||
},
|
||||
],
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello, ",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433200,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "world!",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433300,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "\nHow can I help you?",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765434100,
|
||||
kind: "success",
|
||||
promptTokens: 10,
|
||||
generatedTokens: 20,
|
||||
thinkingTokens: 0,
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:12.1 [Chat]",
|
||||
" Options: {",
|
||||
' "model": "granite3.2-dense:8b"',
|
||||
" }",
|
||||
" Role: system",
|
||||
" | You are a helpful assistant",
|
||||
" +1.0 Role: assistant",
|
||||
" | Hello, world!",
|
||||
" +1.2 | How can I help you?",
|
||||
" +2.0 Success",
|
||||
" Prompt Tokens: 10",
|
||||
" Generated Tokens: 20",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should format completion interactions correctly", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output);
|
||||
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765432100,
|
||||
kind: "startComplete",
|
||||
options: {
|
||||
model: "granite3.2-dense:8b",
|
||||
},
|
||||
prompt: "A horse is a horse",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "chunk",
|
||||
chunk: ", of course, of course",
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:12.1 [Complete]",
|
||||
" Options: {",
|
||||
' "model": "granite3.2-dense:8b"',
|
||||
" }",
|
||||
" Prompt:",
|
||||
" | A horse is a horse",
|
||||
" +1.0 Result:",
|
||||
" | , of course, of course",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should format FIM interactions correctly", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output);
|
||||
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765432100,
|
||||
kind: "startFim",
|
||||
options: {
|
||||
model: "granite3.2-dense:8b",
|
||||
},
|
||||
prefix: "A\nB",
|
||||
suffix: "D\nE",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "chunk",
|
||||
chunk: "C",
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:12.1 [Fim]",
|
||||
" Options: {",
|
||||
' "model": "granite3.2-dense:8b"',
|
||||
" }",
|
||||
" Prefix:",
|
||||
" | A",
|
||||
" | B",
|
||||
" Suffix:",
|
||||
" | D",
|
||||
" | E",
|
||||
" +1.0 Result:",
|
||||
" | C",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should interleave log items correctly", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output);
|
||||
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello, ",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "2",
|
||||
timestamp: 1698765433200,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello, ",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433300,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "World!",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "2",
|
||||
timestamp: 1698765433400,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "World!",
|
||||
},
|
||||
});
|
||||
// Check if we end interaction 2 and start another interaction,
|
||||
// it gets a different prefix marker.
|
||||
logger._logItem({
|
||||
interactionId: "2",
|
||||
timestamp: 1698765434000,
|
||||
kind: "success",
|
||||
promptTokens: 10,
|
||||
generatedTokens: 20,
|
||||
thinkingTokens: 0,
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "3",
|
||||
timestamp: 1698765434100,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello, World!",
|
||||
},
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:13.1 Role: assistant",
|
||||
" | Hello, ",
|
||||
"|15:17:13.2 Role: assistant",
|
||||
"| | Hello, ",
|
||||
" +0.2 | World!",
|
||||
"| +0.2 | World!",
|
||||
"| +0.8 Success",
|
||||
"| Prompt Tokens: 10",
|
||||
"| Generated Tokens: 20",
|
||||
"&15:17:14.1 Role: assistant",
|
||||
"& | Hello, World!",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should wrap long lines", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output, 40);
|
||||
|
||||
// Test a single message long enough to wrap; the input is
|
||||
// "<xx...xx>", not "xxxx" to make sure we are writing the correct
|
||||
// substrings.
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "<" + "x".repeat(58) + ">",
|
||||
},
|
||||
});
|
||||
// Test when a first message doesn't wrap, but another message
|
||||
// that continues the same line causes a wrap
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433200,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "\n<" + "y".repeat(29),
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433300,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "y".repeat(29) + ">",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433400,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "\n" + "Artichokes and Beans ".repeat(3),
|
||||
},
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:13.1 Role: assistant",
|
||||
" | <" + "x".repeat(39),
|
||||
" . " + "x".repeat(19) + ">",
|
||||
" +0.1 | <" + "y".repeat(39),
|
||||
" +0.2 . " + "y".repeat(19) + ">",
|
||||
" +0.3 | Artichokes and Beans Artichokes and",
|
||||
" . Beans Artichokes and Beans ",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
});
|
||||
426
core/llm/logFormatter.ts
Normal file
426
core/llm/logFormatter.ts
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
import { Writable } from "stream";
|
||||
import {
|
||||
AssistantChatMessage,
|
||||
ChatMessage,
|
||||
LLMInteractionCancel,
|
||||
LLMInteractionError,
|
||||
LLMInteractionItem,
|
||||
LLMInteractionStartChat,
|
||||
LLMInteractionStartComplete,
|
||||
LLMInteractionStartFim,
|
||||
LLMInteractionSuccess,
|
||||
ThinkingChatMessage,
|
||||
ToolCallDelta,
|
||||
UserChatMessage,
|
||||
} from "..";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
// Markers for different overlapping interactions.
|
||||
const LOG_PREFIXES = [" ", "|", "&", "%", "#"];
|
||||
// Wrap wide to avoid messing up code
|
||||
const DEFAULT_WRAP_WIDTH = 100;
|
||||
|
||||
interface InteractionData {
|
||||
prefix: string;
|
||||
startItem: LLMInteractionItem;
|
||||
lastItem: LLMInteractionItem | null;
|
||||
}
|
||||
|
||||
function formatTimestamp(timestamp: number) {
|
||||
const date = new Date(timestamp);
|
||||
|
||||
const hours = date.getUTCHours().toString().padStart(2, "0");
|
||||
const minutes = date.getUTCMinutes().toString().padStart(2, "0");
|
||||
const seconds = date.getUTCSeconds();
|
||||
const milliseconds = date.getUTCMilliseconds();
|
||||
|
||||
// Format seconds with one decimal place
|
||||
const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`;
|
||||
|
||||
return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A class that formats LLM log output as a human-readable stream.
|
||||
* The general appearance of the output is something like:
|
||||
*
|
||||
* 01:23:45.6 [Chat]
|
||||
* Options: {
|
||||
* "maxTokens": 1000,
|
||||
* }
|
||||
* Role: system
|
||||
* | You are a helpful assistant.
|
||||
* Role: user
|
||||
* | Who are you?
|
||||
* +0.2 Role: assistant
|
||||
* | How can I help you today?
|
||||
* +0.3 | I can tell you about the weather or the stock mark
|
||||
* +0.4 . et. [THIS LINE IS WRAPPED]
|
||||
* |01:23:46.1 [Complete]
|
||||
* | Options: {
|
||||
* | "maxTokens": 1000,
|
||||
* | }
|
||||
* | Prefix:
|
||||
* | | COMPLETE THIS
|
||||
* +0.6 Success
|
||||
* PromptTokens: 50
|
||||
* GeneratedTokens: 30
|
||||
* | +0.2 Result:
|
||||
* | | COMPLETION
|
||||
*
|
||||
* The lines with | are a second interaction that starts while the
|
||||
* first one is still in progress; every interaction starts with
|
||||
* an absolute timestamp, and relative timestamps are included for
|
||||
* separately received results in the same interaction.
|
||||
*/
|
||||
export class LLMLogFormatter {
|
||||
// Current active interactions
|
||||
private interactions: Record<string, InteractionData> = {};
|
||||
private lastItem: LLMInteractionItem | null = null;
|
||||
// Item that started the current line; we use this to determine
|
||||
// if the next line needs a timestamp.
|
||||
private lastLineStartItem: LLMInteractionItem | null = null;
|
||||
private openLine: boolean = false;
|
||||
private openLineChars: number = 0;
|
||||
private lastFreedPrefix: string | null = null;
|
||||
|
||||
/**
|
||||
* Creates a new LLMLogWriter.
|
||||
* @param logger - The LLMLogger instance to listen to for log items
|
||||
* @param output - Stream to write formatted output to
|
||||
* @param wrapWidth - Maximum width of a line before wrapping
|
||||
*/
|
||||
constructor(
|
||||
private logger: LLMLogger,
|
||||
private output: Writable,
|
||||
private wrapWidth: number = DEFAULT_WRAP_WIDTH,
|
||||
) {
|
||||
this.logger.onLogItem((item) => {
|
||||
this.logItem(item);
|
||||
});
|
||||
}
|
||||
|
||||
private getInteractionData(item: LLMInteractionItem) {
|
||||
let interaction = this.interactions[item.interactionId];
|
||||
if (interaction !== undefined) {
|
||||
return interaction;
|
||||
}
|
||||
|
||||
let usedPrefixes = Object.values(this.interactions).map(
|
||||
(interaction) => interaction.prefix,
|
||||
);
|
||||
|
||||
// Select a prefix that is not currently in use, and is
|
||||
// also not the last retired prefix - but with the
|
||||
// exception that we can reuse the empty prefix " "
|
||||
// immediately - this isn't confusing.
|
||||
let i = 0;
|
||||
let prefix;
|
||||
while (true) {
|
||||
const candidate = i < LOG_PREFIXES.length ? LOG_PREFIXES[i] : `X`;
|
||||
if (
|
||||
!usedPrefixes.includes(candidate) &&
|
||||
(candidate === " " || candidate !== this.lastFreedPrefix)
|
||||
) {
|
||||
prefix = candidate;
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
this.interactions[item.interactionId] = {
|
||||
prefix,
|
||||
startItem: item,
|
||||
lastItem: null,
|
||||
};
|
||||
|
||||
return this.interactions[item.interactionId];
|
||||
}
|
||||
|
||||
private formatTimestamp(
|
||||
interaction: InteractionData,
|
||||
item: LLMInteractionItem,
|
||||
) {
|
||||
if (item !== this.lastLineStartItem) {
|
||||
if (item === interaction.startItem) {
|
||||
return formatTimestamp(item.timestamp);
|
||||
} else {
|
||||
const delta = (item.timestamp - interaction.startItem.timestamp) / 1000;
|
||||
return ("+" + delta.toFixed(1)).padStart(10, " ");
|
||||
}
|
||||
} else {
|
||||
return " ";
|
||||
}
|
||||
}
|
||||
|
||||
// the implementation behind logLines and logMessageText
|
||||
private logFragment(
|
||||
item: LLMInteractionItem,
|
||||
fragment: string,
|
||||
startAt: number,
|
||||
marker: string = "",
|
||||
joinBefore: boolean = false,
|
||||
joinAfter: boolean = false,
|
||||
wrap: boolean = false,
|
||||
) {
|
||||
const interaction = this.getInteractionData(item);
|
||||
|
||||
if (
|
||||
this.openLine &&
|
||||
(!joinBefore || item.interactionId !== this.lastItem?.interactionId)
|
||||
) {
|
||||
this.openLine = false;
|
||||
this.openLineChars = 0;
|
||||
this.output.write("\n");
|
||||
}
|
||||
|
||||
let continueAt = null;
|
||||
if (
|
||||
wrap &&
|
||||
fragment.length - startAt > this.wrapWidth - this.openLineChars
|
||||
) {
|
||||
continueAt = startAt + this.wrapWidth - this.openLineChars;
|
||||
|
||||
// Look for a better line-breaking point at whitespace
|
||||
const searchBackwardLimit = Math.max(startAt, continueAt - 20); // Don't look back too far
|
||||
for (let i = continueAt; i > searchBackwardLimit; i--) {
|
||||
if (/\s/.test(fragment.charAt(i))) {
|
||||
continueAt = i + 1; // Break after the whitespace
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// When there's whitespace immediately after the wrap width,
|
||||
// the above will result in breaking *after* that, so we exceed
|
||||
// the wrap width. The trimEnd() avoids that.
|
||||
fragment = fragment.substring(startAt, continueAt).trimEnd();
|
||||
joinAfter = false;
|
||||
} else if (startAt > 0) {
|
||||
fragment = fragment.substring(startAt);
|
||||
}
|
||||
|
||||
if (!this.openLine || !this.openLine) {
|
||||
let timestamp = this.formatTimestamp(interaction, item);
|
||||
this.output.write(`${interaction.prefix}${timestamp} ${marker}`);
|
||||
this.lastLineStartItem = item;
|
||||
}
|
||||
|
||||
this.output.write(fragment);
|
||||
this.openLine = joinAfter;
|
||||
this.lastItem = item;
|
||||
if (!this.openLine) {
|
||||
this.output.write("\n");
|
||||
this.openLineChars = 0;
|
||||
} else {
|
||||
this.openLineChars += fragment.length;
|
||||
}
|
||||
|
||||
return continueAt;
|
||||
}
|
||||
|
||||
// Use for everything but text content; a newline is
|
||||
// implicitly added at the end of content
|
||||
private logLines(
|
||||
item: LLMInteractionItem,
|
||||
content: string,
|
||||
marker: string = "",
|
||||
) {
|
||||
for (const line of content.split("\n")) {
|
||||
this.logFragment(item, line, 0, marker);
|
||||
}
|
||||
}
|
||||
|
||||
// This logs text context - as compared to logLines:
|
||||
// - No newline is appended to the end of content
|
||||
// - consecutive calls to logMessageText for the same interaction
|
||||
// will join onto a single line
|
||||
// - It will wrap text at the wrap width
|
||||
private logMessageText(item: LLMInteractionItem, content: string) {
|
||||
const lines = content.split("\n");
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
let startAt: number | null = 0;
|
||||
let marker = "| ";
|
||||
while (startAt !== null) {
|
||||
// When wrapping, the next start position is turned;
|
||||
// null means we've written everything
|
||||
startAt = this.logFragment(
|
||||
item,
|
||||
lines[i],
|
||||
startAt,
|
||||
marker,
|
||||
true,
|
||||
i === lines.length - 1,
|
||||
true,
|
||||
);
|
||||
marker = ". ";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private logToolcalls(item: LLMInteractionItem, toolsCalls: ToolCallDelta[]) {
|
||||
for (const toolCall of toolsCalls) {
|
||||
this.logLines(
|
||||
item,
|
||||
`Tool call: ${JSON.stringify(toolCall, undefined, 2)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private logMessageContent(
|
||||
item: LLMInteractionItem,
|
||||
message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage,
|
||||
) {
|
||||
if (typeof message.content === "string") {
|
||||
this.logMessageText(item, message.content);
|
||||
} else {
|
||||
for (const part of message.content) {
|
||||
if (part.type === "text") {
|
||||
this.logMessageText(item, part.text);
|
||||
} else {
|
||||
this.logLines(item, `Image: ${part.imageUrl.url}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private logMessage(
|
||||
item: LLMInteractionItem,
|
||||
message: ChatMessage,
|
||||
forceRole: boolean = false,
|
||||
) {
|
||||
let showRole = true;
|
||||
if (
|
||||
!forceRole &&
|
||||
(message.role === "assistant" || message.role === "thinking")
|
||||
) {
|
||||
const interaction = this.getInteractionData(item);
|
||||
const lastMessage =
|
||||
interaction.lastItem?.kind === "message"
|
||||
? interaction.lastItem.message
|
||||
: null;
|
||||
if (message.role === lastMessage?.role) {
|
||||
showRole = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (showRole) {
|
||||
this.logLines(item, "Role: " + message.role);
|
||||
}
|
||||
|
||||
switch (message.role) {
|
||||
case "assistant":
|
||||
if (message.toolCalls) {
|
||||
this.logToolcalls(item, message.toolCalls);
|
||||
}
|
||||
this.logMessageContent(item, message);
|
||||
break;
|
||||
case "thinking":
|
||||
if (message.toolCalls) {
|
||||
this.logToolcalls(item, message.toolCalls);
|
||||
}
|
||||
this.logMessageContent(item, message);
|
||||
if (message.redactedThinking) {
|
||||
this.logLines(item, `Redacted Thinking: ${message.redactedThinking}`);
|
||||
}
|
||||
if (message.signature) {
|
||||
this.logLines(item, `Signature: ${message.signature}`);
|
||||
}
|
||||
break;
|
||||
case "user":
|
||||
this.logMessageContent(item, message);
|
||||
break;
|
||||
case "system":
|
||||
this.logMessageText(item, message.content);
|
||||
break;
|
||||
case "tool":
|
||||
this.logLines(item, `Tool Call ID: ${message.toolCallId}`);
|
||||
this.logMessageText(item, message.content);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private logTokens(
|
||||
item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel,
|
||||
) {
|
||||
this.logLines(item, `Prompt Tokens: ${item.promptTokens}`);
|
||||
this.logLines(item, `Generated Tokens: ${item.generatedTokens}`);
|
||||
if (item.thinkingTokens > 0) {
|
||||
this.logLines(item, `Thinking Tokens: ${item.thinkingTokens}`);
|
||||
}
|
||||
}
|
||||
|
||||
private logOptions(
|
||||
item:
|
||||
| LLMInteractionStartChat
|
||||
| LLMInteractionStartComplete
|
||||
| LLMInteractionStartFim,
|
||||
) {
|
||||
this.logLines(
|
||||
item,
|
||||
"Options: " + JSON.stringify(item.options, undefined, 2),
|
||||
);
|
||||
}
|
||||
|
||||
private logItem(item: LLMInteractionItem) {
|
||||
const interaction = this.getInteractionData(item);
|
||||
|
||||
switch (item.kind) {
|
||||
case "startChat":
|
||||
this.logLines(item, "[Chat]");
|
||||
this.logOptions(item);
|
||||
let lastMessage = null;
|
||||
for (let message of item.messages) {
|
||||
this.logMessage(item, message, true);
|
||||
}
|
||||
break;
|
||||
case "startComplete":
|
||||
this.logLines(item, "[Complete]");
|
||||
this.logOptions(item);
|
||||
this.logLines(item, "Prompt:");
|
||||
this.logLines(item, item.prompt, "| ");
|
||||
break;
|
||||
case "startFim":
|
||||
this.logLines(item, "[Fim]");
|
||||
this.logOptions(item);
|
||||
this.logLines(item, "Prefix:");
|
||||
this.logLines(item, item.prefix, "| ");
|
||||
this.logLines(item, "Suffix:");
|
||||
this.logLines(item, item.suffix, "| ");
|
||||
break;
|
||||
case "chunk":
|
||||
if (interaction.lastItem?.kind !== "chunk") {
|
||||
this.logLines(item, "Result:");
|
||||
}
|
||||
this.logMessageText(item, item.chunk);
|
||||
break;
|
||||
case "message":
|
||||
this.logMessage(item, item.message);
|
||||
break;
|
||||
case "cancel":
|
||||
this.logLines(item, "Cancelled");
|
||||
this.logTokens(item);
|
||||
break;
|
||||
case "error":
|
||||
this.logLines(item, "Error");
|
||||
this.logTokens(item);
|
||||
break;
|
||||
case "success":
|
||||
this.logLines(item, "Success");
|
||||
this.logTokens(item);
|
||||
break;
|
||||
}
|
||||
|
||||
if (
|
||||
item.kind === "cancel" ||
|
||||
item.kind === "error" ||
|
||||
item.kind === "success"
|
||||
) {
|
||||
if (interaction.prefix !== " ") {
|
||||
this.lastFreedPrefix = interaction.prefix;
|
||||
}
|
||||
delete this.interactions[item.interactionId];
|
||||
} else {
|
||||
interaction.lastItem = item;
|
||||
}
|
||||
}
|
||||
}
|
||||
43
core/llm/logger.ts
Normal file
43
core/llm/logger.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import {
|
||||
ILLMLogger,
|
||||
ILLMInteractionLog,
|
||||
LLMInteractionItem,
|
||||
LLMInteractionItemDetails,
|
||||
} from "..";
|
||||
|
||||
type LLMLogItemFunction = (item: LLMInteractionItem) => void;
|
||||
|
||||
export class LLMLogger implements ILLMLogger {
|
||||
private nextId = 0;
|
||||
|
||||
public createInteractionLog(): LLMInteractionLog {
|
||||
return new LLMInteractionLog(this, (this.nextId++).toString());
|
||||
}
|
||||
|
||||
private logItemListeners: LLMLogItemFunction[] = [];
|
||||
|
||||
onLogItem(listener: LLMLogItemFunction) {
|
||||
this.logItemListeners.push(listener);
|
||||
}
|
||||
|
||||
public _logItem(item: LLMInteractionItem) {
|
||||
for (const listener of this.logItemListeners) {
|
||||
listener(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class LLMInteractionLog implements ILLMInteractionLog {
|
||||
constructor(
|
||||
private logger: LLMLogger,
|
||||
public interactionId: string,
|
||||
) {}
|
||||
|
||||
logItem(item: LLMInteractionItemDetails) {
|
||||
this.logger._logItem({
|
||||
...item,
|
||||
interactionId: this.interactionId,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
59
core/llm/rules/isRuleActive.test.ts
Normal file
59
core/llm/rules/isRuleActive.test.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { isRuleActive } from "./isRuleActive";
|
||||
|
||||
describe("isRuleActive", () => {
|
||||
const rule = {
|
||||
name: "My Rule",
|
||||
rule: "Do no harm",
|
||||
if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}',
|
||||
};
|
||||
|
||||
it("should return false when activePaths is empty", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: [],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when no matching paths exist", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["test.py", "main.js"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return true when both conditions are met", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.tsx", "main.js"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when only glob matches but model doesn't", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.tsx"],
|
||||
currentModel: "gpt-4",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when model matches but glob doesn't", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.ts"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
68
core/llm/rules/isRuleActive.ts
Normal file
68
core/llm/rules/isRuleActive.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { Rule } from "@continuedev/config-yaml";
|
||||
import { compileExpression } from "filtrex";
|
||||
import { minimatch } from "minimatch";
|
||||
|
||||
const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/;
|
||||
|
||||
const createGlobFunction = (activePaths: string[]) => {
|
||||
return (pattern: string) => {
|
||||
const result = activePaths.some((path) => minimatch(path, pattern));
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
const contains = (str: string, searchStr: string): boolean => {
|
||||
return str.includes(searchStr);
|
||||
};
|
||||
|
||||
const evaluateIf = ({
|
||||
condition,
|
||||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
condition: string;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim();
|
||||
if (!expression) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const evaluate = compileExpression(expression, {
|
||||
extraFunctions: {
|
||||
glob: createGlobFunction(activePaths),
|
||||
contains,
|
||||
},
|
||||
constants: {
|
||||
"current.model.model": currentModel,
|
||||
},
|
||||
});
|
||||
|
||||
return evaluate({});
|
||||
} catch (error) {
|
||||
console.error("Error evaluating rule condition:", error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const isRuleActive = ({
|
||||
rule,
|
||||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
rule: Rule;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}): boolean => {
|
||||
if (typeof rule === "string") {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (rule.if) {
|
||||
return evaluateIf({ condition: rule.if, activePaths, currentModel });
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
|
@ -23,19 +23,22 @@ export async function* llmStreamChat(
|
|||
void TTS.kill();
|
||||
}
|
||||
|
||||
const { title, legacySlashCommandData, completionOptions, messages } =
|
||||
msg.data;
|
||||
const { legacySlashCommandData, completionOptions, messages } = msg.data;
|
||||
|
||||
const model = await configHandler.llmFromTitle(title);
|
||||
const model = config.selectedModelByRole.chat;
|
||||
|
||||
if (!model) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
// Log to return in case of error
|
||||
const errorPromptLog = {
|
||||
modelTitle: model.title ?? model.model,
|
||||
modelTitle: model?.title ?? model?.model,
|
||||
completion: "",
|
||||
prompt: "",
|
||||
completionOptions: {
|
||||
...msg.data.completionOptions,
|
||||
model: model.model,
|
||||
model: model?.model,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
} else {
|
||||
modelName = model;
|
||||
}
|
||||
|
||||
|
||||
if (
|
||||
["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
|
||||
(part) => modelName.toLowerCase().includes(part),
|
||||
|
|
@ -92,6 +92,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
}
|
||||
if (
|
||||
[
|
||||
"cogito",
|
||||
"llama3.3",
|
||||
"qwq",
|
||||
"llama3.2",
|
||||
|
|
|
|||
49
core/llm/utils/__tests__/getSecureID.test.ts
Normal file
49
core/llm/utils/__tests__/getSecureID.test.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { getSecureID } from '../getSecureID';
|
||||
|
||||
// Mock the crypto.randomUUID function
|
||||
const mockRandomUUID = jest.fn();
|
||||
global.crypto = {
|
||||
...global.crypto,
|
||||
randomUUID: mockRandomUUID
|
||||
};
|
||||
|
||||
describe('getSecureID', () => {
|
||||
beforeEach(() => {
|
||||
// Reset the static property before each test
|
||||
(getSecureID as any).uuid = undefined;
|
||||
|
||||
// Reset the mock implementation
|
||||
mockRandomUUID.mockReset();
|
||||
// Setup a mock implementation that returns a fixed value for testing
|
||||
mockRandomUUID.mockReturnValue('test-uuid-1234');
|
||||
});
|
||||
|
||||
test('should generate a UUID on first call', () => {
|
||||
const result = getSecureID();
|
||||
expect(mockRandomUUID).toHaveBeenCalledTimes(1);
|
||||
expect(result).toBe('<!-- SID: test-uuid-1234 -->');
|
||||
});
|
||||
|
||||
test('should reuse the same UUID on subsequent calls', () => {
|
||||
const firstResult = getSecureID();
|
||||
const secondResult = getSecureID();
|
||||
|
||||
// The UUID generation should only happen once
|
||||
expect(mockRandomUUID).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Both results should be identical
|
||||
expect(firstResult).toBe(secondResult);
|
||||
expect(firstResult).toBe('<!-- SID: test-uuid-1234 -->');
|
||||
});
|
||||
|
||||
test('should maintain the same UUID across different test cases if not reset', () => {
|
||||
// Don't reset the UUID here to test persistence
|
||||
(getSecureID as any).uuid = 'persistent-uuid';
|
||||
|
||||
const result = getSecureID();
|
||||
|
||||
// No new UUID should be generated
|
||||
expect(mockRandomUUID).not.toHaveBeenCalled();
|
||||
expect(result).toBe('<!-- SID: persistent-uuid -->');
|
||||
});
|
||||
});
|
||||
22
core/llm/utils/extractPathsFromCodeBlocks.ts
Normal file
22
core/llm/utils/extractPathsFromCodeBlocks.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
/**
|
||||
* Extracts file paths from markdown code blocks
|
||||
*/
|
||||
export function extractPathsFromCodeBlocks(content: string): string[] {
|
||||
// Match:
|
||||
// 1. Starting ```
|
||||
// 2. Optional language identifier
|
||||
// 3. Required whitespace
|
||||
// 4. File path (captured) that must contain a dot and extension
|
||||
const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g;
|
||||
const paths: string[] = [];
|
||||
let match;
|
||||
|
||||
while ((match = codeBlockRegex.exec(content)) !== null) {
|
||||
const path = match[1];
|
||||
if (path && !path.startsWith("```")) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
8
core/llm/utils/getSecureID.ts
Normal file
8
core/llm/utils/getSecureID.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
// Utility function to get or generate UUID for LLM prompts
|
||||
export function getSecureID(): string {
|
||||
// Adding a type declaration for the static property
|
||||
if (!(getSecureID as any).uuid) {
|
||||
(getSecureID as any).uuid = crypto.randomUUID();
|
||||
}
|
||||
return `<!-- SID: ${(getSecureID as any).uuid} -->`;
|
||||
}
|
||||
1139
core/package-lock.json
generated
1139
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -43,11 +43,11 @@
|
|||
"typescript": "^5.6.3"
|
||||
},
|
||||
"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",
|
||||
|
|
@ -66,6 +66,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",
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { ContinueSDK, SlashCommand } from "../..";
|
|||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
|
||||
import { renderPromptFileV2 } from "../v2/renderPromptFile";
|
||||
|
||||
import { getContextProviderHelpers } from "./getContextProviderHelpers";
|
||||
import { renderTemplatedString } from "./renderTemplatedString";
|
||||
|
|
@ -67,7 +68,17 @@ export function slashCommandFromPromptFileV1(
|
|||
context.llm.systemMessage = systemMessage;
|
||||
|
||||
const userInput = extractUserInput(context.input, name);
|
||||
const renderedPrompt = await renderPromptV1(prompt, context, userInput);
|
||||
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
|
||||
config: context.config,
|
||||
fullInput: userInput,
|
||||
embeddingsProvider: context.config.modelsByRole.embed[0],
|
||||
reranker: context.config.modelsByRole.rerank[0],
|
||||
llm: context.llm,
|
||||
ide: context.ide,
|
||||
selectedCode: context.selectedCode,
|
||||
fetch: context.fetch,
|
||||
});
|
||||
|
||||
const messages = replaceSlashCommandWithPromptInChatHistory(
|
||||
context.history,
|
||||
name,
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ export async function renderPromptFileV2(
|
|||
rawContent: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<[ContextItem[], string]> {
|
||||
const [preamble, body] = getPreambleAndBody(rawContent);
|
||||
const [_, body] = getPreambleAndBody(rawContent);
|
||||
|
||||
const contextItemsPromises: Promise<ContextItem[]>[] = [];
|
||||
const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
|
||||
|
|
@ -75,6 +75,10 @@ export async function renderPromptFileV2(
|
|||
});
|
||||
|
||||
const contextItems = (await Promise.all(contextItemsPromises)).flat();
|
||||
const renderedPrompt =
|
||||
contextItems.map((item) => item.content).join("\n\n") +
|
||||
"\n\n" +
|
||||
renderedBody;
|
||||
|
||||
return [contextItems, renderedBody];
|
||||
return [contextItems, renderedPrompt];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,8 +5,6 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
|
||||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
import { OrganizationDescription } from "../config/ProfileLifecycleManager";
|
||||
import { SharedConfigSchema } from "../config/sharedConfig";
|
||||
import { GlobalContextModelSelections } from "../util/GlobalContext";
|
||||
|
||||
|
|
@ -32,6 +30,7 @@ import type {
|
|||
SlashCommandDescription,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
|
||||
|
||||
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
|
||||
|
||||
|
|
@ -66,14 +65,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
{
|
||||
result: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
profileId: string | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedOrgId: string;
|
||||
usingContinueForTeams: boolean;
|
||||
},
|
||||
];
|
||||
"config/deleteModel": [{ title: string }, void];
|
||||
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
|
||||
"config/listProfiles": [
|
||||
undefined,
|
||||
{ profiles: ProfileDescription[] | null; selectedProfileId: string | null },
|
||||
];
|
||||
"config/refreshProfiles": [undefined, void];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
|
||||
|
|
@ -198,5 +196,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
|
||||
"controlPlane/listOrganizations": [undefined, OrganizationDescription[]];
|
||||
isItemTooBig: [
|
||||
{ item: ContextItemWithId; selectedModelTitle: string | undefined },
|
||||
boolean,
|
||||
];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,19 +1,8 @@
|
|||
import { ProfileDescription } from "../config/ConfigHandler.js";
|
||||
|
||||
import { ToCoreFromIdeOrWebviewProtocol } from "./core.js";
|
||||
import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
|
||||
|
||||
export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & {
|
||||
didChangeSelectedProfile: [{ id: string | null }, void];
|
||||
didChangeSelectedOrg: [
|
||||
{ id: string | null; profileId?: string | null },
|
||||
void,
|
||||
];
|
||||
};
|
||||
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
didChangeAvailableProfiles: [
|
||||
{ profiles: ProfileDescription[]; selectedProfileId: string | null },
|
||||
void,
|
||||
];
|
||||
didSelectOrganization: [{ orgId: string | null }, void];
|
||||
didChangeSelectedProfile: [{ id: string }, void];
|
||||
didChangeSelectedOrg: [{ id: string; profileId?: string }, void];
|
||||
};
|
||||
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol;
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
openUrl: [string, void];
|
||||
runCommand: [{ command: string; options?: TerminalOptions }, void];
|
||||
getSearchResults: [{ query: string }, string];
|
||||
getFileResults: [{ pattern: string }, string[]];
|
||||
subprocess: [{ command: string; cwd?: string }, [string, string]];
|
||||
saveFile: [{ filepath: string }, void];
|
||||
fileExists: [{ filepath: string }, boolean];
|
||||
|
|
@ -106,5 +107,4 @@ export type ToWebviewOrCoreFromIdeProtocol = {
|
|||
{ sessionInfo: ControlPlaneSessionInfo | undefined },
|
||||
void,
|
||||
];
|
||||
didChangeIdeSettings: [{ settings: IdeSettings }, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
|
|||
import type {
|
||||
ApplyState,
|
||||
CodeToEdit,
|
||||
ContextSubmenuItem,
|
||||
EditStatus,
|
||||
MessageContent,
|
||||
RangeInFileWithContents,
|
||||
|
|
@ -12,14 +11,12 @@ import type {
|
|||
|
||||
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
||||
openUrl: [string, void];
|
||||
// We pass the `curSelectedModel` because we currently cannot access the
|
||||
// default model title in the GUI from JB
|
||||
applyToFile: [
|
||||
{
|
||||
text: string;
|
||||
streamId: string;
|
||||
curSelectedModelTitle: string;
|
||||
filepath?: string;
|
||||
toolCallId?: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
@ -52,7 +49,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
{
|
||||
prompt: MessageContent;
|
||||
range: RangeInFileWithContents;
|
||||
selectedModelTitle: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -187,6 +187,10 @@ export class MessageIde implements IDE {
|
|||
return this.request("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getFileResults(pattern: string): Promise<string[]> {
|
||||
return this.request("getFileResults", { pattern });
|
||||
}
|
||||
|
||||
getProblems(fileUri: string): Promise<Problem[]> {
|
||||
return this.request("getProblems", { filepath: fileUri });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -166,6 +166,10 @@ export class ReverseMessageIde {
|
|||
return this.ide.getSearchResults(data.query);
|
||||
});
|
||||
|
||||
this.on("getFileResults", (data) => {
|
||||
return this.ide.getFileResults(data.pattern);
|
||||
});
|
||||
|
||||
this.on("getProblems", (data) => {
|
||||
return this.ide.getProblems(data.filepath);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"config/ideSettingsUpdate",
|
||||
"config/getSerializedProfileInfo",
|
||||
"config/deleteModel",
|
||||
"config/listProfiles",
|
||||
"config/refreshProfiles",
|
||||
"config/openProfile",
|
||||
"config/updateSharedConfig",
|
||||
|
|
@ -60,7 +59,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"controlPlane/openUrl",
|
||||
"controlPlane/listOrganizations",
|
||||
"isItemTooBig",
|
||||
];
|
||||
|
||||
// Message types to pass through from core to webview
|
||||
|
|
@ -69,16 +68,13 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
||||
[
|
||||
"configUpdate",
|
||||
"getDefaultModelTitle",
|
||||
"indexProgress", // Codebase
|
||||
"indexing/statusUpdate", // Docs, etc.
|
||||
"addContextItem",
|
||||
"refreshSubmenuItems",
|
||||
"isContinueInputFocused",
|
||||
"didChangeAvailableProfiles",
|
||||
"setTTSActive",
|
||||
"getWebviewHistoryLength",
|
||||
"getCurrentSessionId",
|
||||
"didCloseFiles",
|
||||
"didSelectOrganization",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContextItemWithId,
|
||||
ContextProviderName,
|
||||
IndexingProgressUpdate,
|
||||
IndexingStatus,
|
||||
PackageDocsResult,
|
||||
} from "../index.js";
|
||||
|
||||
export type ToWebviewFromIdeOrCoreProtocol = {
|
||||
|
|
@ -13,6 +13,9 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
{
|
||||
result: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
profileId: string | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedOrgId: string | null;
|
||||
usingContinueForTeams: boolean;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler";
|
||||
import { ControlPlaneClient } from "../control-plane/client";
|
||||
import Mock from "../llm/llms/Mock";
|
||||
import { LLMLogger } from "../llm/logger";
|
||||
import FileSystemIde from "../util/filesystem";
|
||||
|
||||
import { TEST_DIR } from "./testDir";
|
||||
|
|
@ -17,7 +18,7 @@ export const testControlPlaneClient = new ControlPlaneClient(
|
|||
export const testConfigHandler = new ConfigHandler(
|
||||
testIde,
|
||||
ideSettingsPromise,
|
||||
async (text) => {},
|
||||
new LLMLogger(),
|
||||
Promise.resolve(undefined),
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,18 @@
|
|||
export enum BuiltInToolNames {
|
||||
ReadFile = "builtin_read_file",
|
||||
EditExistingFile = "builtin_edit_existing_file",
|
||||
ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
|
||||
CreateNewFile = "builtin_create_new_file",
|
||||
RunTerminalCommand = "builtin_run_terminal_command",
|
||||
ViewSubdirectory = "builtin_view_subdirectory",
|
||||
ViewRepoMap = "builtin_view_repo_map",
|
||||
ExactSearch = "builtin_exact_search",
|
||||
GrepSearch = "builtin_grep_search",
|
||||
FileGlobSearch = "builtin_file_glob_search",
|
||||
SearchWeb = "builtin_search_web",
|
||||
ViewDiff = "builtin_view_diff",
|
||||
LSTool = "builtin_ls",
|
||||
|
||||
// excluded from allTools for now
|
||||
ViewRepoMap = "builtin_view_repo_map",
|
||||
ViewSubdirectory = "builtin_view_subdirectory",
|
||||
}
|
||||
|
||||
export const BUILT_IN_GROUP_NAME = "Built-In";
|
||||
|
|
|
|||
|
|
@ -4,14 +4,14 @@ import { canParseUrl } from "../util/url";
|
|||
import { BuiltInToolNames } from "./builtIn";
|
||||
|
||||
import { createNewFileImpl } from "./implementations/createNewFile";
|
||||
import { exactSearchImpl } from "./implementations/exactSearch";
|
||||
import { fileGlobSearchImpl } from "./implementations/globSearch";
|
||||
import { grepSearchImpl } from "./implementations/grepSearch";
|
||||
import { lsToolImpl } from "./implementations/lsTool";
|
||||
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
|
||||
import { readFileImpl } from "./implementations/readFile";
|
||||
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
|
||||
import { searchWebImpl } from "./implementations/searchWeb";
|
||||
import { viewDiffImpl } from "./implementations/viewDiff";
|
||||
import { viewRepoMapImpl } from "./implementations/viewRepoMap";
|
||||
import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory";
|
||||
|
||||
async function callHttpTool(
|
||||
url: string,
|
||||
|
|
@ -139,22 +139,27 @@ export async function callTool(
|
|||
switch (uri) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
// Note: Custom GUI handling for edit
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.ExactSearch:
|
||||
return await exactSearchImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
return await grepSearchImpl(args, extras);
|
||||
case BuiltInToolNames.FileGlobSearch:
|
||||
return await fileGlobSearchImpl(args, extras);
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
return await runTerminalCommandImpl(args, extras);
|
||||
case BuiltInToolNames.SearchWeb:
|
||||
return await searchWebImpl(args, extras);
|
||||
case BuiltInToolNames.ViewDiff:
|
||||
return await viewDiffImpl(args, extras);
|
||||
case BuiltInToolNames.ViewRepoMap:
|
||||
return await viewRepoMapImpl(args, extras);
|
||||
case BuiltInToolNames.ViewSubdirectory:
|
||||
return await viewSubdirectoryImpl(args, extras);
|
||||
case BuiltInToolNames.LSTool:
|
||||
return await lsToolImpl(args, extras);
|
||||
case BuiltInToolNames.ReadCurrentlyOpenFile:
|
||||
return await readCurrentlyOpenFileImpl(args, extras);
|
||||
// case BuiltInToolNames.ViewRepoMap:
|
||||
// return await viewRepoMapImpl(args, extras);
|
||||
// case BuiltInToolNames.ViewSubdirectory:
|
||||
// return await viewSubdirectoryImpl(args, extras);
|
||||
default:
|
||||
return await callToolFromUri(uri, args, extras);
|
||||
}
|
||||
|
|
|
|||
37
core/tools/definitions/editFile.ts
Normal file
37
core/tools/definitions/editFile.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface EditToolArgs {
|
||||
filepath: string;
|
||||
new_contents: string;
|
||||
}
|
||||
|
||||
export const editFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.EditExistingFile,
|
||||
description:
|
||||
"Use this tool to edit an existing file. If you don't know the contents of the file, read it first.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "new_contents"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to edit, relative to the root of the workspace.",
|
||||
},
|
||||
new_contents: {
|
||||
type: "string",
|
||||
description: "The new file contents",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
26
core/tools/definitions/globSearch.ts
Normal file
26
core/tools/definitions/globSearch.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const globSearchTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Glob File Search",
|
||||
wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
|
||||
isCurrently: 'finding file matches for "{{{ pattern }}}"',
|
||||
hasAlready: 'retreived file matches for "{{{ pattern }}}"',
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.FileGlobSearch,
|
||||
description: "Search for files in the project",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["pattern"],
|
||||
properties: {
|
||||
pattern: {
|
||||
type: "string",
|
||||
description: "Glob pattern for file path matching",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -1,17 +1,17 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const exactSearchTool: Tool = {
|
||||
export const grepSearchTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Exact Search",
|
||||
displayTitle: "Grep Search",
|
||||
wouldLikeTo: 'search for "{{{ query }}}" in the repository',
|
||||
isCurrently: 'getting search results for "{{{ query }}}"',
|
||||
hasAlready: 'retreived search results for "{{{ query }}}"',
|
||||
hasAlready: 'retrieved search results for "{{{ query }}}"',
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.ExactSearch,
|
||||
description: "Perform an exact search over the repository using ripgrep.",
|
||||
name: BuiltInToolNames.GrepSearch,
|
||||
description: "Perform a search over the repository using ripgrep.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["query"],
|
||||
33
core/tools/definitions/lsTool.ts
Normal file
33
core/tools/definitions/lsTool.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const lsTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "LS Tool",
|
||||
wouldLikeTo: "list files and folders in {{{ dirPath }}}",
|
||||
isCurrently: "listing files and folders in {{{ dirPath }}}",
|
||||
hasAlready: "listed files and folders in {{{ dirPath }}}",
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.LSTool,
|
||||
description: "List files and folders in a given directory",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["dirPath", "recursive"],
|
||||
properties: {
|
||||
dirPath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'",
|
||||
},
|
||||
recursive: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"If true, lists files and folders recursively. To prevent unexpected large results, use this sparingly",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -7,7 +7,7 @@ export const searchWebTool: Tool = {
|
|||
displayTitle: "Search Web",
|
||||
wouldLikeTo: 'search the web for "{{{ query }}}"',
|
||||
isCurrently: 'searching the web for "{{{ query }}}"',
|
||||
hasAlready: 'searched the web fore "{{{ query }}}"',
|
||||
hasAlready: 'searched the web for "{{{ query }}}"',
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getCleanUriPath, getUriPathBasename } from "../../util/uri";
|
||||
|
||||
export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
||||
const resolvedFileUri = await inferResolvedUriFromRelativePath(
|
||||
|
|
@ -8,8 +9,26 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
|||
extras.ide,
|
||||
);
|
||||
if (resolvedFileUri) {
|
||||
const exists = await extras.ide.fileExists(resolvedFileUri);
|
||||
if (exists) {
|
||||
throw new Error(
|
||||
`File ${args.filepath} already exists. Use the edit tool to edit this file`,
|
||||
);
|
||||
}
|
||||
await extras.ide.writeFile(resolvedFileUri, args.contents);
|
||||
await extras.ide.openFile(resolvedFileUri);
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(resolvedFileUri),
|
||||
description: getCleanUriPath(resolvedFileUri),
|
||||
content: "File created successfuly",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: resolvedFileUri,
|
||||
},
|
||||
},
|
||||
];
|
||||
} else {
|
||||
throw new Error("Failed to resolve path");
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
import { ToolImpl } from ".";
|
||||
|
||||
export const exactSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const content = await extras.ide.getSearchResults(args.query);
|
||||
return [
|
||||
{
|
||||
name: "Search results",
|
||||
description: "Results from exact search",
|
||||
content,
|
||||
},
|
||||
];
|
||||
};
|
||||
12
core/tools/implementations/globSearch.ts
Normal file
12
core/tools/implementations/globSearch.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { ToolImpl } from ".";
|
||||
|
||||
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const results = await extras.ide.getFileResults(args.pattern);
|
||||
return [
|
||||
{
|
||||
name: "File results",
|
||||
description: "Results from file glob search",
|
||||
content: results.join("\n"),
|
||||
},
|
||||
];
|
||||
};
|
||||
13
core/tools/implementations/grepSearch.ts
Normal file
13
core/tools/implementations/grepSearch.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch";
|
||||
|
||||
export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const results = await extras.ide.getSearchResults(args.query);
|
||||
return [
|
||||
{
|
||||
name: "Search results",
|
||||
description: "Results from grep search",
|
||||
content: formatGrepSearchResults(results),
|
||||
},
|
||||
];
|
||||
};
|
||||
31
core/tools/implementations/lsTool.ts
Normal file
31
core/tools/implementations/lsTool.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
|
||||
export const lsToolImpl: ToolImpl = async (args, extras) => {
|
||||
const uri = await resolveRelativePathInDir(args.dirPath, extras.ide);
|
||||
if (!uri) {
|
||||
throw new Error(
|
||||
`Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`,
|
||||
);
|
||||
}
|
||||
|
||||
const entries = await walkDir(uri, extras.ide, {
|
||||
returnRelativeUrisPaths: true,
|
||||
include: "both",
|
||||
recursive: args.recursive ?? false,
|
||||
});
|
||||
|
||||
const content =
|
||||
entries.length > 0
|
||||
? entries.join("\n")
|
||||
: `No files/folders found in ${args.dirPath}`;
|
||||
|
||||
return [
|
||||
{
|
||||
name: "File/folder list",
|
||||
description: `Files/folders in ${args.dirPath}`,
|
||||
content,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
|
@ -1,21 +1,28 @@
|
|||
import { createNewFileTool } from "./definitions/createNewFile";
|
||||
import { exactSearchTool } from "./definitions/exactSearch";
|
||||
import { editFileTool } from "./definitions/editFile";
|
||||
import { globSearchTool } from "./definitions/globSearch";
|
||||
import { grepSearchTool } from "./definitions/grepSearch";
|
||||
import { lsTool } from "./definitions/lsTool";
|
||||
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
|
||||
import { readFileTool } from "./definitions/readFile";
|
||||
import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
|
||||
import { searchWebTool } from "./definitions/searchWeb";
|
||||
import { viewDiffTool } from "./definitions/viewDiff";
|
||||
import { viewRepoMapTool } from "./definitions/viewRepoMap";
|
||||
import { viewSubdirectoryTool } from "./definitions/viewSubdirectory";
|
||||
|
||||
export const allTools = [
|
||||
readFileTool,
|
||||
editFileTool,
|
||||
createNewFileTool,
|
||||
runTerminalCommandTool,
|
||||
viewSubdirectoryTool,
|
||||
viewRepoMapTool,
|
||||
exactSearchTool,
|
||||
|
||||
grepSearchTool,
|
||||
globSearchTool,
|
||||
searchWebTool,
|
||||
viewDiffTool,
|
||||
readCurrentlyOpenFileTool,
|
||||
|
||||
lsTool,
|
||||
// replacing with ls tool for now
|
||||
// viewSubdirectoryTool,
|
||||
// viewRepoMapTool,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -238,6 +238,10 @@ class FileSystemIde implements IDE {
|
|||
return "";
|
||||
}
|
||||
|
||||
async getFileResults(pattern: string): Promise<string[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
|
|
|||
61
core/util/grepSearch.ts
Normal file
61
core/util/grepSearch.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
export function formatGrepSearchResults(results: string): string {
|
||||
const keepLines: string[] = [];
|
||||
|
||||
function countLeadingSpaces(line: string) {
|
||||
return line?.match(/^ */)?.[0].length ?? 0;
|
||||
}
|
||||
|
||||
const processResult = (lines: string[]) => {
|
||||
// Skip results in which only the file path was kept
|
||||
const resultPath = lines[0];
|
||||
const resultContent = lines.slice(1);
|
||||
if (resultContent.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Add path
|
||||
keepLines.push(resultPath);
|
||||
|
||||
// Find the minimum indentation of content lines
|
||||
let minIndent = Infinity;
|
||||
for (const line of resultContent) {
|
||||
const indent = countLeadingSpaces(line);
|
||||
if (indent < minIndent) {
|
||||
minIndent = indent;
|
||||
}
|
||||
}
|
||||
|
||||
// Make all lines line up to 2-space indent
|
||||
const changeIndentBy = 2 - minIndent;
|
||||
if (changeIndentBy === 0) {
|
||||
keepLines.push(...resultContent);
|
||||
} else if (changeIndentBy < 0) {
|
||||
keepLines.push(
|
||||
...resultContent.map((line) => line.substring(-changeIndentBy)),
|
||||
);
|
||||
} else {
|
||||
keepLines.push(
|
||||
...resultContent.map((line) => " ".repeat(changeIndentBy) + line),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let resultLines: string[] = [];
|
||||
for (const line of results.split("\n").filter((l) => !!l)) {
|
||||
if (line.startsWith("./") || line === "--") {
|
||||
processResult(resultLines); // process previous result
|
||||
resultLines = [line];
|
||||
continue;
|
||||
}
|
||||
|
||||
// Exclude leading zero- or single-char lines
|
||||
if (resultLines.length === 1 && line.trim().length <= 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
resultLines.push(line);
|
||||
}
|
||||
processResult(resultLines);
|
||||
|
||||
return keepLines.join("\n");
|
||||
}
|
||||
|
|
@ -530,10 +530,6 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
|
|||
|
||||
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
|
||||
|
||||
### Prompt Files
|
||||
|
||||
See [Prompt Files](./deep-dives/prompt-files.md). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers.
|
||||
|
||||
### `@Issue`
|
||||
|
||||
Reference the conversation in a GitHub issue.
|
||||
|
|
@ -883,7 +879,6 @@ You can override this query by setting the `issueQuery` parameter.
|
|||
|
||||
You can set the `maxResults` parameter to limit the number of results returned. The default is `50`.
|
||||
|
||||
|
||||
### `@Discord`
|
||||
|
||||
Reference the messages in a Discord channel.
|
||||
|
|
|
|||
|
|
@ -1,69 +0,0 @@
|
|||
---
|
||||
title: Prompt files
|
||||
---
|
||||
|
||||
Prompt files allow you to build and use local prompts, and provide a convenient way to test and iterate on prompts before publishing them to the Hub.
|
||||
|
||||
:::info
|
||||
Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts)
|
||||
:::
|
||||
|
||||
## Quick start
|
||||
|
||||
Below is a quick example of setting up a prompt file:
|
||||
|
||||
1. Create a folder called `.continue/prompts` at the top level of your workspace (or you can use the button in the UI by typing @, selecting "Prompt Files", and selecting "New Prompt File").
|
||||
2. Add a file called `rails.prompt` to this folder.
|
||||
3. Write the following contents to `rails.prompt` and save.
|
||||
|
||||
```.prompt
|
||||
name: Rails Project
|
||||
description: Information about this project
|
||||
---
|
||||
Attached is a summary of the current Ruby on Rails application, including the @Gemfile and database schema in @db/schema.rb
|
||||
```
|
||||
|
||||
Now to use this prompt, you can highlight code and use <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> to select it in the Continue sidebar.
|
||||
|
||||
Then, type <kbd>/</kbd> and choose the "Rails Project" prompt. You can now ask any question as usual and the LLM will have the information from your .prompt file.
|
||||
|
||||
## Format
|
||||
|
||||
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers.
|
||||
|
||||
:::info
|
||||
The current state of this format is experimental and subject to change
|
||||
:::
|
||||
|
||||
### Preamble
|
||||
|
||||
The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters:
|
||||
|
||||
- `name` - The display title
|
||||
- `description` - The description you will see in the dropdown
|
||||
- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set)
|
||||
|
||||
If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator.
|
||||
|
||||
### Context
|
||||
|
||||
Many [context provider](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is:
|
||||
|
||||
- `@terminal` - The contents of the terminal
|
||||
- `@currentFile` - The currently active file
|
||||
- `@open` - All open files
|
||||
- `@os` - Information about the operating system
|
||||
- `@problems` - Problems reported by the language server in the active file
|
||||
- `@repo-map` - A map of files in the repository
|
||||
- `@tree` - A tree view of the repository structure
|
||||
|
||||
Or you can directly type URLs and file paths:
|
||||
|
||||
- `@https://github.com/continuedev/continue` - The contents of a URL
|
||||
- `@src/index.ts` - The contents of a file (VS Code only)
|
||||
|
||||
All references will be attached as context items, rather than injected directly inline.
|
||||
|
||||
## Feedback
|
||||
|
||||
If you have ideas about how to improve the `.prompt` file format, please reach out on [Discord](https://discord.gg/NWtdYexhMs).
|
||||
97
docs/docs/customize/deep-dives/prompts.md
Normal file
97
docs/docs/customize/deep-dives/prompts.md
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
---
|
||||
title: Prompts
|
||||
---
|
||||
|
||||
Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks.
|
||||
|
||||
:::info
|
||||
Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts)
|
||||
:::
|
||||
|
||||
## Examples
|
||||
|
||||
Below are some examples to get you started.
|
||||
|
||||
### Security review
|
||||
|
||||
```text title="Security best practices review"
|
||||
@open - Review these files for the following security best practices:
|
||||
- Does the architecture follow security-by-design principles?
|
||||
- Are there potential security vulnerabilities in the system design?
|
||||
- Is sensitive data handled appropriately throughout the lifecycle?
|
||||
```
|
||||
|
||||
### Reference best practice guides
|
||||
|
||||
```text title="Redux best practices review"
|
||||
@https://redux.js.org/style-guide/
|
||||
@currentFile
|
||||
|
||||
Review this code for adherence to Redux best practices.
|
||||
```
|
||||
|
||||
### Pull in commonly used files for tasks
|
||||
|
||||
```text title="Generate a new TypeORM entity"
|
||||
@src/db/dataSource.ts @src/db/entity/SampleEntity.ts
|
||||
|
||||
Use these files to generate a new TypeORM entity based on the following requirements:
|
||||
```
|
||||
|
||||
## Including Context Providers in your prompts
|
||||
|
||||
Many [context providers](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is:
|
||||
|
||||
- `@terminal` - The contents of the terminal
|
||||
- `@currentFile` - The currently active file
|
||||
- `@open` - All open files
|
||||
- `@os` - Information about the operating system
|
||||
- `@problems` - Problems reported by the language server in the active file
|
||||
- `@repo-map` - A map of files in the repository
|
||||
- `@tree` - A tree view of the repository structure
|
||||
|
||||
Or you can directly type URLs and file paths:
|
||||
|
||||
- `@https://github.com/continuedev/continue` - The contents of a URL
|
||||
- `@src/index.ts` - The contents of a file (VS Code only)
|
||||
|
||||
All references will be attached as context items, rather than injected directly inline.
|
||||
|
||||
## Local `.prompt` files
|
||||
|
||||
In addition to Prompt blocks on the Hub, you can also define prompts in local `.prompt` files, located in the `.continue/prompts` folder at the top level of your workspace. This is useful for quick iteration on prompts to test them out before pushing up to the Hub.
|
||||
|
||||
### Quick Start
|
||||
|
||||
Below is a quick example of setting up a prompt file:
|
||||
|
||||
1. Create a folder called `.continue/prompts` at the top level of your workspace
|
||||
2. Add a file called `test.prompt` to this folder.
|
||||
3. Write the following contents to `test.prompt` and save.
|
||||
|
||||
```.prompt
|
||||
name: Current file prompt
|
||||
description: A test prompt using the current file context provider
|
||||
---
|
||||
@currentFile
|
||||
```
|
||||
|
||||
Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and add type out some additional text such as "Review the code for any issues".
|
||||
|
||||
### Format
|
||||
|
||||
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers.
|
||||
|
||||
:::info
|
||||
The current state of this format is experimental and subject to change
|
||||
:::
|
||||
|
||||
### Preamble
|
||||
|
||||
The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters:
|
||||
|
||||
- `name` - The display title
|
||||
- `description` - The description you will see in the dropdown
|
||||
- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set)
|
||||
|
||||
If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue