Merge branch 'main' into reasoning_params_to_schemas
This commit is contained in:
commit
ff204efad6
360 changed files with 14804 additions and 4692 deletions
61
.github/workflows/auto-release.yml
vendored
61
.github/workflows/auto-release.yml
vendored
|
|
@ -1,6 +1,9 @@
|
|||
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
|
||||
|
|
@ -13,30 +16,13 @@ jobs:
|
|||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Important for getting all tags and commits
|
||||
|
||||
- name: Get latest tag
|
||||
id: get_latest_tag
|
||||
- name: Get version from package.json
|
||||
id: get_version
|
||||
run: |
|
||||
# Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists
|
||||
latest_tag=$(git tag --sort=-creatordate | grep -E "-vscode$" | head -n 1 || echo "v1.1.0-vscode")
|
||||
echo "Latest tag: $latest_tag"
|
||||
echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV
|
||||
|
||||
- name: Generate next version
|
||||
id: generate_version
|
||||
run: |
|
||||
# Extract version numbers (handle the -vscode suffix)
|
||||
version=${LATEST_TAG#v} # Remove v prefix
|
||||
version=${version%-vscode} # Remove -vscode suffix
|
||||
IFS='.' read -ra VERSION_PARTS <<< "$version"
|
||||
|
||||
# Increment patch version
|
||||
((VERSION_PARTS[2]++))
|
||||
|
||||
# Create new version string with -vscode suffix
|
||||
new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-vscode"
|
||||
# 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
|
||||
|
||||
|
|
@ -49,7 +35,7 @@ jobs:
|
|||
--generate-notes \
|
||||
--title "$NEW_VERSION" \
|
||||
--draft \
|
||||
--latest
|
||||
--latest \
|
||||
--prerelease
|
||||
|
||||
create-jetbrains-release:
|
||||
|
|
@ -60,29 +46,14 @@ jobs:
|
|||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Important for getting all tags and commits
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get latest tag
|
||||
id: get_latest_tag
|
||||
- name: Get version from gradle.properties
|
||||
id: get_version
|
||||
run: |
|
||||
# Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists
|
||||
latest_tag=$(git tag --sort=-creatordate | grep -E "-jetbrains$" | head -n 1 || echo "v1.1.0-jetbrains")
|
||||
echo "Latest tag: $latest_tag"
|
||||
echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV
|
||||
|
||||
- name: Generate next version
|
||||
id: generate_version
|
||||
run: |
|
||||
# Extract version numbers (handle the -jetbrains suffix)
|
||||
version=${LATEST_TAG#v} # Remove v prefix
|
||||
version=${version%-jetbrains} # Remove -jetbrains suffix
|
||||
IFS='.' read -ra VERSION_PARTS <<< "$version"
|
||||
|
||||
# Increment patch version
|
||||
((VERSION_PARTS[2]++))
|
||||
|
||||
# Create new version string with -jetbrains suffix
|
||||
new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-jetbrains"
|
||||
# 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
|
||||
|
||||
|
|
@ -95,5 +66,5 @@ jobs:
|
|||
--generate-notes \
|
||||
--title "$NEW_VERSION" \
|
||||
--draft \
|
||||
--latest
|
||||
--latest \
|
||||
--prerelease
|
||||
|
|
|
|||
61
.github/workflows/jetbrains-release.yaml
vendored
61
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -37,6 +37,52 @@ jobs:
|
|||
echo "should_run=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
bump-version:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- check_release_name
|
||||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
# 0. Setup git
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
git config --local user.email "action@github.com"
|
||||
git config --local user.name "GitHub Action"
|
||||
|
||||
- name: Create PR branch
|
||||
run: |
|
||||
BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)"
|
||||
git checkout -b $BRANCH_NAME
|
||||
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
|
||||
|
||||
- name: Bump version in gradle.properties
|
||||
run: |
|
||||
cd extensions/intelllij
|
||||
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
|
||||
rm -rf tmp
|
||||
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
|
||||
echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@v7
|
||||
with:
|
||||
token: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
|
||||
title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}"
|
||||
body: |
|
||||
Automated PR to bump the JetBrains extension version after successful pre-release publication.
|
||||
|
||||
- Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }}
|
||||
branch: ${{ env.BRANCH_NAME }}
|
||||
base: main
|
||||
delete-branch: true
|
||||
|
||||
# Prepare and publish the plugin to JetBrains Marketplace repository
|
||||
build:
|
||||
needs: check_release_name
|
||||
|
|
@ -121,6 +167,21 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Build and check config-yaml
|
||||
run: |
|
||||
cd ../../packages/config-yaml
|
||||
npm i
|
||||
npx tsc --noEmit
|
||||
# Tests are currently failing, commenting out for now
|
||||
# npm test
|
||||
npm run build
|
||||
|
||||
# npm install core
|
||||
- name: Install core node_modules
|
||||
run: |
|
||||
|
|
|
|||
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) }}
|
||||
|
|
|
|||
2
.github/workflows/preview.yaml
vendored
2
.github/workflows/preview.yaml
vendored
|
|
@ -263,7 +263,7 @@ jobs:
|
|||
echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@v5
|
||||
uses: peter-evans/create-pull-request@v7
|
||||
with:
|
||||
token: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
|
||||
|
|
|
|||
15
.github/workflows/vscode-version-bump.yml
vendored
15
.github/workflows/vscode-version-bump.yml
vendored
|
|
@ -1,4 +1,4 @@
|
|||
name: VS Code Extension Version Bump
|
||||
name: Create VS Code main release draft
|
||||
on:
|
||||
schedule:
|
||||
# Runs at 7 AM PST (15:00 UTC) every Friday
|
||||
|
|
@ -15,6 +15,10 @@ jobs:
|
|||
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:
|
||||
|
|
@ -97,6 +101,15 @@ jobs:
|
|||
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
|
||||
|
|
|
|||
2
binary/package-lock.json
generated
2
binary/package-lock.json
generated
|
|
@ -48,7 +48,7 @@
|
|||
"@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.71",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
|
|
|
|||
|
|
@ -234,15 +234,17 @@ describe("Test Suite", () => {
|
|||
result: { config },
|
||||
} = await messenger.request("config/getSerializedProfileInfo", undefined);
|
||||
|
||||
expect(config!.models.some((m) => m.title === model.title)).toBe(true);
|
||||
expect(config!.modelsByRole.chat.some((m) => m.title === model.title)).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
await messenger.request("config/deleteModel", { title: model.title });
|
||||
const {
|
||||
result: { config: configAfterDelete },
|
||||
} = await messenger.request("config/getSerializedProfileInfo", undefined);
|
||||
expect(configAfterDelete!.models.some((m) => m.title === model.title)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
configAfterDelete!.modelsByRole.chat.some((m) => m.title === model.title),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should make an LLM completion", async () => {
|
||||
|
|
|
|||
|
|
@ -12,11 +12,11 @@
|
|||
"curly": "off",
|
||||
"@typescript-eslint/semi": "off",
|
||||
"eqeqeq": "error",
|
||||
"complexity": ["error", { "max": 38 }],
|
||||
"max-lines-per-function": ["error", { "max": 996 }],
|
||||
"max-statements": ["error", { "max": 114 }],
|
||||
"complexity": ["error", { "max": 36 }],
|
||||
"max-lines-per-function": ["error", { "max": 472 }],
|
||||
"max-statements": ["error", { "max": 108 }],
|
||||
"max-depth": ["error", { "max": 6 }],
|
||||
"max-nested-callbacks": ["error", { "max": 4 }],
|
||||
"max-params": ["error", { "max": 11 }]
|
||||
"max-params": ["error", { "max": 8 }]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ const DraftIssueCommand: SlashCommand = {
|
|||
let title = await llm.complete(
|
||||
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
|
||||
new AbortController().signal,
|
||||
{ maxTokens: 20 },
|
||||
{ maxTokens: 30 },
|
||||
);
|
||||
|
||||
title = `${removeQuotesAndEscapes(title.trim())}\n\n`;
|
||||
|
|
@ -40,7 +40,7 @@ const DraftIssueCommand: SlashCommand = {
|
|||
|
||||
let body = "";
|
||||
const messages: ChatMessage[] = [
|
||||
...history,
|
||||
...history.filter((msg) => msg.role !== "system"),
|
||||
{ role: "user", content: PROMPT(input, title) },
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
export function constructMcpSlashCommand(
|
||||
|
|
@ -22,8 +23,8 @@ export function constructMcpSlashCommand(
|
|||
}
|
||||
|
||||
const result = await client.getPrompt({ name, arguments: argsObject });
|
||||
|
||||
const messages: ChatMessage[] = result.messages.map((msg) => {
|
||||
const mcpMessages: PromptMessage[] = result.messages;
|
||||
const messages: ChatMessage[] = mcpMessages.map((msg) => {
|
||||
if (msg.content.type !== "text") {
|
||||
throw new Error(
|
||||
"Continue currently only supports text prompts through MCP",
|
||||
|
|
@ -40,12 +41,22 @@ export function constructMcpSlashCommand(
|
|||
return;
|
||||
}
|
||||
|
||||
const reversedMessages = [...messages].reverse();
|
||||
const messageToAppendInput =
|
||||
reversedMessages.find((m) => m.role === "user") ??
|
||||
reversedMessages.find((m) => m.role === "assistant") ??
|
||||
reversedMessages[0];
|
||||
messageToAppendInput.content += ` ${userInput}`;
|
||||
if (userInput) {
|
||||
const lastMessage = messages.at(-1);
|
||||
if (!lastMessage || lastMessage.role !== "user") {
|
||||
messages.push({
|
||||
role: "user",
|
||||
content: userInput,
|
||||
});
|
||||
} else {
|
||||
let newContent = renderChatMessage(lastMessage);
|
||||
if (newContent) {
|
||||
newContent += "\n\n";
|
||||
}
|
||||
newContent += userInput;
|
||||
lastMessage.content = newContent;
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
|
|
|
|||
|
|
@ -34,13 +34,18 @@ export function ctxItemToRifWithContents(
|
|||
): RangeInFileWithContents {
|
||||
let startLine = 0;
|
||||
let endLine = 0;
|
||||
let adjustLines = linesOffByOne ? 1 : 0;
|
||||
|
||||
const nameSplit = item.name.split("(");
|
||||
|
||||
if (nameSplit.length > 1) {
|
||||
const lines = nameSplit[1].split(")")[0].split("-");
|
||||
startLine = Number.parseInt(lines[0], 10) - (linesOffByOne ? 1 : 0);
|
||||
endLine = Number.parseInt(lines[1], 10) - (linesOffByOne ? 1 : 0);
|
||||
startLine = Number.parseInt(lines[0], 10);
|
||||
if (startLine === 0) {
|
||||
adjustLines = 0; // safety to make sure doesn't go negative
|
||||
}
|
||||
startLine -= adjustLines;
|
||||
endLine = Number.parseInt(lines[1], 10) - adjustLines;
|
||||
}
|
||||
|
||||
const rif: RangeInFileWithContents = {
|
||||
|
|
|
|||
|
|
@ -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 () => {
|
||||
|
|
|
|||
|
|
@ -4,25 +4,18 @@ import {
|
|||
ControlPlaneClient,
|
||||
ControlPlaneSessionInfo,
|
||||
} from "../control-plane/client.js";
|
||||
import { getControlPlaneEnv, useHub } from "../control-plane/env.js";
|
||||
import { getControlPlaneEnv } from "../control-plane/env.js";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContinueConfig,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
} from "../index.js";
|
||||
import Ollama from "../llm/llms/Ollama.js";
|
||||
import { GlobalContext } from "../util/GlobalContext.js";
|
||||
|
||||
import { getAllAssistantFiles } from "./loadLocalAssistants.js";
|
||||
import {
|
||||
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 {
|
||||
|
|
@ -141,16 +134,11 @@ export class ConfigHandler {
|
|||
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)));
|
||||
}
|
||||
const personalHubOrg = await this.getPersonalHubOrg();
|
||||
const hubOrgs = await Promise.all(
|
||||
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
|
||||
);
|
||||
return [...hubOrgs, personalHubOrg];
|
||||
} else {
|
||||
return [await this.getLocalOrg()];
|
||||
}
|
||||
|
|
@ -172,22 +160,22 @@ export class ConfigHandler {
|
|||
|
||||
return await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create(
|
||||
{
|
||||
const profileLoader = await PlatformProfileLoader.create({
|
||||
configResult: {
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
assistant.ownerSlug,
|
||||
assistant.packageSlug,
|
||||
assistant.iconUrl,
|
||||
assistant.configResult.config?.version ?? "latest",
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.llmLogger,
|
||||
assistant.rawYaml,
|
||||
orgScopeId,
|
||||
);
|
||||
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);
|
||||
}),
|
||||
|
|
@ -219,25 +207,6 @@ export class ConfigHandler {
|
|||
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[],
|
||||
|
|
@ -473,27 +442,6 @@ export class ConfigHandler {
|
|||
}
|
||||
}
|
||||
|
||||
// Only used till we move to using selectedModelByRole.chat
|
||||
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");
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
// Ancient method of adding custom providers through vs code
|
||||
private additionalContextProviders: IContextProvider[] = [];
|
||||
registerCustomContextProvider(contextProvider: IContextProvider) {
|
||||
|
|
|
|||
|
|
@ -1,26 +0,0 @@
|
|||
import { IDE } from "..";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
|
||||
|
||||
export async function getSystemPromptDotFile(ide: IDE): Promise<string | null> {
|
||||
const dirs = await ide.getWorkspaceDirs();
|
||||
|
||||
let prompts: string[] = [];
|
||||
for (const dir of dirs) {
|
||||
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
|
||||
if (await ide.fileExists(dotFile)) {
|
||||
try {
|
||||
const content = await ide.readFile(dotFile);
|
||||
prompts.push(content);
|
||||
} catch (e) {
|
||||
// ignore if file doesn't exist
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!prompts.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return prompts.join("\n\n");
|
||||
}
|
||||
32
core/config/getWorkspaceContinueRuleDotFiles.ts
Normal file
32
core/config/getWorkspaceContinueRuleDotFiles.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { ConfigValidationError } from "@continuedev/config-yaml";
|
||||
import { IDE, RuleWithSource } from "..";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
|
||||
|
||||
export async function getWorkspaceContinueRuleDotFiles(ide: IDE) {
|
||||
const dirs = await ide.getWorkspaceDirs();
|
||||
|
||||
const errors: ConfigValidationError[] = [];
|
||||
const rules: RuleWithSource[] = [];
|
||||
for (const dir of dirs) {
|
||||
try {
|
||||
const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE);
|
||||
const exists = await ide.fileExists(dotFile);
|
||||
if (exists) {
|
||||
const content = await ide.readFile(dotFile);
|
||||
rules.push({
|
||||
rule: content,
|
||||
ruleFile: dotFile,
|
||||
source: ".continuerules",
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Failed to load system prompt dot file from workspace ${dir}: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { rules, errors };
|
||||
}
|
||||
|
|
@ -8,7 +8,6 @@ import {
|
|||
ConfigValidationError,
|
||||
ModelRole,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import * as JSONC from "comment-json";
|
||||
import * as tar from "tar";
|
||||
|
||||
|
|
@ -19,7 +18,6 @@ import {
|
|||
ContinueConfig,
|
||||
ContinueRcJson,
|
||||
CustomContextProvider,
|
||||
CustomLLM,
|
||||
EmbeddingsProviderDescription,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
|
|
@ -38,7 +36,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";
|
||||
|
|
@ -46,9 +43,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";
|
||||
|
|
@ -71,9 +67,12 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util";
|
||||
import {
|
||||
getModelByRole,
|
||||
isSupportedLanceDbCpuTargetForLinux,
|
||||
serializePromptTemplates,
|
||||
} from "./util";
|
||||
import { validateConfig } from "./validation.js";
|
||||
|
||||
export function resolveSerializedConfig(
|
||||
|
|
@ -204,12 +203,6 @@ async function serializedToIntermediateConfig(
|
|||
return config;
|
||||
}
|
||||
|
||||
function isModelDescription(
|
||||
llm: ModelDescription | CustomLLM,
|
||||
): llm is ModelDescription {
|
||||
return (llm as ModelDescription).title !== undefined;
|
||||
}
|
||||
|
||||
export function isContextProviderWithParams(
|
||||
contextProvider: CustomContextProvider | ContextProviderWithParams,
|
||||
): contextProvider is ContextProviderWithParams {
|
||||
|
|
@ -217,96 +210,106 @@ export function isContextProviderWithParams(
|
|||
}
|
||||
|
||||
/** Only difference between intermediate and final configs is the `models` array */
|
||||
async function intermediateToFinalConfig(
|
||||
config: Config,
|
||||
ide: IDE,
|
||||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
llmLogger: ILLMLogger,
|
||||
workOsAccessToken: string | undefined,
|
||||
loadPromptFiles: boolean = true,
|
||||
allowFreeTrial: boolean = true,
|
||||
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
async function intermediateToFinalConfig({
|
||||
config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
loadPromptFiles = true,
|
||||
allowFreeTrial = true,
|
||||
}: {
|
||||
config: Config;
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
loadPromptFiles?: boolean;
|
||||
allowFreeTrial?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
// Auto-detect models
|
||||
let models: BaseLLM[] = [];
|
||||
for (const desc of config.models) {
|
||||
if (isModelDescription(desc)) {
|
||||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
config.systemMessage,
|
||||
);
|
||||
if (!llm) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const detectedModels = await Promise.all(
|
||||
modelNames.map(async (modelName) => {
|
||||
return await llmFromDescription(
|
||||
{
|
||||
...desc,
|
||||
model: modelName,
|
||||
title: modelName,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
copyOf(config.completionOptions),
|
||||
config.systemMessage,
|
||||
);
|
||||
}),
|
||||
);
|
||||
models.push(
|
||||
...(detectedModels.filter(
|
||||
(x) => typeof x !== "undefined",
|
||||
) as BaseLLM[]),
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
await Promise.all(
|
||||
config.models.map(async (desc) => {
|
||||
if ("title" in desc) {
|
||||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
);
|
||||
if (!llm) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
models.push(llm);
|
||||
}
|
||||
} else {
|
||||
const llm = new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, logger: llmLogger } as any,
|
||||
});
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const models = modelNames.map(
|
||||
(modelName) =>
|
||||
new CustomLLMClass({
|
||||
...desc,
|
||||
options: {
|
||||
...desc.options,
|
||||
model: modelName,
|
||||
logger: llmLogger,
|
||||
},
|
||||
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const detectedModels = await Promise.all(
|
||||
modelNames.map(async (modelName) => {
|
||||
return await llmFromDescription(
|
||||
{
|
||||
...desc,
|
||||
model: modelName,
|
||||
title: modelName,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
copyOf(config.completionOptions),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
models.push(...models);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
);
|
||||
models.push(
|
||||
...(detectedModels.filter(
|
||||
(x) => typeof x !== "undefined",
|
||||
) as BaseLLM[]),
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
}
|
||||
} else {
|
||||
models.push(llm);
|
||||
}
|
||||
} else {
|
||||
models.push(llm);
|
||||
const llm = new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, logger: llmLogger } as any,
|
||||
});
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const models = modelNames.map(
|
||||
(modelName) =>
|
||||
new CustomLLMClass({
|
||||
...desc,
|
||||
options: {
|
||||
...desc.options,
|
||||
model: modelName,
|
||||
logger: llmLogger,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
models.push(...models);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
}
|
||||
} else {
|
||||
models.push(llm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Prepare models
|
||||
for (const model of models) {
|
||||
|
|
@ -342,7 +345,7 @@ async function intermediateToFinalConfig(
|
|||
? config.tabAutocompleteModel
|
||||
: [config.tabAutocompleteModel]
|
||||
).map(async (desc) => {
|
||||
if (isModelDescription(desc)) {
|
||||
if ("title" in desc) {
|
||||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
|
|
@ -350,7 +353,6 @@ async function intermediateToFinalConfig(
|
|||
ideSettings,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
config.systemMessage,
|
||||
);
|
||||
|
||||
if (llm?.providerName === "free-trial") {
|
||||
|
|
@ -425,38 +427,32 @@ async function intermediateToFinalConfig(
|
|||
function getEmbeddingsILLM(
|
||||
embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
|
||||
): ILLM | null {
|
||||
if (!embedConfig) {
|
||||
return null;
|
||||
}
|
||||
if ("providerName" in embedConfig) {
|
||||
return embedConfig;
|
||||
}
|
||||
const { provider, ...options } = embedConfig;
|
||||
const embeddingsProviderClass = allEmbeddingsProviders[provider];
|
||||
if (embeddingsProviderClass) {
|
||||
if (
|
||||
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
|
||||
) {
|
||||
return new embeddingsProviderClass();
|
||||
} else {
|
||||
const llmOptions: LLMOptions = {
|
||||
model: options.model ?? "UNSPECIFIED",
|
||||
...options,
|
||||
};
|
||||
return new embeddingsProviderClass(
|
||||
llmOptions,
|
||||
(url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...config.requestOptions,
|
||||
...options.requestOptions,
|
||||
}),
|
||||
);
|
||||
if (embedConfig) {
|
||||
// config.ts-injected ILLM
|
||||
if ("providerName" in embedConfig) {
|
||||
return embedConfig;
|
||||
}
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Embeddings provider ${provider} not found. Using default`,
|
||||
});
|
||||
const { provider, ...options } = embedConfig;
|
||||
if (provider === "transformers.js") {
|
||||
return new TransformersJsEmbeddingsProvider();
|
||||
} else {
|
||||
const cls = LLMClasses.find((c) => c.providerName === provider);
|
||||
if (cls) {
|
||||
const llmOptions: LLMOptions = {
|
||||
model: options.model ?? "UNSPECIFIED",
|
||||
...options,
|
||||
};
|
||||
return new cls(llmOptions);
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Embeddings provider ${provider} not found`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ideInfo.ideType === "vscode") {
|
||||
return new TransformersJsEmbeddingsProvider();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -469,11 +465,11 @@ async function intermediateToFinalConfig(
|
|||
if (!rerankingConfig) {
|
||||
return null;
|
||||
}
|
||||
// config.ts-injected ILLM
|
||||
if ("providerName" in rerankingConfig) {
|
||||
return rerankingConfig;
|
||||
}
|
||||
const { name, params } = config.reranker as RerankerDescription;
|
||||
const rerankerClass = AllRerankers[name];
|
||||
|
||||
if (name === "llm") {
|
||||
const llm = models.find((model) => model.title === params?.modelTitle);
|
||||
|
|
@ -486,16 +482,20 @@ async function intermediateToFinalConfig(
|
|||
} else {
|
||||
return new LLMReranker(llm);
|
||||
}
|
||||
} else if (rerankerClass) {
|
||||
const llmOptions: LLMOptions = {
|
||||
model: "rerank-2",
|
||||
...params,
|
||||
};
|
||||
return new rerankerClass(llmOptions, (url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...params?.requestOptions,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
const cls = LLMClasses.find((c) => c.providerName === name);
|
||||
if (cls) {
|
||||
const llmOptions: LLMOptions = {
|
||||
model: params?.model,
|
||||
...params,
|
||||
};
|
||||
return new cls(llmOptions);
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Unknown reranking provider ${name}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -504,7 +504,6 @@ async function intermediateToFinalConfig(
|
|||
const continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
models,
|
||||
tools: [...allTools],
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: config.slashCommands ?? [],
|
||||
|
|
@ -526,8 +525,16 @@ async function intermediateToFinalConfig(
|
|||
rerank: newReranker ?? null,
|
||||
summarize: null, // Not implemented
|
||||
},
|
||||
rules: [],
|
||||
};
|
||||
|
||||
if (config.systemMessage) {
|
||||
continueConfig.rules.unshift({
|
||||
rule: config.systemMessage,
|
||||
source: "json-systemMessage",
|
||||
});
|
||||
}
|
||||
|
||||
// Trigger MCP server refreshes (Config is reloaded again once connected!)
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.setConnections(
|
||||
|
|
@ -544,7 +551,7 @@ async function intermediateToFinalConfig(
|
|||
// Handle experimental modelRole config values for apply and edit
|
||||
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
|
||||
if (inlineEditModel) {
|
||||
const match = continueConfig.models.find(
|
||||
const match = continueConfig.modelsByRole.chat.find(
|
||||
(m) => m.title === inlineEditModel,
|
||||
);
|
||||
if (match) {
|
||||
|
|
@ -563,7 +570,7 @@ async function intermediateToFinalConfig(
|
|||
"applyCodeBlock",
|
||||
)?.title;
|
||||
if (applyBlockModel) {
|
||||
const match = continueConfig.models.find(
|
||||
const match = continueConfig.modelsByRole.chat.find(
|
||||
(m) => m.title === applyBlockModel,
|
||||
);
|
||||
if (match) {
|
||||
|
|
@ -602,11 +609,12 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
contextLength: llm.contextLength,
|
||||
template: llm.template,
|
||||
completionOptions: llm.completionOptions,
|
||||
systemMessage: llm.systemMessage,
|
||||
baseChatSystemMessage: llm.baseChatSystemMessage,
|
||||
requestOptions: llm.requestOptions,
|
||||
promptTemplates: llm.promptTemplates as any,
|
||||
promptTemplates: serializePromptTemplates(llm.promptTemplates),
|
||||
capabilities: llm.capabilities,
|
||||
roles: llm.roles,
|
||||
configurationStatus: llm.getConfigurationStatus(),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -616,8 +624,6 @@ async function finalToBrowserConfig(
|
|||
): Promise<BrowserSerializedContinueConfig> {
|
||||
return {
|
||||
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
|
||||
models: final.models.map(llmToSerializedModelDescription),
|
||||
systemMessage: final.systemMessage,
|
||||
completionOptions: final.completionOptions,
|
||||
slashCommands: final.slashCommands?.map(
|
||||
({ run, ...slashCommandDescription }) => slashCommandDescription,
|
||||
|
|
@ -857,11 +863,6 @@ async function loadContinueConfigFromJson(
|
|||
return { errors, config: undefined, configLoadInterrupted: true };
|
||||
}
|
||||
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
if (systemPromptDotFile) {
|
||||
serialized.systemMessage = systemPromptDotFile;
|
||||
}
|
||||
|
||||
// Apply shared config
|
||||
// TODO: override several of these values with user/org shared config
|
||||
const sharedConfig = new GlobalContext().getSharedConfig();
|
||||
|
|
@ -930,15 +931,15 @@ async function loadContinueConfigFromJson(
|
|||
|
||||
// Convert to final config format
|
||||
const { config: finalConfig, errors: finalErrors } =
|
||||
await intermediateToFinalConfig(
|
||||
intermediate,
|
||||
await intermediateToFinalConfig({
|
||||
config: intermediate,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
);
|
||||
});
|
||||
return {
|
||||
config: finalConfig,
|
||||
errors: [...(errors ?? []), ...finalErrors],
|
||||
|
|
|
|||
|
|
@ -1,3 +1,10 @@
|
|||
/**
|
||||
* I'm disabling this rule for the entire file under the assumption
|
||||
* that this is a one-time migration script. I'm expecting this
|
||||
* code to be removed in the future.
|
||||
*/
|
||||
/* eslint-disable max-statements */
|
||||
|
||||
import { IDE } from "..";
|
||||
import { deduplicateArray } from "../util";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
|
|
|
|||
|
|
@ -1,80 +0,0 @@
|
|||
import { ConfigJson } from "@continuedev/config-types";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { PRODUCTION_ENV } from "../../control-plane/env.js";
|
||||
import {
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
SerializedContinueConfig,
|
||||
} from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
export default class ControlPlaneProfileLoader implements IProfileLoader {
|
||||
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
|
||||
|
||||
description: ProfileDescription;
|
||||
|
||||
workspaceSettings: ConfigJson | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly workspaceId: string,
|
||||
private workspaceTitle: string,
|
||||
private readonly controlPlaneClient: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private llmLogger: ILLMLogger,
|
||||
private readonly onReload: () => void,
|
||||
) {
|
||||
this.description = {
|
||||
id: workspaceId,
|
||||
profileType: "control-plane",
|
||||
iconUrl: "",
|
||||
fullSlug: {
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
title: workspaceTitle,
|
||||
errors: undefined,
|
||||
uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`,
|
||||
};
|
||||
|
||||
setInterval(async () => {
|
||||
this.workspaceSettings =
|
||||
await this.controlPlaneClient.getSettingsForWorkspace(
|
||||
this.description.id,
|
||||
);
|
||||
this.onReload();
|
||||
}, ControlPlaneProfileLoader.RELOAD_INTERVAL);
|
||||
}
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
const settings =
|
||||
this.workspaceSettings ??
|
||||
((await this.controlPlaneClient.getSettingsForWorkspace(
|
||||
this.description.id,
|
||||
)) as any);
|
||||
const serializedConfig: SerializedContinueConfig = settings;
|
||||
|
||||
return await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.llmLogger,
|
||||
serializedConfig,
|
||||
undefined,
|
||||
undefined,
|
||||
this.workspaceId,
|
||||
undefined,
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
setIsActive(isActive: boolean): void {}
|
||||
}
|
||||
|
|
@ -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.llmLogger,
|
||||
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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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 llmLogger: ILLMLogger,
|
||||
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>,
|
||||
llmLogger: ILLMLogger,
|
||||
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,
|
||||
|
|
@ -77,7 +125,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
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.llmLogger,
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -34,20 +34,32 @@ import { migrateJsonSharedConfig } from "../migrateSharedConfig";
|
|||
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
|
||||
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
|
||||
|
||||
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
|
||||
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
|
||||
|
||||
export default async function doLoadConfig(
|
||||
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>> {
|
||||
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();
|
||||
|
|
@ -70,19 +82,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,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
configYamlPath,
|
||||
orgScopeId,
|
||||
);
|
||||
});
|
||||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
configLoadInterrupted = result.configLoadInterrupted;
|
||||
|
|
@ -110,6 +121,12 @@ export default async function doLoadConfig(
|
|||
// Remove ability have undefined errors, just have an array
|
||||
errors = [...(errors ?? [])];
|
||||
|
||||
// Add rules from .continuerules files
|
||||
const { rules, errors: continueRulesErrors } =
|
||||
await getWorkspaceContinueRuleDotFiles(ide);
|
||||
newConfig.rules.unshift(...rules);
|
||||
errors.push(...continueRulesErrors);
|
||||
|
||||
// Rectify model selections for each role
|
||||
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
|
||||
|
||||
|
|
@ -258,7 +275,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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -658,7 +658,6 @@ declare global {
|
|||
remoteConfigServerUrl: string | undefined;
|
||||
remoteConfigSyncPeriod: number;
|
||||
userToken: string;
|
||||
enableControlServerBeta: boolean;
|
||||
pauseCodebaseIndexOnStart: boolean;
|
||||
}
|
||||
|
||||
|
|
@ -958,7 +957,7 @@ declare global {
|
|||
cacheBehavior?: CacheBehavior;
|
||||
}
|
||||
|
||||
export interface EmbedOptions {
|
||||
export interface JSONEmbedOptions {
|
||||
apiBase?: string;
|
||||
apiKey?: string;
|
||||
model?: string;
|
||||
|
|
|
|||
45
core/config/util.test.ts
Normal file
45
core/config/util.test.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { PromptTemplate } from "..";
|
||||
import { serializePromptTemplates } from "./util";
|
||||
|
||||
describe("serializePromptTemplates", () => {
|
||||
it("should return undefined for undefined input", () => {
|
||||
expect(serializePromptTemplates(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should convert function templates to empty strings", () => {
|
||||
const functionTemplate: PromptTemplate = () => "Generated template";
|
||||
const templates: Record<string, PromptTemplate> = {
|
||||
template1: functionTemplate,
|
||||
};
|
||||
|
||||
const result = serializePromptTemplates(templates);
|
||||
|
||||
expect(result).toEqual({ template1: "" });
|
||||
});
|
||||
|
||||
it("should pass through string templates unchanged", () => {
|
||||
const templates: Record<string, PromptTemplate> = {
|
||||
template1: "This is a static template",
|
||||
template2: "Another static template",
|
||||
};
|
||||
|
||||
const result = serializePromptTemplates(templates);
|
||||
|
||||
expect(result).toEqual(templates);
|
||||
});
|
||||
|
||||
it("should handle mixed template types", () => {
|
||||
const functionTemplate: PromptTemplate = () => "Generated template";
|
||||
const templates: Record<string, PromptTemplate> = {
|
||||
function: functionTemplate,
|
||||
string: "This is a static template",
|
||||
};
|
||||
|
||||
const result = serializePromptTemplates(templates);
|
||||
|
||||
expect(result).toEqual({
|
||||
function: "",
|
||||
string: "This is a static template",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,13 +1,16 @@
|
|||
import fs from "fs";
|
||||
import os from "os";
|
||||
|
||||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import {
|
||||
ContinueConfig,
|
||||
ExperimentalModelRoles,
|
||||
IDE,
|
||||
ILLM,
|
||||
ModelDescription,
|
||||
JSONModelDescription,
|
||||
PromptTemplate,
|
||||
} from "../";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigFile } from "../util/paths";
|
||||
|
||||
|
|
@ -22,16 +25,21 @@ function stringify(obj: any, indentation?: number): string {
|
|||
}
|
||||
|
||||
export function addModel(
|
||||
model: ModelDescription,
|
||||
model: JSONModelDescription,
|
||||
role?: keyof ExperimentalModelRoles,
|
||||
) {
|
||||
editConfigFile(
|
||||
(config) => {
|
||||
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
|
||||
if (config.models?.some((m) => stringify(m) === stringify(model))) {
|
||||
return config;
|
||||
}
|
||||
if (config.models?.some((m: any) => m?.title === model.title)) {
|
||||
model.title = `${model.title} (1)`;
|
||||
|
||||
const numMatches = config.models?.reduce(
|
||||
(prev, curr) => (curr.title.startsWith(model.title) ? prev + 1 : prev),
|
||||
0,
|
||||
);
|
||||
if (numMatches !== 0) {
|
||||
model.title = `${model.title} (${numMatches})`;
|
||||
}
|
||||
|
||||
config.models.push(model);
|
||||
|
|
@ -50,22 +58,34 @@ export function addModel(
|
|||
return config;
|
||||
},
|
||||
(config) => {
|
||||
if (config.models?.some((m: any) => m?.title === model.title)) {
|
||||
model.title = `${model.title} (1)`;
|
||||
const numMatches = config.models?.reduce(
|
||||
(prev, curr) =>
|
||||
"name" in curr && curr.name.startsWith(model.title) ? prev + 1 : prev,
|
||||
0,
|
||||
);
|
||||
if (numMatches !== 0) {
|
||||
model.title = `${model.title} (${numMatches})`;
|
||||
}
|
||||
|
||||
if (!config.models) {
|
||||
config.models = [];
|
||||
}
|
||||
|
||||
config.models.push({
|
||||
const desc: ModelConfig = {
|
||||
name: model.title,
|
||||
provider: model.provider,
|
||||
model: model.model,
|
||||
apiKey: model.apiKey,
|
||||
apiBase: model.apiBase,
|
||||
defaultCompletionOptions: model.completionOptions,
|
||||
});
|
||||
};
|
||||
if (model.systemMessage) {
|
||||
desc.chatOptions = {
|
||||
baseSystemMessage:
|
||||
DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage,
|
||||
};
|
||||
}
|
||||
config.models.push(desc);
|
||||
return config;
|
||||
},
|
||||
);
|
||||
|
|
@ -94,7 +114,7 @@ export function getModelByRole<T extends keyof ExperimentalModelRoles>(
|
|||
return undefined;
|
||||
}
|
||||
|
||||
const matchingModel = config.models.find(
|
||||
const matchingModel = config.modelsByRole.chat.find(
|
||||
(model) => model.title === roleTitle,
|
||||
);
|
||||
|
||||
|
|
@ -169,3 +189,22 @@ async function showUnsupportedCpuToast(ide: IDE) {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is required because users are only able to define prompt templates as a
|
||||
* string, while internally we also allow prompt templates to be functions
|
||||
* @param templates
|
||||
* @returns
|
||||
*/
|
||||
export function serializePromptTemplates(
|
||||
templates: Record<string, PromptTemplate> | undefined,
|
||||
): Record<string, string> | undefined {
|
||||
if (!templates) return undefined;
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(templates).map(([key, template]) => {
|
||||
const serialized = typeof template === "function" ? "" : template;
|
||||
return [key, serialized];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
97
core/config/workspace/workspaceBlocks.ts
Normal file
97
core/config/workspace/workspaceBlocks.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { BlockType, ConfigYaml } from "@continuedev/config-yaml";
|
||||
import * as YAML from "yaml";
|
||||
import { IDE } from "../..";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
|
||||
const configYaml: ConfigYaml = {
|
||||
name: `New ${blockType.slice(0, -1)}`,
|
||||
version: "0.0.1",
|
||||
schema: "v1",
|
||||
};
|
||||
switch (blockType) {
|
||||
case "context":
|
||||
configYaml.context = [
|
||||
{
|
||||
provider: "file",
|
||||
},
|
||||
];
|
||||
break;
|
||||
case "models":
|
||||
configYaml.models = [
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-7-sonnet-latest",
|
||||
apiKey: "${{ secrets.ANTHROPIC_API_KEY }}",
|
||||
name: "Claude 3.7 Sonnet",
|
||||
roles: ["chat", "edit"],
|
||||
},
|
||||
];
|
||||
break;
|
||||
case "rules":
|
||||
configYaml.rules = ["Always give concise responses"];
|
||||
break;
|
||||
case "docs":
|
||||
configYaml.docs = [
|
||||
{
|
||||
name: "New docs",
|
||||
startUrl: "https://docs.continue.dev",
|
||||
},
|
||||
];
|
||||
break;
|
||||
case "prompts":
|
||||
configYaml.prompts = [
|
||||
{
|
||||
name: "New prompt",
|
||||
description: "New prompt",
|
||||
prompt:
|
||||
"Please write a thorough suite of unit tests for this code, making sure to cover all relevant edge cases",
|
||||
},
|
||||
];
|
||||
break;
|
||||
case "mcpServers":
|
||||
configYaml.mcpServers = [
|
||||
{
|
||||
name: "New MCP server",
|
||||
command: "npx",
|
||||
args: ["-y", "<your-mcp-server>"],
|
||||
env: {},
|
||||
},
|
||||
];
|
||||
break;
|
||||
}
|
||||
|
||||
return configYaml;
|
||||
}
|
||||
|
||||
export async function createNewWorkspaceBlockFile(
|
||||
ide: IDE,
|
||||
blockType: BlockType,
|
||||
): Promise<void> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
if (workspaceDirs.length === 0) {
|
||||
throw new Error(
|
||||
"No workspace directories found. Make sure you've opened a folder in your IDE.",
|
||||
);
|
||||
}
|
||||
|
||||
const baseDirUri = joinPathsToUri(workspaceDirs[0], `.continue/${blockType}`);
|
||||
|
||||
// Find the first available filename
|
||||
let counter = 0;
|
||||
let fileUri: string;
|
||||
do {
|
||||
const suffix = counter === 0 ? "" : `-${counter}`;
|
||||
fileUri = joinPathsToUri(
|
||||
baseDirUri,
|
||||
`new-${blockType.slice(0, -1)}${suffix}.yaml`,
|
||||
);
|
||||
counter++;
|
||||
} while (await ide.fileExists(fileUri));
|
||||
|
||||
await ide.writeFile(
|
||||
fileUri,
|
||||
YAML.stringify(getContentsForNewBlock(blockType)),
|
||||
);
|
||||
await ide.openFile(fileUri);
|
||||
}
|
||||
|
|
@ -5,32 +5,34 @@ import {
|
|||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
FQSN,
|
||||
isAssistantUnrolledNonNullable,
|
||||
MCPServer,
|
||||
ModelRole,
|
||||
PlatformClient,
|
||||
RegistryClient,
|
||||
Rule,
|
||||
SecretResult,
|
||||
unrollAssistantFromContent,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
|
||||
import {
|
||||
ContinueConfig,
|
||||
ExperimentalMCPOptions,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
} from "../..";
|
||||
import { slashFromCustomCommand } from "../../commands";
|
||||
import { AllRerankers } from "../../context/allRerankers";
|
||||
import { MCPManagerSingleton } from "../../context/mcp";
|
||||
import 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";
|
||||
|
|
@ -38,7 +40,6 @@ import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
|||
import { allTools } from "../../tools";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { getConfigYamlPath } from "../../util/paths";
|
||||
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
|
|
@ -61,6 +62,35 @@ export class LocalPlatformClient implements PlatformClient {
|
|||
}
|
||||
}
|
||||
|
||||
function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
||||
if (typeof rule === "string") {
|
||||
return {
|
||||
rule: rule,
|
||||
source: "rules-block",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
source: "rules-block",
|
||||
rule: rule.rule,
|
||||
if: rule.if,
|
||||
name: rule.name,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function convertYamlMcpToContinueMcp(
|
||||
server: MCPServer,
|
||||
): ExperimentalMCPOptions {
|
||||
return {
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: server.command,
|
||||
args: server.args ?? [],
|
||||
env: server.env,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function loadConfigYaml(
|
||||
rawYaml: string,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
|
|
@ -82,7 +112,6 @@ async function loadConfigYaml(
|
|||
await controlPlaneClient.getAccessToken(),
|
||||
getControlPlaneEnvSync(
|
||||
ideSettings.continueTestEnvironment,
|
||||
ideSettings.enableControlServerBeta,
|
||||
).CONTROL_PLANE_URL,
|
||||
),
|
||||
{
|
||||
|
|
@ -93,7 +122,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 {
|
||||
|
|
@ -111,41 +148,31 @@ async function loadConfigYaml(
|
|||
};
|
||||
}
|
||||
|
||||
async function configYamlToContinueConfig(
|
||||
config: AssistantUnrolled,
|
||||
ide: IDE,
|
||||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
llmLogger: ILLMLogger,
|
||||
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: undefined,
|
||||
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: [],
|
||||
|
|
@ -157,7 +184,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,
|
||||
|
|
@ -165,14 +192,44 @@ async function configYamlToContinueConfig(
|
|||
rerank: null,
|
||||
summarize: null,
|
||||
},
|
||||
data: config.data,
|
||||
rules: [],
|
||||
};
|
||||
|
||||
// Right now, if there are any missing packages in the config, then we will just throw an error
|
||||
if (!isAssistantUnrolledNonNullable(config)) {
|
||||
return {
|
||||
config: continueConfig,
|
||||
errors: [
|
||||
{
|
||||
message: "Found missing blocks in config.yaml",
|
||||
fatal: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
for (const rule of config.rules ?? []) {
|
||||
continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
|
||||
}
|
||||
|
||||
continueConfig.data = config.data;
|
||||
continueConfig.docs = config.docs?.map((doc) => ({
|
||||
title: doc.name,
|
||||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
}));
|
||||
continueConfig.experimental = {
|
||||
modelContextProtocolServers: config.mcpServers?.map(
|
||||
convertYamlMcpToContinueMcp,
|
||||
),
|
||||
};
|
||||
|
||||
// Prompt files -
|
||||
try {
|
||||
const promptFiles = await getAllPromptFiles(ide, undefined, true);
|
||||
|
||||
for (const file of promptFiles) {
|
||||
promptFiles.forEach((file) => {
|
||||
try {
|
||||
const slashCommand = slashCommandFromPromptFileV1(
|
||||
file.path,
|
||||
|
|
@ -187,7 +244,7 @@ async function configYamlToContinueConfig(
|
|||
message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
|
|
@ -208,9 +265,9 @@ async function configYamlToContinueConfig(
|
|||
});
|
||||
|
||||
// Models
|
||||
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
|
||||
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
|
||||
for (const model of config.models ?? []) {
|
||||
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
|
||||
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
|
||||
try {
|
||||
const llms = await llmsFromModelConfig({
|
||||
model,
|
||||
|
|
@ -222,10 +279,6 @@ async function configYamlToContinueConfig(
|
|||
config: continueConfig,
|
||||
});
|
||||
|
||||
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
|
||||
continueConfig.models.push(...llms);
|
||||
}
|
||||
|
||||
if (model.roles?.includes("chat")) {
|
||||
continueConfig.modelsByRole.chat.push(...llms);
|
||||
}
|
||||
|
|
@ -247,59 +300,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({
|
||||
|
|
@ -323,7 +342,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) {
|
||||
|
|
@ -338,14 +357,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",
|
||||
);
|
||||
}
|
||||
|
|
@ -375,7 +395,10 @@ async function configYamlToContinueConfig(
|
|||
}
|
||||
return undefined;
|
||||
}
|
||||
const instance: IContextProvider = new cls(context.params ?? {});
|
||||
const instance: IContextProvider = new cls({
|
||||
name: context.name,
|
||||
...context.params,
|
||||
});
|
||||
return instance;
|
||||
})
|
||||
.filter((p) => !!p) ?? []) as IContextProvider[];
|
||||
|
|
@ -408,19 +431,29 @@ async function configYamlToContinueConfig(
|
|||
return { config: continueConfig, errors: localErrors };
|
||||
}
|
||||
|
||||
export async function loadContinueConfigFromYaml(
|
||||
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>> {
|
||||
export async function loadContinueConfigFromYaml({
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
configYamlPath,
|
||||
orgScopeId,
|
||||
}: {
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
configYamlPath: string | undefined;
|
||||
orgScopeId: string | null;
|
||||
}): Promise<ConfigResult<ContinueConfig>> {
|
||||
const rawYaml =
|
||||
overrideConfigYaml === undefined
|
||||
? fs.readFileSync(
|
||||
|
|
@ -446,32 +479,16 @@ export async function loadContinueConfigFromYaml(
|
|||
}
|
||||
|
||||
const { config: continueConfig, errors: localErrors } =
|
||||
await configYamlToContinueConfig(
|
||||
configYamlResult.config,
|
||||
await configYamlToContinueConfig({
|
||||
config: configYamlResult.config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
platformConfigMetadata,
|
||||
);
|
||||
|
||||
try {
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
if (systemPromptDotFile) {
|
||||
if (continueConfig.systemMessage) {
|
||||
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
|
||||
} else {
|
||||
continueConfig.systemMessage = systemPromptDotFile;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`,
|
||||
allowFreeTrial: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Apply shared config
|
||||
// TODO: override several of these values with user/org shared config
|
||||
|
|
|
|||
|
|
@ -63,9 +63,8 @@ async function modelConfigToBaseLLM({
|
|||
logger: llmLogger,
|
||||
uniqueId,
|
||||
title: model.name,
|
||||
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"),
|
||||
|
|
|
|||
|
|
@ -1,21 +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 SiliconFlow from "../llm/llms/SiliconFlow";
|
||||
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,
|
||||
siliconflow: SiliconFlow,
|
||||
};
|
||||
|
|
@ -24,6 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider {
|
|||
this.options.title || ContinueProxyContextProvider.description.title,
|
||||
displayTitle:
|
||||
this.options.displayTitle ||
|
||||
this.options.name ||
|
||||
ContinueProxyContextProvider.description.displayTitle,
|
||||
description:
|
||||
this.options.description ||
|
||||
|
|
|
|||
|
|
@ -16,18 +16,20 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
|
||||
override get description(): ContextProviderDescription {
|
||||
return {
|
||||
title: this.options.title || "http",
|
||||
displayTitle: this.options.displayTitle || "HTTP",
|
||||
title: this.options.title || HttpContextProvider.description.title,
|
||||
displayTitle:
|
||||
this.options.displayTitle ||
|
||||
this.options.name ||
|
||||
HttpContextProvider.description.displayTitle,
|
||||
description:
|
||||
this.options.description ||
|
||||
"Retrieve a context item from a custom server",
|
||||
type: "normal",
|
||||
this.options.description || HttpContextProvider.description.description,
|
||||
type: HttpContextProvider.description.type,
|
||||
renderInlineAs:
|
||||
this.options.renderInlineAs ||
|
||||
HttpContextProvider.description.renderInlineAs,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -45,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: [],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -21,16 +21,6 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
|
|||
const WORKOS_ENV_ID_PRODUCTION = "continue";
|
||||
const WORKOS_ENV_ID_STAGING = "continue-staging";
|
||||
|
||||
export const PRODUCTION_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL:
|
||||
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
|
||||
CONTROL_PLANE_URL:
|
||||
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
|
||||
AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION,
|
||||
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
|
||||
APP_URL: "https://app.continue.dev/",
|
||||
};
|
||||
|
||||
const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/",
|
||||
CONTROL_PLANE_URL: "https://api.continue.dev/",
|
||||
|
|
@ -71,15 +61,11 @@ export async function getControlPlaneEnv(
|
|||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<ControlPlaneEnv> {
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
return getControlPlaneEnvSync(
|
||||
ideSettings.continueTestEnvironment,
|
||||
ideSettings.enableControlServerBeta,
|
||||
);
|
||||
return getControlPlaneEnvSync(ideSettings.continueTestEnvironment);
|
||||
}
|
||||
|
||||
export function getControlPlaneEnvSync(
|
||||
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
|
||||
enableControlServerBeta: IdeSettings["enableControlServerBeta"],
|
||||
): ControlPlaneEnv {
|
||||
// Note .local overrides .staging
|
||||
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
|
||||
|
|
@ -90,10 +76,6 @@ export function getControlPlaneEnvSync(
|
|||
return STAGING_ENV;
|
||||
}
|
||||
|
||||
if (enableControlServerBeta === true) {
|
||||
return PRODUCTION_ENV;
|
||||
}
|
||||
|
||||
const env =
|
||||
ideTestEnvironment === "production"
|
||||
? "hub"
|
||||
|
|
@ -109,17 +91,12 @@ export function getControlPlaneEnvSync(
|
|||
? STAGING_ENV
|
||||
: env === "test"
|
||||
? TEST_ENV
|
||||
: env === "hub"
|
||||
? PRODUCTION_HUB_ENV
|
||||
: PRODUCTION_ENV;
|
||||
: PRODUCTION_HUB_ENV;
|
||||
}
|
||||
|
||||
export async function useHub(
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
): Promise<boolean> {
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
if (ideSettings.enableControlServerBeta) {
|
||||
return false;
|
||||
}
|
||||
return ideSettings.continueTestEnvironment !== "none";
|
||||
}
|
||||
|
|
|
|||
767
core/core.ts
767
core/core.ts
|
|
@ -4,12 +4,7 @@ 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 { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
|
||||
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";
|
||||
|
|
@ -31,11 +26,20 @@ import { GlobalContext } from "./util/GlobalContext";
|
|||
import historyManager from "./util/history";
|
||||
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
|
||||
import { Telemetry } from "./util/posthog";
|
||||
import {
|
||||
isProcessBackgrounded,
|
||||
markProcessAsBackgrounded,
|
||||
} from "./util/processTerminalBackgroundStates";
|
||||
import { getSymbolsForManyFiles } from "./util/treeSitter";
|
||||
import { TTS } from "./util/tts";
|
||||
|
||||
import {
|
||||
ContextItemWithId,
|
||||
DiffLine,
|
||||
IdeSettings,
|
||||
ModelDescription,
|
||||
RangeInFile,
|
||||
type ContextItem,
|
||||
type ContextItemId,
|
||||
type IDE,
|
||||
type IndexingProgressUpdate,
|
||||
|
|
@ -43,7 +47,14 @@ import {
|
|||
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
|
||||
import {
|
||||
setupBestConfig,
|
||||
setupLocalConfig,
|
||||
setupQuickstartConfig,
|
||||
} from "./config/onboarding";
|
||||
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
|
||||
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";
|
||||
|
|
@ -51,6 +62,43 @@ 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 { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Failed to load config");
|
||||
}
|
||||
|
||||
const llm = config.selectedModelByRole.chat;
|
||||
|
||||
if (!llm) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
for await (const diffLine of streamDiffLines({
|
||||
highlighted: data.highlighted,
|
||||
prefix: data.prefix,
|
||||
suffix: data.suffix,
|
||||
llm,
|
||||
rules: config.rules,
|
||||
input: data.input,
|
||||
language: data.language,
|
||||
onlyOneInsertion: false,
|
||||
overridePrompt: undefined,
|
||||
})) {
|
||||
if (abortedMessageIds.has(msg.messageId)) {
|
||||
abortedMessageIds.delete(msg.messageId);
|
||||
break;
|
||||
}
|
||||
yield diffLine;
|
||||
}
|
||||
}
|
||||
|
||||
export class Core {
|
||||
configHandler: ConfigHandler;
|
||||
codebaseIndexerPromise: Promise<CodebaseIndexer>;
|
||||
|
|
@ -117,8 +165,7 @@ export class Core {
|
|||
this.messenger,
|
||||
);
|
||||
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.onConnectionsRefreshed = async () => {
|
||||
MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => {
|
||||
await this.configHandler.reloadConfig();
|
||||
};
|
||||
|
||||
|
|
@ -130,8 +177,6 @@ export class Core {
|
|||
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
|
||||
|
|
@ -209,6 +254,11 @@ export class Core {
|
|||
(..._) => Promise.resolve([]),
|
||||
);
|
||||
|
||||
this.registerMessageHandlers(ideSettingsPromise);
|
||||
}
|
||||
|
||||
/* eslint-disable max-lines-per-function */
|
||||
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
|
||||
|
|
@ -219,9 +269,7 @@ export class Core {
|
|||
stack: err.stack,
|
||||
});
|
||||
|
||||
// Again, specifically for jetbrains to prevent duplicate error messages
|
||||
// The same logic can currently be found in the webview protocol
|
||||
// bc streaming errors are handled in the GUI
|
||||
// just to prevent duplicate error messages in jetbrains (same logic in webview protocol)
|
||||
if (
|
||||
["llm/streamChat", "chatDescriber/describe"].includes(
|
||||
message.messageType,
|
||||
|
|
@ -233,7 +281,6 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
// Special
|
||||
on("abort", (msg) => {
|
||||
this.abortedMessageIds.add(msg.messageId);
|
||||
});
|
||||
|
|
@ -262,12 +309,14 @@ export class Core {
|
|||
historyManager.save(msg.data);
|
||||
});
|
||||
|
||||
// Dev data
|
||||
on("history/clear", (msg) => {
|
||||
historyManager.clearAll();
|
||||
});
|
||||
|
||||
on("devdata/log", async (msg) => {
|
||||
void DataLogger.getInstance().logDevData(msg.data);
|
||||
});
|
||||
|
||||
// Edit config
|
||||
on("config/addModel", (msg) => {
|
||||
const model = msg.data.model;
|
||||
addModel(model, msg.data.role);
|
||||
|
|
@ -285,6 +334,11 @@ export class Core {
|
|||
await this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/addLocalWorkspaceBlock", async (msg) => {
|
||||
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
|
||||
await this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/openProfile", async (msg) => {
|
||||
await this.configHandler.openConfigProfile(msg.data.profileId);
|
||||
});
|
||||
|
|
@ -299,7 +353,13 @@ export class Core {
|
|||
});
|
||||
|
||||
on("config/refreshProfiles", async (msg) => {
|
||||
const { selectOrgId, selectProfileId } = msg.data ?? {};
|
||||
await this.configHandler.refreshAll();
|
||||
if (selectOrgId) {
|
||||
await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId);
|
||||
} else if (selectProfileId) {
|
||||
await this.configHandler.setSelectedProfileId(selectProfileId);
|
||||
}
|
||||
});
|
||||
|
||||
on("config/updateSharedConfig", async (msg) => {
|
||||
|
|
@ -328,7 +388,7 @@ export class Core {
|
|||
});
|
||||
|
||||
on("mcp/reloadServer", async (msg) => {
|
||||
mcpManager.refreshConnection(msg.data.id);
|
||||
MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
});
|
||||
// Context providers
|
||||
on("context/addDocs", async (msg) => {
|
||||
|
|
@ -348,7 +408,6 @@ export class Core {
|
|||
if (!config) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const items = await config.contextProviders
|
||||
?.find((provider) => provider.description.title === msg.data.title)
|
||||
?.loadSubmenuItems({
|
||||
|
|
@ -360,94 +419,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;
|
||||
|
|
@ -461,8 +433,6 @@ export class Core {
|
|||
this.configHandler.currentProfile?.profileDescription.id ?? null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
usingContinueForTeams: (await ideSettingsPromise)
|
||||
.enableControlServerBeta,
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -480,13 +450,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,
|
||||
|
|
@ -494,31 +470,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.bind(this));
|
||||
|
||||
// Provide messenger to utils so they can interact with GUI + state
|
||||
TTS.messenger = this.messenger;
|
||||
|
|
@ -529,9 +481,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);
|
||||
});
|
||||
|
||||
|
|
@ -551,93 +507,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.bind(this));
|
||||
|
||||
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.bind(this));
|
||||
|
||||
on("stats/getTokensPerDay", async (msg) => {
|
||||
const rows = await DevDataSqliteDb.getTokensPerDay();
|
||||
|
|
@ -648,7 +524,6 @@ export class Core {
|
|||
return rows;
|
||||
});
|
||||
|
||||
// Codebase indexing
|
||||
on("index/forceReIndex", async ({ data }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config || config.disableIndexing) {
|
||||
|
|
@ -678,65 +553,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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// File changes - TODO - remove remaining logic for these from IDEs where possible
|
||||
on("files/changed", this.handleFilesChanged.bind(this));
|
||||
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);
|
||||
}
|
||||
|
|
@ -785,11 +607,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) => {
|
||||
|
|
@ -804,7 +622,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) => {
|
||||
|
|
@ -813,20 +630,26 @@ export class Core {
|
|||
on("docs/getDetails", async (msg) => {
|
||||
return await this.docsService.getDetails(msg.data.startUrl);
|
||||
});
|
||||
//
|
||||
|
||||
on("didChangeSelectedProfile", async (msg) => {
|
||||
await this.configHandler.setSelectedProfileId(msg.data.id);
|
||||
if (msg.data.id) {
|
||||
await this.configHandler.setSelectedProfileId(msg.data.id);
|
||||
}
|
||||
});
|
||||
|
||||
on("didChangeSelectedOrg", async (msg) => {
|
||||
await this.configHandler.setSelectedOrgId(
|
||||
msg.data.id,
|
||||
msg.data.profileId,
|
||||
);
|
||||
if (msg.data.id) {
|
||||
await this.configHandler.setSelectedOrgId(
|
||||
msg.data.id,
|
||||
msg.data.profileId || undefined,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
on("didChangeControlPlaneSessionInfo", async (msg) => {
|
||||
this.messenger.send("sessionUpdate", {
|
||||
sessionInfo: msg.data.sessionInfo,
|
||||
});
|
||||
await this.configHandler.updateControlPlaneSessionInfo(
|
||||
msg.data.sessionInfo,
|
||||
);
|
||||
|
|
@ -853,44 +676,352 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
on(
|
||||
"tools/call",
|
||||
async ({ data: { toolCall, selectedModelTitle }, messageId }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
|
||||
const tool = config.tools.find(
|
||||
(t) => t.function.name === toolCall.function.name,
|
||||
);
|
||||
const tool = config.tools.find(
|
||||
(t) => t.function.name === toolCall.function.name,
|
||||
);
|
||||
|
||||
if (!tool) {
|
||||
throw new Error(`Tool ${toolCall.function.name} not found`);
|
||||
}
|
||||
if (!tool) {
|
||||
throw new Error(`Tool ${toolCall.function.name} not found`);
|
||||
}
|
||||
|
||||
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
|
||||
if (!config.selectedModelByRole.chat) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
const contextItems = await callTool(
|
||||
tool,
|
||||
JSON.parse(toolCall.function.arguments || "{}"),
|
||||
{
|
||||
ide: this.ide,
|
||||
llm,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
// Define a callback for streaming output updates
|
||||
const onPartialOutput = (params: {
|
||||
toolCallId: string;
|
||||
contextItems: ContextItem[];
|
||||
}) => {
|
||||
this.messenger.send("toolCallPartialOutput", params);
|
||||
};
|
||||
|
||||
const contextItems = await callTool(
|
||||
tool,
|
||||
},
|
||||
JSON.parse(toolCall.function.arguments || "{}"),
|
||||
{
|
||||
ide: this.ide,
|
||||
llm: config.selectedModelByRole.chat,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
tool,
|
||||
toolCallId: toolCall.id,
|
||||
onPartialOutput,
|
||||
},
|
||||
);
|
||||
|
||||
if (tool.faviconUrl) {
|
||||
contextItems.forEach((item) => {
|
||||
item.icon = tool.faviconUrl;
|
||||
});
|
||||
}
|
||||
|
||||
return { contextItems };
|
||||
},
|
||||
);
|
||||
|
||||
on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => {
|
||||
return this.isItemTooBig(item);
|
||||
});
|
||||
|
||||
// Process state handlers
|
||||
on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
|
||||
markProcessAsBackgrounded(toolCallId);
|
||||
});
|
||||
|
||||
on(
|
||||
"process/isBackgrounded",
|
||||
async ({ data: { toolCallId }, messageId }) => {
|
||||
const isBackgrounded = isProcessBackgrounded(toolCallId);
|
||||
return isBackgrounded; // Return true to indicate the message was handled successfully
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private async isItemTooBig(item: ContextItemWithId) {
|
||||
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),
|
||||
);
|
||||
|
||||
if (tool.faviconUrl) {
|
||||
contextItems.forEach((item) => {
|
||||
item.icon = tool.faviconUrl;
|
||||
});
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
return { contextItems };
|
||||
});
|
||||
} 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(
|
||||
|
|
|
|||
|
|
@ -2,10 +2,9 @@ import { DiffLine, ILLM } from "../..";
|
|||
import { generateLines } from "../../diff/util";
|
||||
import { supportedLanguages } from "../../util/treeSitter";
|
||||
import { getUriFileExtension } from "../../util/uri";
|
||||
|
||||
import { deterministicApplyLazyEdit } from "./deterministic";
|
||||
import { streamLazyApply } from "./streamLazyApply";
|
||||
import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply";
|
||||
import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply";
|
||||
|
||||
function canUseInstantApply(filename: string) {
|
||||
const fileExtension = getUriFileExtension(filename);
|
||||
|
|
@ -14,36 +13,44 @@ function canUseInstantApply(filename: string) {
|
|||
|
||||
export async function applyCodeBlock(
|
||||
oldFile: string,
|
||||
newFile: string,
|
||||
newLazyFile: string,
|
||||
filename: string,
|
||||
llm: ILLM,
|
||||
fastLlm: ILLM,
|
||||
): Promise<[boolean, AsyncGenerator<DiffLine>]> {
|
||||
// This was buggy, removed for now, maybe forever
|
||||
if (false && canUseInstantApply(filename)) {
|
||||
const diffLines = await deterministicApplyLazyEdit(
|
||||
): Promise<{
|
||||
isInstantApply: boolean;
|
||||
diffLinesGenerator: AsyncGenerator<DiffLine>;
|
||||
}> {
|
||||
if (canUseInstantApply(filename)) {
|
||||
const diffLines = await deterministicApplyLazyEdit({
|
||||
oldFile,
|
||||
newFile,
|
||||
newLazyFile,
|
||||
filename,
|
||||
);
|
||||
onlyFullFileRewrite: true,
|
||||
});
|
||||
|
||||
// Fall back to LLM method if we couldn't apply deterministically
|
||||
if (diffLines !== undefined) {
|
||||
const diffGenerator = generateLines(diffLines!);
|
||||
return [true, diffGenerator];
|
||||
return {
|
||||
isInstantApply: true,
|
||||
diffLinesGenerator: generateLines(diffLines!),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// If the code block is a diff
|
||||
if (isUnifiedDiffFormat(newFile)) {
|
||||
if (isUnifiedDiffFormat(newLazyFile)) {
|
||||
try {
|
||||
const diffLines = applyUnifiedDiff(oldFile, newFile);
|
||||
const diffGenerator = generateLines(diffLines!);
|
||||
return [true, diffGenerator];
|
||||
const diffLines = applyUnifiedDiff(oldFile, newLazyFile);
|
||||
return {
|
||||
isInstantApply: true,
|
||||
diffLinesGenerator: generateLines(diffLines!),
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Failed to apply unified diff", e);
|
||||
}
|
||||
}
|
||||
|
||||
return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)];
|
||||
return {
|
||||
isInstantApply: false,
|
||||
diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,11 +21,11 @@ async function collectDiffs(
|
|||
): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> {
|
||||
const ourDiffs: DiffLine[] = [];
|
||||
|
||||
for (const diffLine of (await deterministicApplyLazyEdit(
|
||||
for (const diffLine of (await deterministicApplyLazyEdit({
|
||||
oldFile,
|
||||
newFile,
|
||||
newLazyFile: newFile,
|
||||
filename,
|
||||
)) ?? []) {
|
||||
})) ?? []) {
|
||||
ourDiffs.push(diffLine);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,11 @@ type AstReplacements = Array<{
|
|||
replacementNodes: Parser.SyntaxNode[];
|
||||
}>;
|
||||
|
||||
const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/;
|
||||
export function isLazyText(text: string): boolean {
|
||||
return LAZY_COMMENT_REGEX.test(text);
|
||||
}
|
||||
|
||||
function reconstructNewFile(
|
||||
oldFile: string,
|
||||
newFile: string,
|
||||
|
|
@ -121,11 +126,23 @@ function nodeSurroundedInLazyBlocks(
|
|||
}
|
||||
|
||||
// TODO: If we don't have high confidence, return undefined to fall back to slower methods
|
||||
export async function deterministicApplyLazyEdit(
|
||||
oldFile: string,
|
||||
newLazyFile: string,
|
||||
filename: string,
|
||||
): Promise<DiffLine[] | undefined> {
|
||||
export async function deterministicApplyLazyEdit({
|
||||
oldFile,
|
||||
newLazyFile,
|
||||
filename,
|
||||
/**
|
||||
* Using this as a flag to slowly reintroduce lazy applies.
|
||||
* With this set, we will only attempt to deterministically apply
|
||||
* when there are no lazy blocks and then just replace the whole file,
|
||||
* and otherwise never use instant apply
|
||||
*/
|
||||
onlyFullFileRewrite = false,
|
||||
}: {
|
||||
oldFile: string;
|
||||
newLazyFile: string;
|
||||
filename: string;
|
||||
onlyFullFileRewrite?: boolean;
|
||||
}): Promise<DiffLine[] | undefined> {
|
||||
const parser = await getParserForFile(filename);
|
||||
if (!parser) {
|
||||
return undefined;
|
||||
|
|
@ -135,6 +152,20 @@ export async function deterministicApplyLazyEdit(
|
|||
let newTree = parser.parse(newLazyFile);
|
||||
let reconstructedNewFile: string | undefined = undefined;
|
||||
|
||||
if (onlyFullFileRewrite) {
|
||||
if (!isLazyText(newTree.rootNode.text)) {
|
||||
const diff = myersDiff(oldFile, newLazyFile);
|
||||
|
||||
if (shouldRejectDiff(diff)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return diff;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// If there is no lazy block anywhere, we add our own to the outsides
|
||||
// so that large chunks of the file don't get removed
|
||||
if (!findInAst(newTree.rootNode, isLazyBlock)) {
|
||||
|
|
@ -198,11 +229,6 @@ export async function deterministicApplyLazyEdit(
|
|||
return diff;
|
||||
}
|
||||
|
||||
const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/;
|
||||
export function isLazyLine(text: string): boolean {
|
||||
return LAZY_COMMENT_REGEX.test(text);
|
||||
}
|
||||
|
||||
function isLazyBlock(node: Parser.SyntaxNode): boolean {
|
||||
// Special case for "{/* ... existing code ... */}"
|
||||
if (
|
||||
|
|
@ -213,7 +239,7 @@ function isLazyBlock(node: Parser.SyntaxNode): boolean {
|
|||
return true;
|
||||
}
|
||||
|
||||
return node.type.includes("comment") && isLazyLine(node.text);
|
||||
return node.type.includes("comment") && isLazyText(node.text);
|
||||
}
|
||||
|
||||
function stringsWithinLevDistThreshold(
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@ export async function* streamLazyApply(
|
|||
filename: string,
|
||||
newCode: string,
|
||||
llm: ILLM,
|
||||
fastLlm: ILLM,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
|
||||
if (!promptFactory) {
|
||||
|
|
@ -39,7 +38,7 @@ export async function* streamLazyApply(
|
|||
oldCode,
|
||||
linesBefore,
|
||||
linesAfter,
|
||||
fastLlm,
|
||||
llm,
|
||||
)) {
|
||||
yield line;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,11 @@
|
|||
import { ChatMessage, DiffLine, ILLM, Prediction } from "../";
|
||||
import {
|
||||
ChatMessage,
|
||||
DiffLine,
|
||||
ILLM,
|
||||
Prediction,
|
||||
RuleWithSource,
|
||||
UserChatMessage,
|
||||
} from "../";
|
||||
import {
|
||||
filterCodeBlockLines,
|
||||
filterEnglishLinesAtEnd,
|
||||
|
|
@ -10,7 +17,9 @@ import {
|
|||
} from "../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamDiff } from "../diff/streamDiff";
|
||||
import { streamLines } from "../diff/util";
|
||||
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
|
||||
import { gptEditPrompt } from "../llm/templates/edit";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
|
||||
function constructPrompt(
|
||||
|
|
@ -47,16 +56,27 @@ function modelIsInept(model: string): boolean {
|
|||
return !(model.includes("gpt") || model.includes("claude"));
|
||||
}
|
||||
|
||||
export async function* streamDiffLines(
|
||||
prefix: string,
|
||||
highlighted: string,
|
||||
suffix: string,
|
||||
llm: ILLM,
|
||||
input: string,
|
||||
language: string | undefined,
|
||||
onlyOneInsertion: boolean,
|
||||
overridePrompt: ChatMessage[] | undefined,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
export async function* streamDiffLines({
|
||||
prefix,
|
||||
highlighted,
|
||||
suffix,
|
||||
llm,
|
||||
input,
|
||||
language,
|
||||
onlyOneInsertion,
|
||||
overridePrompt,
|
||||
rules,
|
||||
}: {
|
||||
prefix: string;
|
||||
highlighted: string;
|
||||
suffix: string;
|
||||
llm: ILLM;
|
||||
input: string;
|
||||
language: string | undefined;
|
||||
onlyOneInsertion: boolean;
|
||||
overridePrompt: ChatMessage[] | undefined;
|
||||
rules: RuleWithSource[];
|
||||
}): AsyncGenerator<DiffLine> {
|
||||
void Telemetry.capture(
|
||||
"inlineEdit",
|
||||
{
|
||||
|
|
@ -78,9 +98,54 @@ export async function* streamDiffLines(
|
|||
oldLines = [];
|
||||
}
|
||||
|
||||
const prompt =
|
||||
let prompt =
|
||||
overridePrompt ??
|
||||
constructPrompt(prefix, highlighted, suffix, llm, input, language);
|
||||
|
||||
// Rules will be included with edit prompt
|
||||
// If any rules are present this will result in using chat instead of legacy completion
|
||||
const lastUserMessage: UserChatMessage | undefined =
|
||||
typeof prompt === "string"
|
||||
? {
|
||||
role: "user",
|
||||
content: prompt,
|
||||
}
|
||||
: (findLast(prompt, (msg) => msg.role === "user") as
|
||||
| UserChatMessage
|
||||
| undefined);
|
||||
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
currentModel: llm.model,
|
||||
rules,
|
||||
userMessage: lastUserMessage,
|
||||
baseSystemMessage: undefined,
|
||||
});
|
||||
|
||||
if (systemMessage) {
|
||||
if (typeof prompt === "string") {
|
||||
prompt = [
|
||||
{
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: prompt,
|
||||
},
|
||||
];
|
||||
} else {
|
||||
const curSysMsg = prompt.find((msg) => msg.role === "system");
|
||||
if (curSysMsg) {
|
||||
curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content;
|
||||
} else {
|
||||
prompt.unshift({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const inept = modelIsInept(llm.model);
|
||||
|
||||
const prediction: Prediction = {
|
||||
|
|
|
|||
130
core/index.d.ts
vendored
130
core/index.d.ts
vendored
|
|
@ -1,5 +1,6 @@
|
|||
import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml";
|
||||
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { LLMConfigurationStatuses } from "./llm/constants";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
||||
declare global {
|
||||
|
|
@ -76,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;
|
||||
llmLogger?: ILLMLogger;
|
||||
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,
|
||||
|
|
@ -162,6 +143,8 @@ export interface ILLM extends LLMOptions {
|
|||
otherData: Record<string, string>,
|
||||
canPutWordsInModelsMouth?: boolean,
|
||||
): string | ChatMessage[];
|
||||
|
||||
getConfigurationStatus(): LLMConfigurationStatuses;
|
||||
}
|
||||
|
||||
export interface ModelInstaller {
|
||||
|
|
@ -412,6 +395,7 @@ export interface ContextItem {
|
|||
icon?: string;
|
||||
uri?: ContextItemUri;
|
||||
hidden?: boolean;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export interface ContextItemWithId extends ContextItem {
|
||||
|
|
@ -576,7 +560,7 @@ export interface LLMOptions {
|
|||
|
||||
title?: string;
|
||||
uniqueId?: string;
|
||||
systemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
contextLength?: number;
|
||||
maxStopWords?: number;
|
||||
completionOptions?: CompletionOptions;
|
||||
|
|
@ -586,7 +570,6 @@ export interface LLMOptions {
|
|||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
rules?: Rule[];
|
||||
apiKey?: string;
|
||||
|
||||
// continueProperties
|
||||
|
|
@ -717,7 +700,6 @@ export interface IdeSettings {
|
|||
remoteConfigServerUrl: string | undefined;
|
||||
remoteConfigSyncPeriod: number;
|
||||
userToken: string;
|
||||
enableControlServerBeta: boolean;
|
||||
continueTestEnvironment: "none" | "production" | "staging" | "local";
|
||||
pauseCodebaseIndexOnStart: boolean;
|
||||
}
|
||||
|
|
@ -983,6 +965,8 @@ export interface ToolExtras {
|
|||
llm: ILLM;
|
||||
fetch: FetchFunction;
|
||||
tool: Tool;
|
||||
toolCallId?: string;
|
||||
onPartialOutput?: (params: { toolCallId: string, contextItems: ContextItem[] }) => void;
|
||||
}
|
||||
|
||||
export interface Tool {
|
||||
|
|
@ -1044,9 +1028,8 @@ export interface ModelDescription {
|
|||
model: string;
|
||||
apiKey?: string;
|
||||
|
||||
// continueProperties
|
||||
apiKeyLocation?: string;
|
||||
apiBase?: string;
|
||||
apiKeyLocation?: string;
|
||||
orgScopeId?: string | null;
|
||||
|
||||
onPremProxyUrl?: string | null;
|
||||
|
|
@ -1055,15 +1038,16 @@ export interface ModelDescription {
|
|||
maxStopWords?: number;
|
||||
template?: TemplateType;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
systemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: { [key: string]: string };
|
||||
cacheBehavior?: CacheBehavior;
|
||||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
configurationStatus?: LLMConfigurationStatuses;
|
||||
}
|
||||
|
||||
export interface EmbedOptions {
|
||||
export interface JSONEmbedOptions {
|
||||
apiBase?: string;
|
||||
apiKey?: string;
|
||||
model?: string;
|
||||
|
|
@ -1084,7 +1068,7 @@ export interface EmbedOptions {
|
|||
projectId?: string;
|
||||
}
|
||||
|
||||
export interface EmbeddingsProviderDescription extends EmbedOptions {
|
||||
export interface EmbeddingsProviderDescription extends JSONEmbedOptions {
|
||||
provider: string;
|
||||
}
|
||||
|
||||
|
|
@ -1308,11 +1292,39 @@ export interface AnalyticsConfig {
|
|||
clientKey?: string;
|
||||
}
|
||||
|
||||
export interface JSONModelDescription {
|
||||
title: string;
|
||||
provider: string;
|
||||
model: string;
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
|
||||
contextLength?: number;
|
||||
maxStopWords?: number;
|
||||
template?: TemplateType;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
systemMessage?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
cacheBehavior?: CacheBehavior;
|
||||
|
||||
region?: string;
|
||||
profile?: string;
|
||||
modelArn?: string;
|
||||
apiType?: "openai" | "azure";
|
||||
apiVersion?: string;
|
||||
deployment?: string;
|
||||
projectId?: string;
|
||||
accountId?: string;
|
||||
aiGatewaySlug?: string;
|
||||
useLegacyCompletionsEndpoint?: boolean;
|
||||
deploymentId?: string;
|
||||
}
|
||||
|
||||
// config.json
|
||||
export interface SerializedContinueConfig {
|
||||
env?: string[];
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
models: JSONModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
|
|
@ -1323,7 +1335,7 @@ export interface SerializedContinueConfig {
|
|||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: EmbeddingsProviderDescription;
|
||||
tabAutocompleteModel?: ModelDescription | ModelDescription[];
|
||||
tabAutocompleteModel?: JSONModelDescription | JSONModelDescription[];
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
ui?: ContinueUIConfig;
|
||||
reranker?: RerankerDescription;
|
||||
|
|
@ -1343,11 +1355,11 @@ export type ContinueRcJson = Partial<SerializedContinueConfig> & {
|
|||
export interface Config {
|
||||
/** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://docs.continue.dev/telemetry */
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
/** Each entry in this array will originally be a ModelDescription, the same object from your config.json, but you may add CustomLLMs.
|
||||
/** Each entry in this array will originally be a JSONModelDescription, the same object from your config.json, but you may add CustomLLMs.
|
||||
* A CustomLLM requires you only to define an AsyncGenerator that calls the LLM and yields string updates. You can choose to define either `streamCompletion` or `streamChat` (or both).
|
||||
* Continue will do the rest of the work to construct prompt templates, handle context items, prune context, etc.
|
||||
*/
|
||||
models: (CustomLLM | ModelDescription)[];
|
||||
models: (CustomLLM | JSONModelDescription)[];
|
||||
/** A system message to be followed by all of your models */
|
||||
systemMessage?: string;
|
||||
/** The default completion options for all models */
|
||||
|
|
@ -1371,8 +1383,8 @@ export interface Config {
|
|||
/** The model that Continue will use for tab autocompletions. */
|
||||
tabAutocompleteModel?:
|
||||
| CustomLLM
|
||||
| ModelDescription
|
||||
| (CustomLLM | ModelDescription)[];
|
||||
| JSONModelDescription
|
||||
| (CustomLLM | JSONModelDescription)[];
|
||||
/** Options for tab autocomplete */
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
/** UI styles customization */
|
||||
|
|
@ -1389,8 +1401,7 @@ export interface Config {
|
|||
// in the actual Continue source code
|
||||
export interface ContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ILLM[];
|
||||
systemMessage?: string;
|
||||
// systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
slashCommands: SlashCommand[];
|
||||
|
|
@ -1405,7 +1416,7 @@ export interface ContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: Rule[];
|
||||
rules: RuleWithSource[];
|
||||
modelsByRole: Record<ModelRole, ILLM[]>;
|
||||
selectedModelByRole: Record<ModelRole, ILLM | null>;
|
||||
data?: DataDestination[];
|
||||
|
|
@ -1413,8 +1424,7 @@ export interface ContinueConfig {
|
|||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
// systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
slashCommands: SlashCommandDescription[];
|
||||
|
|
@ -1428,7 +1438,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: Rule[];
|
||||
rules: RuleWithSource[];
|
||||
usePlatform: boolean;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
modelsByRole: Record<ModelRole, ModelDescription[]>;
|
||||
|
|
@ -1475,4 +1485,20 @@ export type PackageDocsResult = {
|
|||
export interface TerminalOptions {
|
||||
reuseTerminal?: boolean;
|
||||
terminalName?: string;
|
||||
waitForCompletion?: boolean;
|
||||
}
|
||||
|
||||
export interface RuleWithSource {
|
||||
name?: string;
|
||||
slug?: string;
|
||||
source:
|
||||
| "default"
|
||||
| "model-chat-options"
|
||||
| "rules-block"
|
||||
| "json-systemMessage"
|
||||
| ".continuerules";
|
||||
if?: string;
|
||||
rule: string;
|
||||
description?: string;
|
||||
ruleFile?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -39,7 +39,6 @@
|
|||
// const ideSettingsPromise = Promise.resolve({
|
||||
// remoteConfigSyncPeriod: 60,
|
||||
// userToken: "",
|
||||
// enableControlServerBeta: false,
|
||||
// continueTestEnvironment: "none" as const,
|
||||
// pauseCodebaseIndexOnStart: false,
|
||||
// ideSettings: {} as any,
|
||||
|
|
|
|||
|
|
@ -64,6 +64,48 @@ export type AddParams = {
|
|||
favicon?: string;
|
||||
};
|
||||
|
||||
const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
newFailedDocs.push(siteIndexingConfig);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
||||
const removeFromFailedGlobalContext = (
|
||||
siteIndexingConfig: SiteIndexingConfig,
|
||||
) => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
||||
const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
return failedDocs.find((d) =>
|
||||
siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
};
|
||||
|
||||
const siteIndexingConfigsAreEqual = (
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
) => {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.faviconUrl === config2.faviconUrl &&
|
||||
config1.title === config2.title &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
);
|
||||
};
|
||||
|
||||
/*
|
||||
General process:
|
||||
- On config update:
|
||||
|
|
@ -433,12 +475,7 @@ export default class DocsService {
|
|||
|
||||
// If not force-reindexing and has failed with same config, don't reattempt
|
||||
if (!forceReindex) {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const hasFailed = failedDocs.find((d) =>
|
||||
this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
if (hasFailed) {
|
||||
if (hasIndexingFailed(siteIndexingConfig)) {
|
||||
console.log(
|
||||
`Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`,
|
||||
);
|
||||
|
|
@ -473,25 +510,6 @@ export default class DocsService {
|
|||
return;
|
||||
}
|
||||
|
||||
const markFailedInGlobalContext = () => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
newFailedDocs.push(siteIndexingConfig);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
||||
const removeFromFailedGlobalContext = () => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !this.siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
||||
try {
|
||||
this.docsIndexingQueue.add(startUrl);
|
||||
|
||||
|
|
@ -630,7 +648,7 @@ export default class DocsService {
|
|||
});
|
||||
|
||||
// void this.ide.showToast("info", `Failed to index ${startUrl}`);
|
||||
markFailedInGlobalContext();
|
||||
markFailedInGlobalContext(siteIndexingConfig);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -690,7 +708,7 @@ export default class DocsService {
|
|||
providers: ["docs"],
|
||||
});
|
||||
|
||||
removeFromFailedGlobalContext();
|
||||
removeFromFailedGlobalContext(siteIndexingConfig);
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`Error indexing docs at: ${siteIndexingConfig.startUrl}`,
|
||||
|
|
@ -711,7 +729,7 @@ export default class DocsService {
|
|||
status: "failed",
|
||||
progress: 1,
|
||||
});
|
||||
markFailedInGlobalContext();
|
||||
markFailedInGlobalContext(siteIndexingConfig);
|
||||
} finally {
|
||||
this.docsIndexingQueue.delete(startUrl);
|
||||
}
|
||||
|
|
@ -973,10 +991,7 @@ export default class DocsService {
|
|||
(d) => d.startUrl === doc.startUrl,
|
||||
);
|
||||
|
||||
if (
|
||||
oldConfigDoc &&
|
||||
!this.siteIndexingConfigsAreEqual(oldConfigDoc, doc)
|
||||
) {
|
||||
if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
|
||||
changedDocs.push(doc);
|
||||
} else {
|
||||
if (forceReindex) {
|
||||
|
|
@ -1163,24 +1178,11 @@ export default class DocsService {
|
|||
);
|
||||
}
|
||||
|
||||
private siteIndexingConfigsAreEqual(
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
) {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.faviconUrl === config2.faviconUrl &&
|
||||
config1.title === config2.title &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
);
|
||||
}
|
||||
|
||||
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
|
||||
// Handles the case where a user has manually added the doc to config.json
|
||||
// so it already exists in the file
|
||||
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
|
||||
this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
|
||||
siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
|
||||
);
|
||||
|
||||
if (!doesEquivalentDocExist) {
|
||||
|
|
|
|||
|
|
@ -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,24 +1,60 @@
|
|||
import { ChatHistoryItem, ChatMessage, MessagePart } from "../";
|
||||
import {
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
RuleWithSource,
|
||||
TextMessagePart,
|
||||
UserChatMessage,
|
||||
} from "../";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { normalizeToMessageParts } from "../util/messageContent";
|
||||
import { messageIsEmpty } from "./messages";
|
||||
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
|
||||
|
||||
const DEFAULT_SYSTEM_MESSAGE = `<important_rules>
|
||||
Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'.
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L8";
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
Always include the language and file name in the info string when you write code blocks.
|
||||
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
|
||||
|
||||
When addressing code modification requests, present a concise code snippet that
|
||||
emphasizes only the necessary changes and uses abbreviated placeholders for
|
||||
unmodified sections. For 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,
|
||||
rules: RuleWithSource[],
|
||||
modelName: string,
|
||||
): ChatMessage[] {
|
||||
const filteredHistory = history.filter(
|
||||
(item) => item.message.role !== "system",
|
||||
);
|
||||
const msgs: ChatMessage[] = [];
|
||||
|
||||
msgs.push({
|
||||
role: "system",
|
||||
content: DEFAULT_SYSTEM_MESSAGE,
|
||||
});
|
||||
|
||||
for (let i = 0; i < filteredHistory.length; i++) {
|
||||
const historyItem = filteredHistory[i];
|
||||
|
||||
|
|
@ -26,9 +62,14 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] {
|
|||
// Gather context items for user messages
|
||||
let content = normalizeToMessageParts(historyItem.message);
|
||||
|
||||
const ctxItems = historyItem.contextItems.map((ctxItem) => {
|
||||
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
|
||||
});
|
||||
const ctxItems = historyItem.contextItems
|
||||
.map((ctxItem) => {
|
||||
return {
|
||||
type: "text",
|
||||
text: `${ctxItem.content}\n`,
|
||||
} as TextMessagePart;
|
||||
})
|
||||
.filter((part) => !!part.text.trim());
|
||||
|
||||
content = [...ctxItems, ...content];
|
||||
msgs.push({
|
||||
|
|
@ -46,6 +87,32 @@ export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] {
|
|||
}
|
||||
}
|
||||
|
||||
const userMessage = findLast(msgs, (msg) => msg.role === "user") as
|
||||
| UserChatMessage
|
||||
| undefined;
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
rules,
|
||||
userMessage,
|
||||
currentModel: modelName,
|
||||
});
|
||||
if (systemMessage.trim()) {
|
||||
msgs.unshift({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
|
||||
// We dispatch an empty assistant chat message to the history on submission. Don't send it
|
||||
const lastMessage = msgs.at(-1);
|
||||
if (
|
||||
lastMessage &&
|
||||
lastMessage.role === "assistant" &&
|
||||
messageIsEmpty(lastMessage)
|
||||
) {
|
||||
msgs.pop();
|
||||
}
|
||||
|
||||
// Remove the "id" from all of the messages
|
||||
return msgs.map((msg) => {
|
||||
const { id, ...rest } = msg as any;
|
||||
|
|
|
|||
|
|
@ -1,13 +1,7 @@
|
|||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
|
||||
import {
|
||||
ChatMessage,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
UserChatMessage,
|
||||
} from "../index.js";
|
||||
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
|
||||
|
||||
import { Rule } from "@continuedev/config-yaml";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
AsyncEncoder,
|
||||
|
|
@ -17,8 +11,12 @@ 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";
|
||||
import {
|
||||
addSpaceToAnyEmptyMessages,
|
||||
chatMessageIsEmpty,
|
||||
flattenMessages,
|
||||
messageHasToolCalls,
|
||||
} from "./messages.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
|
|
@ -126,31 +124,6 @@ function countTokens(
|
|||
}
|
||||
}
|
||||
|
||||
function messageHasToolCalls(msg: ChatMessage): boolean {
|
||||
return msg.role === "assistant" && !!msg.toolCalls;
|
||||
}
|
||||
|
||||
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
|
||||
const flattened: ChatMessage[] = [];
|
||||
|
||||
for (let i = 0; i < msgs.length; i++) {
|
||||
const msg = msgs[i];
|
||||
|
||||
if (
|
||||
flattened.length > 0 &&
|
||||
flattened[flattened.length - 1].role === msg.role &&
|
||||
!messageHasToolCalls(msg) &&
|
||||
!messageHasToolCalls(flattened[flattened.length - 1])
|
||||
) {
|
||||
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
|
||||
} else {
|
||||
flattened.push(msg);
|
||||
}
|
||||
}
|
||||
|
||||
return flattened;
|
||||
}
|
||||
|
||||
function countChatMessageTokens(
|
||||
modelName: string,
|
||||
chatMessage: ChatMessage,
|
||||
|
|
@ -248,10 +221,19 @@ function summarize(message: ChatMessage): string {
|
|||
|
||||
function pruneChatHistory(
|
||||
modelName: string,
|
||||
chatHistory: ChatMessage[],
|
||||
msgs: ChatMessage[],
|
||||
contextLength: number,
|
||||
tokensForCompletion: number,
|
||||
): ChatMessage[] {
|
||||
// Move system message to 2nd to last to give it priority
|
||||
const systemMessage = msgs.find((msg) => msg.role === "system");
|
||||
const chatHistory: ChatMessage[] = msgs.filter(
|
||||
(msg) => msg.role !== "system",
|
||||
);
|
||||
if (systemMessage) {
|
||||
chatHistory.splice(-1, 0, systemMessage);
|
||||
}
|
||||
|
||||
let totalTokens =
|
||||
tokensForCompletion +
|
||||
chatHistory.reduce((acc, message) => {
|
||||
|
|
@ -364,147 +346,17 @@ function pruneChatHistory(
|
|||
);
|
||||
totalTokens = contextLength;
|
||||
}
|
||||
return chatHistory;
|
||||
}
|
||||
|
||||
function messageIsEmpty(message: ChatMessage): boolean {
|
||||
if (typeof message.content === "string") {
|
||||
return message.content.trim() === "";
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content.every(
|
||||
(item) => item.type === "text" && item.text?.trim() === "",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] {
|
||||
return messages.map((message) => {
|
||||
if (messageIsEmpty(message)) {
|
||||
message.content = " ";
|
||||
}
|
||||
return message;
|
||||
});
|
||||
}
|
||||
|
||||
function chatMessageIsEmpty(message: ChatMessage): boolean {
|
||||
switch (message.role) {
|
||||
case "system":
|
||||
case "user":
|
||||
return (
|
||||
typeof message.content === "string" && message.content.trim() === ""
|
||||
);
|
||||
case "assistant":
|
||||
return (
|
||||
typeof message.content === "string" &&
|
||||
message.content.trim() === "" &&
|
||||
!message.toolCalls
|
||||
);
|
||||
case "thinking":
|
||||
case "tool":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function addSystemMessage({
|
||||
messages,
|
||||
systemMessage,
|
||||
originalMessages,
|
||||
}: {
|
||||
messages: ChatMessage[];
|
||||
systemMessage: string | undefined;
|
||||
originalMessages: ChatMessage[] | undefined;
|
||||
}): ChatMessage[] {
|
||||
// put system message back if applicable
|
||||
if (
|
||||
!(systemMessage && systemMessage.trim() !== "") &&
|
||||
originalMessages?.[0]?.role !== "system"
|
||||
chatHistory.length > 1 &&
|
||||
chatHistory[chatHistory.length - 2].role === "system"
|
||||
) {
|
||||
return messages;
|
||||
const movedSystemMessage = chatHistory.splice(-2, 1)[0];
|
||||
chatHistory.unshift(movedSystemMessage);
|
||||
}
|
||||
|
||||
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;
|
||||
return chatHistory;
|
||||
}
|
||||
|
||||
function compileChatMessages({
|
||||
|
|
@ -513,64 +365,19 @@ function compileChatMessages({
|
|||
contextLength,
|
||||
maxTokens,
|
||||
supportsImages,
|
||||
prompt,
|
||||
functions,
|
||||
systemMessage,
|
||||
rules,
|
||||
}: {
|
||||
modelName: string;
|
||||
msgs: ChatMessage[] | undefined;
|
||||
msgs: ChatMessage[];
|
||||
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 }))
|
||||
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
|
||||
: [];
|
||||
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
|
||||
|
||||
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
||||
if (prompt) {
|
||||
const promptMsg: ChatMessage = {
|
||||
role: "user",
|
||||
content: prompt,
|
||||
};
|
||||
msgsCopy.push(promptMsg);
|
||||
}
|
||||
|
||||
const lastUserMessage = getLastUserMessage(msgsCopy);
|
||||
|
||||
msgsCopy = addSystemMessage({
|
||||
messages: msgsCopy,
|
||||
systemMessage:
|
||||
systemMessage ??
|
||||
getSystemMessage({
|
||||
userMessage: lastUserMessage,
|
||||
rules,
|
||||
currentModel: modelName,
|
||||
}),
|
||||
originalMessages: msgs,
|
||||
});
|
||||
|
||||
let functionTokens = 0;
|
||||
if (functions) {
|
||||
for (const func of functions) {
|
||||
functionTokens += countTokens(JSON.stringify(func), modelName);
|
||||
}
|
||||
}
|
||||
|
||||
if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) {
|
||||
throw new Error(
|
||||
`maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`,
|
||||
);
|
||||
}
|
||||
|
||||
// If images not supported, convert MessagePart[] to string
|
||||
if (!supportsImages) {
|
||||
for (const msg of msgsCopy) {
|
||||
|
|
@ -585,14 +392,9 @@ function compileChatMessages({
|
|||
modelName,
|
||||
msgsCopy,
|
||||
contextLength,
|
||||
functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY,
|
||||
maxTokens + TOKEN_BUFFER_FOR_SAFETY,
|
||||
);
|
||||
|
||||
if (history.length >= 2 && history[history.length - 2].role === "system") {
|
||||
const movedSystemMessage = history.splice(-2, 1)[0];
|
||||
history.unshift(movedSystemMessage);
|
||||
}
|
||||
|
||||
const flattenedHistory = flattenMessages(history);
|
||||
|
||||
return flattenedHistory;
|
||||
|
|
@ -602,6 +404,7 @@ export {
|
|||
compileChatMessages,
|
||||
countTokens,
|
||||
countTokensAsync,
|
||||
flattenMessages,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
|
|
|
|||
|
|
@ -35,7 +35,6 @@ describe("BaseLLM", () => {
|
|||
const options: LLMOptions = {
|
||||
model: "gpt-3.5-turbo",
|
||||
uniqueId: "testId",
|
||||
systemMessage: "Test System Message",
|
||||
contextLength: 1024,
|
||||
completionOptions: {
|
||||
model: "some-model",
|
||||
|
|
@ -62,7 +61,6 @@ describe("BaseLLM", () => {
|
|||
expect(instance.title).toBeDefined();
|
||||
expect(instance.uniqueId).toBe("testId");
|
||||
expect(instance.model).toBe("gpt-3.5-turbo");
|
||||
expect(instance.systemMessage).toBe("Test System Message");
|
||||
expect(instance.contextLength).toBe(1024);
|
||||
expect(instance.completionOptions.maxTokens).toBe(150);
|
||||
expect(instance.requestOptions).toEqual({});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ModelRole, Rule } from "@continuedev/config-yaml";
|
||||
import { ModelRole } from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import { findLlmInfo } from "@continuedev/llm-info";
|
||||
import {
|
||||
|
|
@ -46,6 +46,7 @@ import {
|
|||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
LLMConfigurationStatuses,
|
||||
} from "./constants.js";
|
||||
import {
|
||||
compileChatMessages,
|
||||
|
|
@ -125,7 +126,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
model: string;
|
||||
|
||||
title?: string;
|
||||
systemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
contextLength: number;
|
||||
maxStopWords?: number | undefined;
|
||||
completionOptions: CompletionOptions;
|
||||
|
|
@ -147,7 +148,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
cacheBehavior?: CacheBehavior;
|
||||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
rules?: Rule[];
|
||||
|
||||
deployment?: string;
|
||||
apiVersion?: string;
|
||||
|
|
@ -193,7 +193,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;
|
||||
|
|
@ -247,7 +247,6 @@ 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;
|
||||
|
|
@ -265,6 +264,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,
|
||||
|
|
@ -281,7 +284,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
private _compileChatMessages(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
functions?: any[],
|
||||
) {
|
||||
let contextLength = this.contextLength;
|
||||
if (
|
||||
|
|
@ -298,10 +300,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
contextLength,
|
||||
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
prompt: undefined,
|
||||
functions,
|
||||
systemMessage: this.systemMessage,
|
||||
rules: this.rules ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -310,45 +308,13 @@ export abstract class BaseLLM implements ILLM {
|
|||
return prompt;
|
||||
}
|
||||
|
||||
// NOTE system message no longer supported here
|
||||
|
||||
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
|
||||
|
||||
const systemMessage = this.systemMessage;
|
||||
if (systemMessage) {
|
||||
msgs.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
||||
return this.templateMessages(msgs);
|
||||
}
|
||||
|
||||
private _compilePromptForLog(
|
||||
prompt: string,
|
||||
completionOptions: CompletionOptions,
|
||||
): string {
|
||||
const completionOptionsLog = JSON.stringify(
|
||||
{
|
||||
contextLength: this.contextLength,
|
||||
...completionOptions,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
|
||||
let requestOptionsLog = "";
|
||||
if (this.requestOptions) {
|
||||
requestOptionsLog = JSON.stringify(this.requestOptions, null, 2);
|
||||
}
|
||||
|
||||
return (
|
||||
"##### Completion options #####\n" +
|
||||
completionOptionsLog +
|
||||
(requestOptionsLog
|
||||
? "\n\n##### Request options #####\n" + requestOptionsLog
|
||||
: "") +
|
||||
"\n\n##### Prompt #####\n" +
|
||||
prompt
|
||||
);
|
||||
}
|
||||
|
||||
private _logEnd(
|
||||
model: string,
|
||||
prompt: string,
|
||||
|
|
|
|||
|
|
@ -30,15 +30,17 @@ class Anthropic extends BaseLLM {
|
|||
description: tool.function.description,
|
||||
input_schema: tool.function.parameters,
|
||||
})),
|
||||
thinking: options.reasoning ? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
} : undefined,
|
||||
thinking: options.reasoning
|
||||
? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
}
|
||||
: undefined,
|
||||
tool_choice: options.toolChoice
|
||||
? {
|
||||
type: "tool",
|
||||
name: options.toolChoice.function.name,
|
||||
}
|
||||
type: "tool",
|
||||
name: options.toolChoice.function.name,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
|
|
@ -70,19 +72,23 @@ class Anthropic extends BaseLLM {
|
|||
} else if (message.role === "thinking" && !message.redactedThinking) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [{
|
||||
type: "thinking",
|
||||
thinking: message.content,
|
||||
signature: message.signature
|
||||
}]
|
||||
content: [
|
||||
{
|
||||
type: "thinking",
|
||||
thinking: message.content,
|
||||
signature: message.signature,
|
||||
},
|
||||
],
|
||||
};
|
||||
} else if (message.role === "thinking" && message.redactedThinking) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [{
|
||||
type: "redacted_thinking",
|
||||
data: message.redactedThinking
|
||||
}]
|
||||
content: [
|
||||
{
|
||||
type: "redacted_thinking",
|
||||
data: message.redactedThinking,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -172,11 +178,12 @@ class Anthropic extends BaseLLM {
|
|||
);
|
||||
}
|
||||
|
||||
const shouldCacheSystemMessage =
|
||||
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const systemMessage: string = stripImages(
|
||||
const systemMessage = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content ?? "",
|
||||
);
|
||||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
|
||||
const msgs = this.convertMessages(messages);
|
||||
const response = await this.fetch(new URL("messages", this.apiBase), {
|
||||
|
|
@ -195,12 +202,12 @@ class Anthropic extends BaseLLM {
|
|||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: this.systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
{
|
||||
type: "text",
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
signal,
|
||||
|
|
@ -240,7 +247,11 @@ class Anthropic extends BaseLLM {
|
|||
// handle redacted thinking
|
||||
if (value.content_block.type === "redacted_thinking") {
|
||||
console.log("redacted thinking", value.content_block.data);
|
||||
yield { role: "thinking", content: "", redactedThinking: value.content_block.data };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: value.content_block.data,
|
||||
};
|
||||
}
|
||||
break;
|
||||
case "content_block_delta":
|
||||
|
|
@ -253,7 +264,11 @@ class Anthropic extends BaseLLM {
|
|||
yield { role: "thinking", content: value.delta.thinking };
|
||||
break;
|
||||
case "signature_delta":
|
||||
yield { role: "thinking", content: "", signature: value.delta.signature };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
signature: value.delta.signature,
|
||||
};
|
||||
break;
|
||||
case "input_json_delta":
|
||||
if (!lastToolUseId || !lastToolUseName) {
|
||||
|
|
|
|||
|
|
@ -14,9 +14,10 @@ import {
|
|||
CompletionOptions,
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
|
||||
import { getSecureID } from "../utils/getSecureID.js";
|
||||
|
||||
interface ModelConfig {
|
||||
formatPayload: (text: string) => any;
|
||||
|
|
@ -284,10 +285,13 @@ class Bedrock extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
): any {
|
||||
const systemMessage = stripImages(
|
||||
messages.find((m) => m.role === "system")?.content ?? "",
|
||||
);
|
||||
const convertedMessages = this._convertMessages(messages);
|
||||
|
||||
const shouldCacheSystemMessage =
|
||||
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
!!systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const enablePromptCaching =
|
||||
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
|
||||
|
||||
|
|
@ -304,10 +308,10 @@ class Bedrock extends BaseLLM {
|
|||
return {
|
||||
modelId: options.model,
|
||||
messages: convertedMessages,
|
||||
system: this.systemMessage
|
||||
system: systemMessage
|
||||
? shouldCacheSystemMessage
|
||||
? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }]
|
||||
: [{ text: this.systemMessage }]
|
||||
? [{ text: systemMessage }, { cachePoint: { type: "default" } }]
|
||||
: [{ text: systemMessage }]
|
||||
: undefined,
|
||||
toolConfig:
|
||||
supportsTools && options.tools
|
||||
|
|
@ -427,6 +431,9 @@ class Bedrock extends BaseLLM {
|
|||
|
||||
// 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" } });
|
||||
|
|
@ -444,6 +451,9 @@ class Bedrock extends BaseLLM {
|
|||
// 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 {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
CompletionOptions,
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamJSON } from "../stream.js";
|
||||
|
||||
|
|
@ -67,6 +67,11 @@ class Cohere extends BaseLLM {
|
|||
...this.requestOptions?.headers,
|
||||
};
|
||||
|
||||
let preamble: string | undefined = undefined;
|
||||
const systemMessage = messages.find((m) => m.role === "system")?.content;
|
||||
if (systemMessage) {
|
||||
preamble = stripImages(systemMessage);
|
||||
}
|
||||
const resp = await this.fetch(new URL("chat", this.apiBase), {
|
||||
method: "POST",
|
||||
headers,
|
||||
|
|
@ -74,7 +79,7 @@ class Cohere extends BaseLLM {
|
|||
...this._convertArgs(options),
|
||||
message: messages.pop()?.content,
|
||||
chat_history: this._convertMessages(messages),
|
||||
preamble: this.systemMessage,
|
||||
preamble,
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
import {
|
||||
AssistantChatMessage,
|
||||
ChatMessage,
|
||||
|
|
@ -7,17 +8,18 @@ import {
|
|||
TextMessagePart,
|
||||
ToolCallDelta,
|
||||
} from "../../index.js";
|
||||
import { findLast } from "../../util/findLast.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
import {
|
||||
GeminiChatContent,
|
||||
GeminiChatContentPart,
|
||||
GeminiChatRequestBody,
|
||||
GeminiChatResponse,
|
||||
GeminiGenerationConfig,
|
||||
GeminiToolFunctionDeclaration,
|
||||
} from "./gemini-types.js";
|
||||
convertContinueToolToGeminiFunction,
|
||||
} from "./gemini-types";
|
||||
|
||||
class Gemini extends BaseLLM {
|
||||
static providerName = "gemini";
|
||||
|
|
@ -155,14 +157,8 @@ class Gemini extends BaseLLM {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
// Ensure this.apiBase is used if available, otherwise use default
|
||||
const apiBase =
|
||||
this.apiBase ||
|
||||
Gemini.defaultOptions?.apiBase ||
|
||||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
|
||||
const isV1API = apiBase.includes("/v1/");
|
||||
const isV1API = this.apiBase?.includes("/v1/");
|
||||
|
||||
// Conditionally apply removeSystemMessage
|
||||
const convertedMsgs = isV1API
|
||||
? this.removeSystemMessage(messages)
|
||||
: messages;
|
||||
|
|
@ -204,20 +200,27 @@ class Gemini extends BaseLLM {
|
|||
options: CompletionOptions,
|
||||
isV1API: boolean,
|
||||
): GeminiChatRequestBody {
|
||||
const toolCallIdToNameMap = new Map<string, string>();
|
||||
messages.forEach((msg) => {
|
||||
if (msg.role === "assistant" && msg.toolCalls) {
|
||||
msg.toolCalls.forEach((call) => {
|
||||
if (call.id && call.function?.name) {
|
||||
toolCallIdToNameMap.set(call.id, call.function.name);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
const systemMessage = messages.find(
|
||||
(msg) => msg.role === "system",
|
||||
)?.content;
|
||||
|
||||
const body: GeminiChatRequestBody = {
|
||||
contents: messages
|
||||
.filter((msg) => !(msg.role === "system" && isV1API))
|
||||
.map((msg) => {
|
||||
if (msg.role === "tool") {
|
||||
let fn_name = "";
|
||||
const lastToolCallMessage = findLast(
|
||||
messages,
|
||||
(msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name,
|
||||
) as AssistantChatMessage;
|
||||
if (lastToolCallMessage) {
|
||||
fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!;
|
||||
}
|
||||
if (!fn_name) {
|
||||
let functionName = toolCallIdToNameMap.get(msg.toolCallId);
|
||||
if (!functionName) {
|
||||
console.warn(
|
||||
"Sending tool call response for unidentified tool call",
|
||||
);
|
||||
|
|
@ -227,7 +230,8 @@ class Gemini extends BaseLLM {
|
|||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: fn_name || "unknown",
|
||||
id: msg.toolCallId,
|
||||
name: functionName || "unknown",
|
||||
response: {
|
||||
output: msg.content, // "output" key is opinionated - not all functions will output objects
|
||||
},
|
||||
|
|
@ -236,28 +240,35 @@ class Gemini extends BaseLLM {
|
|||
],
|
||||
};
|
||||
}
|
||||
const assistantMsg = {
|
||||
role:
|
||||
msg.role === "assistant" ? ("model" as const) : ("user" as const),
|
||||
if (msg.role === "assistant") {
|
||||
const assistantMsg: GeminiChatContent = {
|
||||
role: "model",
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
if (msg.toolCalls) {
|
||||
msg.toolCalls.forEach((toolCall) => {
|
||||
if (toolCall.function?.name && toolCall.function?.arguments) {
|
||||
assistantMsg.parts.push({
|
||||
functionCall: {
|
||||
name: toolCall.function.name,
|
||||
args: JSON.parse(toolCall.function.arguments),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
return assistantMsg;
|
||||
}
|
||||
return {
|
||||
role: "user",
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
if (msg.role === "assistant" && msg.toolCalls) {
|
||||
msg.toolCalls.forEach((toolCall) => {
|
||||
if (toolCall.function?.name && toolCall.function?.arguments) {
|
||||
assistantMsg.parts.push({
|
||||
functionCall: {
|
||||
name: toolCall.function.name,
|
||||
args: JSON.parse(toolCall.function.arguments),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return assistantMsg;
|
||||
}),
|
||||
};
|
||||
if (options) {
|
||||
|
|
@ -266,8 +277,10 @@ class Gemini extends BaseLLM {
|
|||
|
||||
// https://ai.google.dev/gemini-api/docs/api-versions
|
||||
if (!isV1API) {
|
||||
if (this.systemMessage) {
|
||||
body.systemInstruction = { parts: [{ text: this.systemMessage }] };
|
||||
if (systemMessage) {
|
||||
body.systemInstruction = {
|
||||
parts: [{ text: stripImages(systemMessage) }],
|
||||
};
|
||||
}
|
||||
// Convert and add tools if present
|
||||
if (options.tools?.length) {
|
||||
|
|
@ -276,77 +289,12 @@ class Gemini extends BaseLLM {
|
|||
// Same difference
|
||||
const functions: GeminiToolFunctionDeclaration[] = [];
|
||||
options.tools.forEach((tool) => {
|
||||
if (tool.function.description && tool.function.name) {
|
||||
const fn: GeminiToolFunctionDeclaration = {
|
||||
description: tool.function.description,
|
||||
name: tool.function.name,
|
||||
};
|
||||
|
||||
if (
|
||||
tool.function.parameters &&
|
||||
"type" in tool.function.parameters
|
||||
// && typeof tool.function.parameters.type === "string"
|
||||
) {
|
||||
// const paramType = "TYPE_UNSPECIFIED"
|
||||
// | "STRING"
|
||||
// | "NUMBER"
|
||||
// | "INTEGER"
|
||||
// | "BOOLEAN"
|
||||
// | "ARRAY"
|
||||
// | "OBJECT"
|
||||
|
||||
if (tool.function.parameters.type === "object") {
|
||||
// Gemini can't take an empty object
|
||||
// So if empty object param is present just don't add parameters
|
||||
if (
|
||||
JSON.stringify(tool.function.parameters.properties) === "{}"
|
||||
) {
|
||||
functions.push(fn);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Helper function to recursively clean JSON Schema objects
|
||||
const cleanJsonSchema = (schema: any): any => {
|
||||
if (!schema || typeof schema !== "object") return schema;
|
||||
|
||||
if (Array.isArray(schema)) {
|
||||
return schema.map(cleanJsonSchema);
|
||||
}
|
||||
|
||||
const {
|
||||
$schema,
|
||||
additionalProperties,
|
||||
default: defaultValue,
|
||||
...rest
|
||||
} = schema;
|
||||
|
||||
// Recursively clean nested properties
|
||||
if (rest.properties) {
|
||||
rest.properties = Object.entries(rest.properties).reduce(
|
||||
(acc, [key, value]) => ({
|
||||
...acc,
|
||||
[key]: cleanJsonSchema(value),
|
||||
}),
|
||||
{},
|
||||
);
|
||||
}
|
||||
|
||||
// Clean items in arrays
|
||||
if (rest.items) {
|
||||
rest.items = cleanJsonSchema(rest.items);
|
||||
}
|
||||
|
||||
return rest;
|
||||
};
|
||||
|
||||
// Clean the parameters and convert type to uppercase
|
||||
const cleanedParams = cleanJsonSchema(tool.function.parameters);
|
||||
fn.parameters = {
|
||||
...cleanedParams,
|
||||
type: tool.function.parameters.type.toUpperCase(),
|
||||
};
|
||||
}
|
||||
functions.push(fn);
|
||||
try {
|
||||
functions.push(convertContinueToolToGeminiFunction(tool));
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
if (functions.length) {
|
||||
|
|
@ -397,75 +345,39 @@ class Gemini extends BaseLLM {
|
|||
// Check for existence of each level before accessing the final 'text' property
|
||||
const content = data?.candidates?.[0]?.content;
|
||||
if (content) {
|
||||
const supportedParts: MessagePart[] = [];
|
||||
const textParts: MessagePart[] = [];
|
||||
const toolCalls: ToolCallDelta[] = [];
|
||||
|
||||
// Process all parts first to maintain order
|
||||
const processedParts: Array<{
|
||||
type: "content" | "tool" | "toolCall";
|
||||
data: any;
|
||||
}> = [];
|
||||
|
||||
for (const part of content.parts) {
|
||||
if ("text" in part) {
|
||||
supportedParts.push({ type: "text", text: part.text });
|
||||
} else if ("inlineData" in part) {
|
||||
supportedParts.push({
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: `data:image/jpeg;base64,${part.inlineData.data}`,
|
||||
},
|
||||
});
|
||||
textParts.push({ type: "text", text: part.text });
|
||||
} else if ("functionCall" in part) {
|
||||
// Queue function call
|
||||
processedParts.push({
|
||||
type: "toolCall",
|
||||
data: {
|
||||
type: "function",
|
||||
id: "", // Not supported by gemini
|
||||
function: {
|
||||
name: part.functionCall.name,
|
||||
arguments:
|
||||
typeof part.functionCall.args === "string"
|
||||
? part.functionCall.args
|
||||
: JSON.stringify(part.functionCall.args),
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if ("functionResponse" in part) {
|
||||
// Queue function response
|
||||
processedParts.push({
|
||||
type: "tool",
|
||||
data: {
|
||||
role: "tool",
|
||||
content: part.functionResponse.response.output as string,
|
||||
toolCallId: part.functionResponse.name,
|
||||
toolCalls.push({
|
||||
type: "function",
|
||||
id: part.functionCall.id ?? uuidv4(),
|
||||
function: {
|
||||
name: part.functionCall.name,
|
||||
arguments:
|
||||
typeof part.functionCall.args === "string"
|
||||
? part.functionCall.args
|
||||
: JSON.stringify(part.functionCall.args),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Note: function responses shouldn't be streamed, images not supported
|
||||
console.warn("Unsupported gemini part type received", part);
|
||||
}
|
||||
}
|
||||
|
||||
// If we have supported content parts, yield them first
|
||||
if (supportedParts.length) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: supportedParts,
|
||||
};
|
||||
const assistantMessage: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: textParts.length ? textParts : "",
|
||||
};
|
||||
if (toolCalls.length > 0) {
|
||||
assistantMessage.toolCalls = toolCalls;
|
||||
}
|
||||
|
||||
// Then process tool calls and responses in order
|
||||
for (const part of processedParts) {
|
||||
if (part.type === "toolCall") {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [part.data],
|
||||
};
|
||||
} else if (part.type === "tool") {
|
||||
yield part.data;
|
||||
}
|
||||
if (textParts.length || toolCalls.length) {
|
||||
yield assistantMessage;
|
||||
}
|
||||
} else {
|
||||
// Handle the case where the expected data structure is not found
|
||||
|
|
@ -489,10 +401,8 @@ class Gemini extends BaseLLM {
|
|||
`models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
|
||||
this.apiBase,
|
||||
);
|
||||
// This feels hacky to repeat code from above function but was the quickest
|
||||
// way to ensure system message re-formatting isn't done if user has specified v1
|
||||
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
|
||||
const isV1API = apiBase.includes("/v1/");
|
||||
|
||||
const isV1API = !!this.apiBase?.includes("/v1/");
|
||||
|
||||
// Convert chat messages to contents
|
||||
const body = this.prepareBody(messages, options, isV1API);
|
||||
|
|
|
|||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -288,7 +288,10 @@ class OpenAI extends BaseLLM {
|
|||
// To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs
|
||||
// In practice, setting this to true and asking for multiple tool calls
|
||||
// leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}'
|
||||
body.parallel_tool_calls = false;
|
||||
// o3 does not support this
|
||||
if (!body.model.startsWith("o3")) {
|
||||
body.parallel_tool_calls = false;
|
||||
}
|
||||
}
|
||||
|
||||
return body;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { LLMOptions } from "../..";
|
||||
import { LLMConfigurationStatuses } from "../constants";
|
||||
import { LlmApiRequestType } from "../openaiTypeConverters";
|
||||
|
||||
import OpenAI from "./OpenAI";
|
||||
|
|
@ -9,4 +10,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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,16 +80,6 @@ class Replicate extends BaseLLM {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// protected async *_streamChat(
|
||||
// messages: ChatMessage[],
|
||||
// options: CompletionOptions
|
||||
// ): AsyncGenerator<ChatMessage> {
|
||||
// const resp = await this.complete(
|
||||
// stripImages(messages[0]?.content || ""),
|
||||
// options
|
||||
// );
|
||||
// }
|
||||
}
|
||||
|
||||
export default Replicate;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { GoogleAuth } from "google-auth-library";
|
||||
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse, streamSse } from "../stream.js";
|
||||
|
||||
|
|
@ -11,7 +11,7 @@ import Gemini from "./Gemini.js";
|
|||
class VertexAI extends BaseLLM {
|
||||
static providerName = "vertexai";
|
||||
declare apiBase: string;
|
||||
declare vertexProvider: string;
|
||||
declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown";
|
||||
declare anthropicInstance: Anthropic;
|
||||
declare geminiInstance: Gemini;
|
||||
|
||||
|
|
@ -92,13 +92,13 @@ class VertexAI extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const shouldCacheSystemMessage =
|
||||
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const filteredSystemMessages : ChatMessage[] = messages.filter((m) => m.role === "system");
|
||||
let systemMessage: string = "";
|
||||
if(filteredSystemMessages.length > 0) {
|
||||
systemMessage = renderChatMessage(filteredSystemMessages[0]);
|
||||
}
|
||||
const systemMessage = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content ?? "",
|
||||
);
|
||||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
|
||||
const apiURL = new URL(
|
||||
`publishers/anthropic/models/${options.model}:streamRawPredict`,
|
||||
this.apiBase,
|
||||
|
|
@ -118,7 +118,7 @@ class VertexAI extends BaseLLM {
|
|||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: this.systemMessage,
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
|
|
@ -142,8 +142,7 @@ class VertexAI extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
//Gemini
|
||||
|
||||
// Gemini
|
||||
private async *streamChatGemini(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
|
|
@ -306,7 +305,7 @@ class VertexAI extends BaseLLM {
|
|||
yield (await resp.json()).predictions[0].content;
|
||||
}
|
||||
|
||||
//Manager functions
|
||||
// Manager functions
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
|
|
@ -328,6 +327,8 @@ class VertexAI extends BaseLLM {
|
|||
} else {
|
||||
if (options.model.includes("bison")) {
|
||||
yield* this.streamChatBison(convertedMsgs, options);
|
||||
} else {
|
||||
throw new Error(`Unsupported model: ${options.model}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
import { ChatMessage, Chunk, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
|
|
@ -139,24 +144,24 @@ class WatsonX extends BaseLLM {
|
|||
}
|
||||
|
||||
protected async updateWatsonxToken() {
|
||||
var now = new Date().getTime() / 1000;
|
||||
if (
|
||||
watsonxToken === undefined ||
|
||||
now > watsonxToken.expiration ||
|
||||
watsonxToken.token === undefined
|
||||
) {
|
||||
watsonxToken = await this.getBearerToken();
|
||||
} else {
|
||||
console.log(
|
||||
`Reusing token (expires in ${
|
||||
(watsonxToken.expiration - now) / 60
|
||||
} mins)`,
|
||||
);
|
||||
}
|
||||
if (watsonxToken.token === undefined) {
|
||||
throw new Error("Something went wrong. Check your credentials, please.");
|
||||
}
|
||||
var now = new Date().getTime() / 1000;
|
||||
if (
|
||||
watsonxToken === undefined ||
|
||||
now > watsonxToken.expiration ||
|
||||
watsonxToken.token === undefined
|
||||
) {
|
||||
watsonxToken = await this.getBearerToken();
|
||||
} else {
|
||||
console.log(
|
||||
`Reusing token (expires in ${
|
||||
(watsonxToken.expiration - now) / 60
|
||||
} mins)`,
|
||||
);
|
||||
}
|
||||
if (watsonxToken.token === undefined) {
|
||||
throw new Error("Something went wrong. Check your credentials, please.");
|
||||
}
|
||||
}
|
||||
|
||||
protected async _complete(
|
||||
prompt: string,
|
||||
|
|
@ -312,64 +317,60 @@ class WatsonX extends BaseLLM {
|
|||
return embeddings.map((e: any) => e.embedding);
|
||||
}
|
||||
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || !chunks.length) {
|
||||
throw new Error("Query and chunks must not be empty");
|
||||
}
|
||||
try {
|
||||
await this.updateWatsonxToken();
|
||||
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${
|
||||
watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
|
||||
} ${watsonxToken.token}`,
|
||||
};
|
||||
|
||||
const payload: any = {
|
||||
inputs: chunks.map((chunk) => ({ text: chunk.content })),
|
||||
query: query,
|
||||
parameters: {
|
||||
truncate_input_tokens: 500,
|
||||
return_options: {
|
||||
top_n: chunks.length
|
||||
},
|
||||
if (!query || !chunks.length) {
|
||||
throw new Error("Query and chunks must not be empty");
|
||||
}
|
||||
try {
|
||||
await this.updateWatsonxToken();
|
||||
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${
|
||||
watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
|
||||
} ${watsonxToken.token}`,
|
||||
};
|
||||
|
||||
const payload: any = {
|
||||
inputs: chunks.map((chunk) => ({ text: chunk.content })),
|
||||
query: query,
|
||||
parameters: {
|
||||
truncate_input_tokens: 500,
|
||||
return_options: {
|
||||
top_n: chunks.length,
|
||||
},
|
||||
model_id: this.model,
|
||||
project_id: this.projectId,
|
||||
};
|
||||
},
|
||||
model_id: this.model,
|
||||
project_id: this.projectId,
|
||||
};
|
||||
|
||||
const resp = await this.fetch(
|
||||
new URL(
|
||||
`${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`,
|
||||
),
|
||||
{
|
||||
method: "POST",
|
||||
headers: headers,
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
const resp = await this.fetch(
|
||||
new URL(`${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`),
|
||||
{
|
||||
method: "POST",
|
||||
headers: headers,
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Failed to rerank chunks: ${await resp.text()}`);
|
||||
}
|
||||
const data = await resp.json();
|
||||
const ranking = data.results;
|
||||
|
||||
if (!ranking) {
|
||||
throw new Error("Empty response received from Watsonx");
|
||||
}
|
||||
|
||||
// Sort results by index to maintain original order
|
||||
return ranking
|
||||
.sort((a: any, b: any) => a.index - b.index)
|
||||
.map((result: any) => result.score);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error in WatsonxReranker.rerank:", error);
|
||||
throw error;
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Failed to rerank chunks: ${await resp.text()}`);
|
||||
}
|
||||
const data = await resp.json();
|
||||
const ranking = data.results;
|
||||
|
||||
if (!ranking) {
|
||||
throw new Error("Empty response received from Watsonx");
|
||||
}
|
||||
|
||||
// Sort results by index to maintain original order
|
||||
return ranking
|
||||
.sort((a: any, b: any) => a.index - b.index)
|
||||
.map((result: any) => result.score);
|
||||
} catch (error) {
|
||||
console.error("Error in WatsonxReranker.rerank:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { JSONSchema7Object } from "json-schema";
|
||||
import { Tool } from "../..";
|
||||
|
||||
// https://ai.google.dev/api/generate-content
|
||||
export interface GeminiGenerationConfig {
|
||||
|
|
@ -16,70 +17,225 @@ export interface GeminiGenerationConfig {
|
|||
// responseSchema?: object; // https://ai.google.dev/api/caching#Schema
|
||||
}
|
||||
|
||||
export interface GeminiFunctionSchema {
|
||||
type:
|
||||
| "TYPE_UNSPECIFIED"
|
||||
| "STRING"
|
||||
| "NUMBER"
|
||||
| "INTEGER"
|
||||
| "BOOLEAN"
|
||||
| "ARRAY"
|
||||
| "OBJECT";
|
||||
export type GeminiObjectSchemaType =
|
||||
| "TYPE_UNSPECIFIED"
|
||||
| "STRING"
|
||||
| "NUMBER"
|
||||
| "INTEGER"
|
||||
| "BOOLEAN"
|
||||
| "ARRAY"
|
||||
| "OBJECT";
|
||||
|
||||
export interface GeminiObjectSchema {
|
||||
type: GeminiObjectSchemaType;
|
||||
format?: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
nullable?: boolean;
|
||||
enum?: string[];
|
||||
maxItems?: string;
|
||||
minItems?: string;
|
||||
properties?: Record<string, GeminiFunctionSchema>;
|
||||
properties?: Record<string, GeminiObjectSchema>;
|
||||
required?: string[];
|
||||
items?: GeminiFunctionSchema;
|
||||
anyOf?: GeminiObjectSchema[];
|
||||
propertyOrdering?: string[];
|
||||
items?: GeminiObjectSchema;
|
||||
minimum?: number;
|
||||
maximum?: number;
|
||||
}
|
||||
|
||||
const jsonSchemaTypeToGeminiType = (
|
||||
jsonSchemaType: string,
|
||||
): GeminiObjectSchemaType => {
|
||||
switch (jsonSchemaType.toLowerCase()) {
|
||||
case "string":
|
||||
return "STRING";
|
||||
case "object":
|
||||
return "OBJECT";
|
||||
case "number":
|
||||
return "NUMBER";
|
||||
case "integer":
|
||||
return "INTEGER";
|
||||
case "array":
|
||||
return "ARRAY";
|
||||
case "boolean":
|
||||
return "BOOLEAN";
|
||||
default:
|
||||
return "TYPE_UNSPECIFIED";
|
||||
}
|
||||
};
|
||||
|
||||
function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema {
|
||||
const jsonSchemaType = jsonSchema["type"];
|
||||
if (!jsonSchemaType || typeof jsonSchema.type !== "string") {
|
||||
throw new Error(
|
||||
`Invalid type property in function declaration\n${JSON.stringify(jsonSchema, null, 2)}`,
|
||||
);
|
||||
}
|
||||
const geminiSchema: GeminiObjectSchema = {
|
||||
type: jsonSchemaTypeToGeminiType(jsonSchemaType),
|
||||
};
|
||||
|
||||
// if (jsonSchema.format) geminiSchema.format = jsonSchema.format;
|
||||
if (jsonSchema.title) geminiSchema.title = jsonSchema.title;
|
||||
if (jsonSchema.description) geminiSchema.description = jsonSchema.description;
|
||||
|
||||
// Handle nullable
|
||||
if (jsonSchemaType === "null" || jsonSchema.nullable) {
|
||||
geminiSchema.nullable = true;
|
||||
}
|
||||
|
||||
// Handle enum values
|
||||
if (Array.isArray(jsonSchema.enum)) {
|
||||
geminiSchema.enum = jsonSchema.enum.map(String);
|
||||
}
|
||||
|
||||
// Handle array constraints
|
||||
if (jsonSchemaType === "array") {
|
||||
if (typeof jsonSchema.maxItems !== "undefined") {
|
||||
geminiSchema.maxItems = String(jsonSchema.maxItems);
|
||||
}
|
||||
if (typeof jsonSchema.minItems !== "undefined") {
|
||||
geminiSchema.minItems = String(jsonSchema.minItems);
|
||||
}
|
||||
// Handle array items
|
||||
if (jsonSchema.items) {
|
||||
geminiSchema.items = convertJsonSchemaToGeminiSchema(jsonSchema.items);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle numeric constraints
|
||||
if (typeof jsonSchema.minimum !== "undefined") {
|
||||
geminiSchema.minimum = Number(jsonSchema.minimum);
|
||||
}
|
||||
if (typeof jsonSchema.maximum !== "undefined") {
|
||||
geminiSchema.maximum = Number(jsonSchema.maximum);
|
||||
}
|
||||
|
||||
// Handle properties for objects
|
||||
if (jsonSchema.properties) {
|
||||
geminiSchema.properties = {};
|
||||
for (const [key, value] of Object.entries(jsonSchema.properties)) {
|
||||
geminiSchema.properties[key] = convertJsonSchemaToGeminiSchema(value);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle required properties
|
||||
if (Array.isArray(jsonSchema.required)) {
|
||||
geminiSchema.required = jsonSchema.required;
|
||||
}
|
||||
|
||||
// Handle anyOf
|
||||
if (Array.isArray(jsonSchema.anyOf)) {
|
||||
geminiSchema.anyOf = jsonSchema.anyOf.map(convertJsonSchemaToGeminiSchema);
|
||||
}
|
||||
|
||||
// TODO/UNSUPPORTED:
|
||||
// format
|
||||
// property ordering:
|
||||
// if (Array.isArray(jsonSchema.propertyOrdering)) {
|
||||
// geminiSchema.propertyOrdering = jsonSchema.propertyOrdering;
|
||||
// }
|
||||
|
||||
return geminiSchema;
|
||||
}
|
||||
|
||||
// https://ai.google.dev/api/caching#FunctionDeclaration
|
||||
// Note "reponse" field (schema showing function output structure) is not supported at the moment
|
||||
export function convertContinueToolToGeminiFunction(
|
||||
tool: Tool,
|
||||
): GeminiToolFunctionDeclaration {
|
||||
if (!tool.function.name) {
|
||||
throw new Error("Function name required");
|
||||
}
|
||||
const description = tool.function.description ?? "";
|
||||
const name = tool.function.name;
|
||||
|
||||
const fn: GeminiToolFunctionDeclaration = {
|
||||
description,
|
||||
name,
|
||||
};
|
||||
|
||||
if (
|
||||
tool.function.parameters &&
|
||||
"type" in tool.function.parameters &&
|
||||
typeof tool.function.parameters.type === "string"
|
||||
) {
|
||||
// Gemini can't take an empty object
|
||||
// So if empty object param is present just don't add parameters
|
||||
if (tool.function.parameters.type === "object") {
|
||||
if (JSON.stringify(tool.function.parameters.properties) === "{}") {
|
||||
return fn;
|
||||
}
|
||||
}
|
||||
|
||||
fn.parameters = convertJsonSchemaToGeminiSchema(tool.function.parameters);
|
||||
}
|
||||
|
||||
return fn;
|
||||
}
|
||||
|
||||
export type GeminiTextContentPart = {
|
||||
text: string;
|
||||
};
|
||||
|
||||
export type GeminiInlineDataContentPart = {
|
||||
inlineData: {
|
||||
mimeType: string;
|
||||
data: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type GeminiFunctionCallContentPart = {
|
||||
functionCall: {
|
||||
id?: string;
|
||||
name: string;
|
||||
args: JSONSchema7Object;
|
||||
};
|
||||
};
|
||||
|
||||
export type GeminiFunctionResponseContentPart = {
|
||||
functionResponse: {
|
||||
id?: string;
|
||||
name: string;
|
||||
response: JSONSchema7Object;
|
||||
};
|
||||
};
|
||||
|
||||
export type GeminiFileDataContentPart = {
|
||||
fileData: {
|
||||
fileUri: string;
|
||||
mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata
|
||||
};
|
||||
};
|
||||
|
||||
export type GeminiExecutableCodeContentPart = {
|
||||
executableCode: {
|
||||
language: "PYTHON" | "LANGUAGE_UNSPECIFIED";
|
||||
code: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type GeminiCodeExecutionResultContentPart = {
|
||||
codeExecutionResult: {
|
||||
outcome:
|
||||
| "OUTCOME_UNSPECIFIED"
|
||||
| "OUTCOME_OK"
|
||||
| "OUTCOME_FAILED"
|
||||
| "OUTCOME_DEADLINE_EXCEEDED";
|
||||
output: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type GeminiChatContentPart =
|
||||
| {
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
inlineData: {
|
||||
mimeType: string;
|
||||
data: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
functionCall: {
|
||||
name: string;
|
||||
args: JSONSchema7Object;
|
||||
};
|
||||
}
|
||||
| {
|
||||
functionResponse: {
|
||||
name: string;
|
||||
response: JSONSchema7Object;
|
||||
};
|
||||
}
|
||||
| {
|
||||
fileData: {
|
||||
fileUri: string;
|
||||
mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata
|
||||
};
|
||||
}
|
||||
| {
|
||||
executableCode: {
|
||||
language: "PYTHON" | "LANGUAGE_UNSPECIFIED";
|
||||
code: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
codeExecutionResult: {
|
||||
outcome:
|
||||
| "OUTCOME_UNSPECIFIED"
|
||||
| "OUTCOME_OK"
|
||||
| "OUTCOME_FAILED"
|
||||
| "OUTCOME_DEADLINE_EXCEEDED";
|
||||
output: string;
|
||||
};
|
||||
};
|
||||
| GeminiTextContentPart
|
||||
| GeminiInlineDataContentPart
|
||||
| GeminiFunctionCallContentPart
|
||||
| GeminiFunctionResponseContentPart
|
||||
| GeminiFileDataContentPart
|
||||
| GeminiExecutableCodeContentPart
|
||||
| GeminiCodeExecutionResultContentPart;
|
||||
|
||||
export interface GeminiChatContent {
|
||||
role?: "user" | "model";
|
||||
parts: GeminiChatContentPart[];
|
||||
|
|
@ -88,7 +244,8 @@ export interface GeminiChatContent {
|
|||
export interface GeminiToolFunctionDeclaration {
|
||||
name: string;
|
||||
description: string;
|
||||
parameters?: GeminiFunctionSchema;
|
||||
parameters?: GeminiObjectSchema;
|
||||
response?: GeminiObjectSchema;
|
||||
}
|
||||
export interface GeminiTool {
|
||||
functionDeclarations?: GeminiToolFunctionDeclaration[];
|
||||
|
|
|
|||
|
|
@ -3,10 +3,11 @@ import {
|
|||
IdeSettings,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
JSONModelDescription,
|
||||
LLMOptions,
|
||||
ModelDescription,
|
||||
} from "../..";
|
||||
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
|
||||
import { BaseLLM } from "../index";
|
||||
|
||||
import Anthropic from "./Anthropic";
|
||||
|
|
@ -27,6 +28,7 @@ import FunctionNetwork from "./FunctionNetwork";
|
|||
import Gemini from "./Gemini";
|
||||
import Groq from "./Groq";
|
||||
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
|
||||
import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEI";
|
||||
import HuggingFaceTGI from "./HuggingFaceTGI";
|
||||
import Inception from "./Inception";
|
||||
import Kindo from "./Kindo";
|
||||
|
|
@ -56,6 +58,7 @@ import TextGenWebUI from "./TextGenWebUI";
|
|||
import Together from "./Together";
|
||||
import VertexAI from "./VertexAI";
|
||||
import Vllm from "./Vllm";
|
||||
import Voyage from "./Voyage";
|
||||
import WatsonX from "./WatsonX";
|
||||
import xAI from "./xAI";
|
||||
|
||||
|
|
@ -73,6 +76,7 @@ export const LLMClasses = [
|
|||
Together,
|
||||
Novita,
|
||||
HuggingFaceTGI,
|
||||
HuggingFaceTEIEmbeddingsProvider,
|
||||
HuggingFaceInferenceAPI,
|
||||
Kindo,
|
||||
LlamaCpp,
|
||||
|
|
@ -109,16 +113,16 @@ export const LLMClasses = [
|
|||
Scaleway,
|
||||
Relace,
|
||||
Inception,
|
||||
Voyage,
|
||||
];
|
||||
|
||||
export async function llmFromDescription(
|
||||
desc: ModelDescription,
|
||||
desc: JSONModelDescription,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
llmLogger: ILLMLogger,
|
||||
completionOptions?: BaseCompletionOptions,
|
||||
systemMessage?: string,
|
||||
): Promise<BaseLLM | undefined> {
|
||||
const cls = LLMClasses.find((llm) => llm.providerName === desc.provider);
|
||||
|
||||
|
|
@ -131,9 +135,15 @@ export async function llmFromDescription(
|
|||
...desc.completionOptions,
|
||||
};
|
||||
|
||||
systemMessage = desc.systemMessage ?? systemMessage;
|
||||
if (systemMessage !== undefined) {
|
||||
systemMessage = await renderTemplatedString(systemMessage, readFile, {});
|
||||
let baseChatSystemMessage: string | undefined = undefined;
|
||||
if (desc.systemMessage !== undefined) {
|
||||
baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
|
||||
baseChatSystemMessage += "\n\n";
|
||||
baseChatSystemMessage += await renderTemplatedString(
|
||||
desc.systemMessage,
|
||||
readFile,
|
||||
{},
|
||||
);
|
||||
}
|
||||
|
||||
let options: LLMOptions = {
|
||||
|
|
@ -145,7 +155,7 @@ export async function llmFromDescription(
|
|||
finalCompletionOptions.maxTokens ??
|
||||
cls.defaultOptions?.completionOptions?.maxTokens,
|
||||
},
|
||||
systemMessage,
|
||||
baseChatSystemMessage,
|
||||
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;
|
||||
|
|
|
|||
69
core/llm/messages.ts
Normal file
69
core/llm/messages.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { ChatMessage } from "..";
|
||||
|
||||
export function messageHasToolCalls(msg: ChatMessage): boolean {
|
||||
return msg.role === "assistant" && !!msg.toolCalls;
|
||||
}
|
||||
|
||||
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
|
||||
const flattened: ChatMessage[] = [];
|
||||
|
||||
for (let i = 0; i < msgs.length; i++) {
|
||||
const msg = msgs[i];
|
||||
|
||||
if (
|
||||
flattened.length > 0 &&
|
||||
flattened[flattened.length - 1].role === msg.role &&
|
||||
!messageHasToolCalls(msg) &&
|
||||
!messageHasToolCalls(flattened[flattened.length - 1])
|
||||
) {
|
||||
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
|
||||
} else {
|
||||
flattened.push(msg);
|
||||
}
|
||||
}
|
||||
|
||||
return flattened;
|
||||
}
|
||||
|
||||
export function messageIsEmpty(message: ChatMessage): boolean {
|
||||
if (typeof message.content === "string") {
|
||||
return message.content.trim() === "";
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content.every(
|
||||
(item) => item.type === "text" && item.text?.trim() === "",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// some providers don't support empty messages
|
||||
export function addSpaceToAnyEmptyMessages(
|
||||
messages: ChatMessage[],
|
||||
): ChatMessage[] {
|
||||
return messages.map((message) => {
|
||||
if (messageIsEmpty(message)) {
|
||||
message.content = " ";
|
||||
}
|
||||
return message;
|
||||
});
|
||||
}
|
||||
|
||||
export function chatMessageIsEmpty(message: ChatMessage): boolean {
|
||||
switch (message.role) {
|
||||
case "system":
|
||||
case "user":
|
||||
return (
|
||||
typeof message.content === "string" && message.content.trim() === ""
|
||||
);
|
||||
case "assistant":
|
||||
return (
|
||||
typeof message.content === "string" &&
|
||||
message.content.trim() === "" &&
|
||||
!message.toolCalls
|
||||
);
|
||||
case "thinking":
|
||||
case "tool":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
35
core/llm/rules/getSystemMessageWithRules.ts
Normal file
35
core/llm/rules/getSystemMessageWithRules.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { RuleWithSource, UserChatMessage } from "../..";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
|
||||
import { isRuleActive } from "./isRuleActive";
|
||||
|
||||
export const getSystemMessageWithRules = ({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules,
|
||||
currentModel,
|
||||
}: {
|
||||
baseSystemMessage?: string;
|
||||
userMessage: UserChatMessage | undefined;
|
||||
rules: RuleWithSource[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const filePathsFromMessage = userMessage
|
||||
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
|
||||
: [];
|
||||
|
||||
let systemMessage = baseSystemMessage ?? "";
|
||||
for (const rule of rules) {
|
||||
if (
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: filePathsFromMessage,
|
||||
currentModel,
|
||||
})
|
||||
) {
|
||||
systemMessage += `\n\n${rule.rule}`;
|
||||
}
|
||||
}
|
||||
|
||||
return systemMessage;
|
||||
};
|
||||
|
|
@ -1,10 +1,12 @@
|
|||
import { RuleWithSource } from "../..";
|
||||
import { isRuleActive } from "./isRuleActive";
|
||||
|
||||
describe("isRuleActive", () => {
|
||||
const rule = {
|
||||
const rule: RuleWithSource = {
|
||||
name: "My Rule",
|
||||
rule: "Do no harm",
|
||||
if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}',
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
it("should return false when activePaths is empty", () => {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Rule } from "@continuedev/config-yaml";
|
||||
import { compileExpression } from "filtrex";
|
||||
import { minimatch } from "minimatch";
|
||||
import { RuleWithSource } from "../..";
|
||||
|
||||
const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/;
|
||||
|
||||
|
|
@ -52,14 +52,10 @@ export const isRuleActive = ({
|
|||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
rule: Rule;
|
||||
rule: RuleWithSource;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}): boolean => {
|
||||
if (typeof rule === "string") {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (rule.if) {
|
||||
return evaluateIf({ condition: rule.if, activePaths, currentModel });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 -->');
|
||||
});
|
||||
});
|
||||
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} -->`;
|
||||
}
|
||||
584
core/package-lock.json
generated
584
core/package-lock.json
generated
|
|
@ -13,7 +13,7 @@
|
|||
"@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.71",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
|
|
@ -108,6 +108,52 @@
|
|||
"node": ">=20.11.0"
|
||||
}
|
||||
},
|
||||
"../../../../../documents/code/continuedev/continue/packages/config-yaml": {
|
||||
"version": "1.0.78",
|
||||
"extraneous": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
"yaml": "^2.6.1",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
"bin": {
|
||||
"config-yaml": "dist/cli.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.0.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2"
|
||||
}
|
||||
},
|
||||
"../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": {
|
||||
"extraneous": true
|
||||
},
|
||||
"../packages/config-yaml": {
|
||||
"name": "@continuedev/config-yaml",
|
||||
"version": "1.0.78",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
"yaml": "^2.6.1",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
"bin": {
|
||||
"config-yaml": "dist/cli.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.0.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2",
|
||||
"zod-to-json-schema": "^3.24.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
|
||||
|
|
@ -2856,118 +2902,6 @@
|
|||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@biomejs/cli-darwin-x64": {
|
||||
"version": "1.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-1.6.4.tgz",
|
||||
"integrity": "sha512-uo1zgM7jvzcoDpF6dbGizejDLCqNpUIRkCj/oEK0PB0NUw8re/cn1EnxuOLZqDpn+8G75COLQTOx8UQIBBN/Kg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@biomejs/cli-linux-arm64": {
|
||||
"version": "1.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-1.6.4.tgz",
|
||||
"integrity": "sha512-wAOieaMNIpLrxGc2/xNvM//CIZg7ueWy3V5A4T7gDZ3OL/Go27EKE59a+vMKsBCYmTt7jFl4yHz0TUkUbodA/w==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@biomejs/cli-linux-arm64-musl": {
|
||||
"version": "1.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.6.4.tgz",
|
||||
"integrity": "sha512-Hp8Jwt6rjj0wCcYAEN6/cfwrrPLLlGOXZ56Lei4Pt4jy39+UuPeAVFPeclrrCfxyL1wQ2xPrhd/saTHSL6DoJg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@biomejs/cli-linux-x64": {
|
||||
"version": "1.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-1.6.4.tgz",
|
||||
"integrity": "sha512-qTWhuIw+/ePvOkjE9Zxf5OqSCYxtAvcTJtVmZT8YQnmY2I62JKNV2m7tf6O5ViKZUOP0mOQ6NgqHKcHH1eT8jw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@biomejs/cli-linux-x64-musl": {
|
||||
"version": "1.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-1.6.4.tgz",
|
||||
"integrity": "sha512-wqi0hr8KAx5kBO0B+m5u8QqiYFFBJOSJVSuRqTeGWW+GYLVUtXNidykNqf1JsW6jJDpbkSp2xHKE/bTlVaG2Kg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@biomejs/cli-win32-arm64": {
|
||||
"version": "1.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-1.6.4.tgz",
|
||||
"integrity": "sha512-Wp3FiEeF6v6C5qMfLkHwf4YsoNHr/n0efvoC8jCKO/kX05OXaVExj+1uVQ1eGT7Pvx0XVm/TLprRO0vq/V6UzA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@biomejs/cli-win32-x64": {
|
||||
"version": "1.6.4",
|
||||
"resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-1.6.4.tgz",
|
||||
"integrity": "sha512-mz183Di5hTSGP7KjNWEhivcP1wnHLGmOxEROvoFsIxMYtDhzJDad4k5gI/1JbmA0xe4n52vsgqo09tBhrMT/Zg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@continuedev/config-types": {
|
||||
"version": "1.0.14",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz",
|
||||
|
|
@ -2977,14 +2911,8 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@continuedev/config-yaml": {
|
||||
"version": "1.0.71",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz",
|
||||
"integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
"yaml": "^2.6.1",
|
||||
"zod": "^3.24.2"
|
||||
}
|
||||
"resolved": "../packages/config-yaml",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@continuedev/fetch": {
|
||||
"version": "1.0.4",
|
||||
|
|
@ -3018,52 +2946,17 @@
|
|||
"zod": "^3.24.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz",
|
||||
"integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
"node_modules/@continuedev/openai-adapters/node_modules/@continuedev/config-yaml": {
|
||||
"version": "1.0.86",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.86.tgz",
|
||||
"integrity": "sha512-X0H1iPunFcqxgTcoS87EvbqNHjfkfidWt8rQ2CU5A8iBzPSDI/jdkok0Bm0MjgzgZuXbR6GxvwMcZcOTiFw1nA==",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
"yaml": "^2.6.1",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
"bin": {
|
||||
"config-yaml": "dist/cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
|
|
@ -3082,294 +2975,6 @@
|
|||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz",
|
||||
"integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz",
|
||||
"integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz",
|
||||
"integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz",
|
||||
"integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz",
|
||||
"integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz",
|
||||
"integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz",
|
||||
"integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz",
|
||||
"integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint-community/eslint-utils": {
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz",
|
||||
|
|
@ -4110,54 +3715,6 @@
|
|||
"darwin"
|
||||
]
|
||||
},
|
||||
"node_modules/@lancedb/vectordb-darwin-x64": {
|
||||
"version": "0.4.20",
|
||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.20.tgz",
|
||||
"integrity": "sha512-GSYsXE20RIehDu30FjREhJdEzhnwOTV7ZsrSXagStzLY1gr7pyd7sfqxmmUtdD09di7LnQoiM71AOpPTa01YwQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
]
|
||||
},
|
||||
"node_modules/@lancedb/vectordb-linux-arm64-gnu": {
|
||||
"version": "0.4.20",
|
||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.20.tgz",
|
||||
"integrity": "sha512-FpNOjOsz3nJVm6EBGyNgbOW2aFhsWZ/igeY45Z8hbZaaK2YBwrg/DASoNlUzgv6IR8cUaGJ2irNVJfsKR2cG6g==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
"node_modules/@lancedb/vectordb-linux-x64-gnu": {
|
||||
"version": "0.4.20",
|
||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.20.tgz",
|
||||
"integrity": "sha512-pOqWjrRZQSrLTlQPkjidRii7NZDw8Xu9pN6ouVu2JAK8n81FXaPtFCyAI+Y3v9GpnYDN0rvD4eQ36aHAVPsa2g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
"node_modules/@lancedb/vectordb-win32-x64-msvc": {
|
||||
"version": "0.4.20",
|
||||
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.20.tgz",
|
||||
"integrity": "sha512-5J5SsYSJ7jRCmU/sgwVHdrGz43B/7R2T9OEoFTKyVAtqTZdu75rkytXyn9SyEayXVhlUOaw76N0ASm0hAoDS/A==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.5.0.tgz",
|
||||
|
|
@ -15962,27 +15519,6 @@
|
|||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/win-export-certificate-and-key": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/win-export-certificate-and-key/-/win-export-certificate-and-key-1.1.2.tgz",
|
||||
"integrity": "sha512-3Su7Xdt9UR8pZicWQDcGSWNL6We/NzAGxe7AeQ1Z/zAeGHWlTKAh3HemGvIvxLRPsk4NW9D/QL3cL6SIvFcTvQ==",
|
||||
"hasInstallScript": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"dependencies": {
|
||||
"bindings": "^1.5.0",
|
||||
"node-addon-api": "^3.1.0",
|
||||
"node-forge": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/win-export-certificate-and-key/node_modules/node-addon-api": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz",
|
||||
"integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/wink-distance": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz",
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@
|
|||
"@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.71",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
|
|
|
|||
|
|
@ -64,9 +64,6 @@ export function slashCommandFromPromptFileV1(
|
|||
description,
|
||||
prompt,
|
||||
run: async function* (context) {
|
||||
const originalSystemMessage = context.llm.systemMessage;
|
||||
context.llm.systemMessage = systemMessage;
|
||||
|
||||
const userInput = extractUserInput(context.input, name);
|
||||
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
|
||||
config: context.config,
|
||||
|
|
@ -86,6 +83,18 @@ export function slashCommandFromPromptFileV1(
|
|||
systemMessage,
|
||||
);
|
||||
|
||||
if (systemMessage) {
|
||||
const currentSystemMsg = messages.find((msg) => msg.role === "system");
|
||||
if (currentSystemMsg) {
|
||||
currentSystemMsg.content = systemMessage;
|
||||
} else {
|
||||
messages.unshift({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
|
|
@ -93,8 +102,6 @@ export function slashCommandFromPromptFileV1(
|
|||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
|
||||
context.llm.systemMessage = originalSystemMessage;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import { ChatMessage } from "../..";
|
||||
|
||||
export function replaceSlashCommandWithPromptInChatHistory(
|
||||
history: any[],
|
||||
history: ChatMessage[],
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
systemMessage?: string,
|
||||
) {
|
||||
systemMessageOverride?: string,
|
||||
): ChatMessage[] {
|
||||
const messages = [...history];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
|
|
@ -13,7 +15,12 @@ export function replaceSlashCommandWithPromptInChatHistory(
|
|||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
if (content.some((part) => part.text?.startsWith(`/${commandName}`))) {
|
||||
if (
|
||||
content.some(
|
||||
(part) =>
|
||||
part.type === "text" && part.text?.startsWith(`/${commandName}`),
|
||||
)
|
||||
) {
|
||||
messages[i] = updateArrayContent(
|
||||
messages[i],
|
||||
commandName,
|
||||
|
|
@ -30,10 +37,12 @@ export function replaceSlashCommandWithPromptInChatHistory(
|
|||
}
|
||||
}
|
||||
|
||||
if (systemMessage) {
|
||||
messages[0]?.role === "system"
|
||||
? (messages[0].content = systemMessage)
|
||||
: messages.unshift({ role: "system", content: systemMessage });
|
||||
if (systemMessageOverride) {
|
||||
if (messages[0]?.role === "system") {
|
||||
messages[0].content = systemMessageOverride;
|
||||
} else {
|
||||
messages.unshift({ role: "system", content: systemMessageOverride });
|
||||
}
|
||||
}
|
||||
|
||||
return messages;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {
|
||||
BlockType,
|
||||
ConfigResult,
|
||||
DevDataLogEvent,
|
||||
ModelRole,
|
||||
|
|
@ -31,6 +32,7 @@ import type {
|
|||
ToolCall,
|
||||
} from "../";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
|
||||
import { ControlPlaneSessionInfo } from "../control-plane/client";
|
||||
|
||||
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
|
||||
|
||||
|
|
@ -49,6 +51,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"history/delete": [{ id: string }, void];
|
||||
"history/load": [{ id: string }, Session];
|
||||
"history/save": [Session, void];
|
||||
"history/clear": [undefined, void];
|
||||
"devdata/log": [DevDataLogEvent, void];
|
||||
"config/addOpenAiKey": [string, void];
|
||||
"config/addModel": [
|
||||
|
|
@ -58,6 +61,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
},
|
||||
void,
|
||||
];
|
||||
"config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
|
||||
"config/newPromptFile": [undefined, void];
|
||||
"config/ideSettingsUpdate": [IdeSettings, void];
|
||||
"config/getSerializedProfileInfo": [
|
||||
|
|
@ -67,12 +71,20 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
profileId: string | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedOrgId: string;
|
||||
usingContinueForTeams: boolean;
|
||||
},
|
||||
];
|
||||
"config/deleteModel": [{ title: string }, void];
|
||||
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
|
||||
"config/refreshProfiles": [undefined, void];
|
||||
"config/refreshProfiles": [
|
||||
(
|
||||
| undefined
|
||||
| {
|
||||
selectOrgId?: string;
|
||||
selectProfileId?: string;
|
||||
}
|
||||
),
|
||||
void,
|
||||
];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
|
||||
"config/updateSelectedModel": [
|
||||
|
|
@ -196,4 +208,14 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
|
||||
isItemTooBig: [
|
||||
{ item: ContextItemWithId; selectedModelTitle: string | undefined },
|
||||
boolean,
|
||||
];
|
||||
didChangeControlPlaneSessionInfo: [
|
||||
{ sessionInfo: ControlPlaneSessionInfo | undefined },
|
||||
void,
|
||||
];
|
||||
"process/markAsBackgrounded": [{ toolCallId: string }, void];
|
||||
"process/isBackgrounded": [{ toolCallId: string }, boolean];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -103,8 +103,4 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
|
||||
export type ToWebviewOrCoreFromIdeProtocol = {
|
||||
didChangeActiveTextEditor: [{ filepath: string }, void];
|
||||
didChangeControlPlaneSessionInfo: [
|
||||
{ sessionInfo: ControlPlaneSessionInfo | undefined },
|
||||
void,
|
||||
];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -11,13 +11,10 @@ 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;
|
||||
},
|
||||
|
|
@ -52,7 +49,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
{
|
||||
prompt: MessageContent;
|
||||
range: RangeInFileWithContents;
|
||||
selectedModelTitle: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -14,10 +14,12 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"history/delete",
|
||||
"history/load",
|
||||
"history/save",
|
||||
"history/clear",
|
||||
"devdata/log",
|
||||
"config/addModel",
|
||||
"config/newPromptFile",
|
||||
"config/ideSettingsUpdate",
|
||||
"config/addLocalWorkspaceBlock",
|
||||
"config/getSerializedProfileInfo",
|
||||
"config/deleteModel",
|
||||
"config/refreshProfiles",
|
||||
|
|
@ -59,6 +61,9 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"controlPlane/openUrl",
|
||||
"isItemTooBig",
|
||||
"process/markAsBackgrounded",
|
||||
"process/isBackgrounded",
|
||||
];
|
||||
|
||||
// Message types to pass through from core to webview
|
||||
|
|
@ -67,7 +72,6 @@ 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",
|
||||
|
|
@ -76,5 +80,7 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
|||
"setTTSActive",
|
||||
"getWebviewHistoryLength",
|
||||
"getCurrentSessionId",
|
||||
"sessionUpdate",
|
||||
"didCloseFiles",
|
||||
"toolCallPartialOutput",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
|
||||
import { ControlPlaneSessionInfo } from "../control-plane/client.js";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContextItemWithId,
|
||||
|
|
@ -15,7 +16,6 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
profileId: string | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedOrgId: string | null;
|
||||
usingContinueForTeams: boolean;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
@ -41,4 +41,6 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
getWebviewHistoryLength: [undefined, number];
|
||||
getCurrentSessionId: [undefined, string];
|
||||
"jetbrains/setColors": [Record<string, string>, void];
|
||||
sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
|
||||
toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ export enum BuiltInToolNames {
|
|||
SearchWeb = "builtin_search_web",
|
||||
ViewDiff = "builtin_view_diff",
|
||||
LSTool = "builtin_ls",
|
||||
CreateRuleBlock = "builtin_create_rule_block",
|
||||
|
||||
// excluded from allTools for now
|
||||
ViewRepoMap = "builtin_view_repo_map",
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { canParseUrl } from "../util/url";
|
|||
import { BuiltInToolNames } from "./builtIn";
|
||||
|
||||
import { createNewFileImpl } from "./implementations/createNewFile";
|
||||
import { createRuleBlockImpl } from "./implementations/createRuleBlock";
|
||||
import { fileGlobSearchImpl } from "./implementations/globSearch";
|
||||
import { grepSearchImpl } from "./implementations/grepSearch";
|
||||
import { lsToolImpl } from "./implementations/lsTool";
|
||||
|
|
@ -156,6 +157,8 @@ export async function callTool(
|
|||
return await lsToolImpl(args, extras);
|
||||
case BuiltInToolNames.ReadCurrentlyOpenFile:
|
||||
return await readCurrentlyOpenFileImpl(args, extras);
|
||||
case BuiltInToolNames.CreateRuleBlock:
|
||||
return await createRuleBlockImpl(args, extras);
|
||||
// case BuiltInToolNames.ViewRepoMap:
|
||||
// return await viewRepoMapImpl(args, extras);
|
||||
// case BuiltInToolNames.ViewSubdirectory:
|
||||
|
|
|
|||
35
core/tools/definitions/createRuleBlock.ts
Normal file
35
core/tools/definitions/createRuleBlock.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const createRuleBlock: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Create Rule Block",
|
||||
wouldLikeTo: 'create a rule block for "{{{ rule_name }}}"',
|
||||
isCurrently: 'creating a rule block for "{{{ rule_name }}}"',
|
||||
hasAlready: 'created a rule block for "{{{ rule_name }}}"',
|
||||
readonly: false,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.CreateRuleBlock,
|
||||
description:
|
||||
"Creates a persistent rule that applies to all future conversations. " +
|
||||
"Use for establishing ongoing code standards or preferences (e.g. 'use named exports', 'follow Google docstrings'). " +
|
||||
"Not for one-time instructions. Rules are stored as YAML in `.continue/rules`.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["rule_name", "rule_content"],
|
||||
properties: {
|
||||
rule_name: {
|
||||
type: "string",
|
||||
description:
|
||||
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')",
|
||||
},
|
||||
rule_content: {
|
||||
type: "string",
|
||||
description:
|
||||
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -12,17 +12,26 @@ export const runTerminalCommandTool: Tool = {
|
|||
function: {
|
||||
name: BuiltInToolNames.RunTerminalCommand,
|
||||
description:
|
||||
"Run a terminal command in the current directory. The shell is not stateful and will not remember any previous commands. Do NOT perform actions requiring special/admin priveleges.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["command"],
|
||||
properties: {
|
||||
command: {
|
||||
type: "string",
|
||||
description:
|
||||
"The command to run. This will be passed directly into the IDE shell.",
|
||||
"Run a terminal command in the current directory.\
|
||||
The shell is not stateful and will not remember any previous commands.\
|
||||
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
|
||||
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
|
||||
Do NOT perform actions requiring special/admin privileges.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["command"],
|
||||
properties: {
|
||||
command: {
|
||||
type: "string",
|
||||
description:
|
||||
"The command to run. This will be passed directly into the IDE shell.",
|
||||
},
|
||||
waitForCompletion: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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: {
|
||||
|
|
|
|||
52
core/tools/implementations/createRuleBlock.ts
Normal file
52
core/tools/implementations/createRuleBlock.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
import * as YAML from "yaml";
|
||||
import { ToolImpl } from ".";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
export interface CreateRuleBlockArgs {
|
||||
rule_name: string;
|
||||
rule_content: string;
|
||||
}
|
||||
|
||||
export const createRuleBlockImpl: ToolImpl = async (
|
||||
args: CreateRuleBlockArgs,
|
||||
extras,
|
||||
) => {
|
||||
// Sanitize rule name for use in filename (remove special chars, replace spaces with dashes)
|
||||
const safeRuleName = args.rule_name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s-]/g, "")
|
||||
.replace(/\s+/g, "-");
|
||||
|
||||
const ruleBlock: ConfigYaml = {
|
||||
name: args.rule_name,
|
||||
version: "0.0.1",
|
||||
rules: [
|
||||
// This can be either a string or an object with {name, rule}
|
||||
// Since we want a simple rule, we use the string format
|
||||
args.rule_content,
|
||||
],
|
||||
};
|
||||
|
||||
// Convert the rule block to YAML
|
||||
const ruleYaml = YAML.stringify(ruleBlock);
|
||||
|
||||
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
|
||||
const rulesDirUri = joinPathsToUri(
|
||||
localContinueDir,
|
||||
".continue",
|
||||
"rules",
|
||||
`${safeRuleName}.yaml`,
|
||||
);
|
||||
|
||||
await extras.ide.writeFile(rulesDirUri, ruleYaml);
|
||||
await extras.ide.openFile(rulesDirUri);
|
||||
|
||||
return [
|
||||
{
|
||||
name: "Rule Block Created",
|
||||
description: `Created ${args.rule_name} rule`,
|
||||
content: ruleYaml,
|
||||
},
|
||||
];
|
||||
};
|
||||
334
core/tools/implementations/runTerminalCommand.test.ts
Normal file
334
core/tools/implementations/runTerminalCommand.test.ts
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import * as childProcess from "node:child_process";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { IDE, ToolExtras } from "../..";
|
||||
import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
|
||||
import { runTerminalCommandImpl } from "./runTerminalCommand";
|
||||
|
||||
// We're using real child processes, so ensure these aren't mocked
|
||||
jest.unmock("node:child_process");
|
||||
jest.unmock("node:util");
|
||||
|
||||
describe("runTerminalCommandImpl", () => {
|
||||
// Setup mocks and spies
|
||||
const mockGetIdeInfo = jest.fn();
|
||||
const mockGetWorkspaceDirs = jest.fn();
|
||||
const mockOnPartialOutput = jest.fn();
|
||||
const mockRunCommand = jest.fn();
|
||||
|
||||
// Use a simple approach to ensure background processes are terminated
|
||||
let testPid: number | null = null;
|
||||
|
||||
// Create a temp directory for our tests
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'terminal-command-test-'));
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
|
||||
// Setup backgrounded processes handling - don't mock, just make sure it's empty
|
||||
// Get any processes that might be already tracked and clear them
|
||||
const processMap = (processBackgroundStates as any).processTerminalBackgroundStates;
|
||||
if (processMap && typeof processMap.clear === 'function') {
|
||||
processMap.clear();
|
||||
}
|
||||
|
||||
// Setup IDE mocks
|
||||
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
|
||||
mockGetWorkspaceDirs.mockReturnValue(Promise.resolve([`file://${tempDir}`]));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean up any lingering test processes
|
||||
if (testPid !== null) {
|
||||
try {
|
||||
// Platform-independent way to kill a process
|
||||
if (process.platform === 'win32') {
|
||||
await new Promise(resolve => {
|
||||
childProcess.exec(`taskkill /F /PID ${testPid}`, () => resolve(null));
|
||||
});
|
||||
} else {
|
||||
process.kill(testPid);
|
||||
}
|
||||
} catch (e) {
|
||||
// Process might already be gone, ignore
|
||||
}
|
||||
testPid = null;
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
// Clean up the temp directory after tests
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Helper function to create a ToolExtras object
|
||||
const createMockExtras = (overrides: Partial<{
|
||||
onPartialOutput?: jest.Mock;
|
||||
remoteName?: string;
|
||||
}> = {}): ToolExtras => {
|
||||
// Update IDE info if remoteName is provided
|
||||
if (overrides.remoteName) {
|
||||
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: overrides.remoteName }));
|
||||
}
|
||||
|
||||
// Create a minimally compliant IDE mock
|
||||
const mockIde = {
|
||||
getIdeInfo: mockGetIdeInfo,
|
||||
getWorkspaceDirs: mockGetWorkspaceDirs,
|
||||
runCommand: mockRunCommand,
|
||||
// Add stubs for other required IDE methods
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
};
|
||||
|
||||
// Create a base ToolExtras object with required properties
|
||||
const baseExtras = {
|
||||
ide: mockIde as unknown as IDE,
|
||||
llm: {} as any,
|
||||
fetch: {} as any,
|
||||
tool: {} as any,
|
||||
toolCallId: "test-tool-call"
|
||||
} as ToolExtras;
|
||||
|
||||
// Apply overrides
|
||||
if (overrides.onPartialOutput) {
|
||||
baseExtras.onPartialOutput = overrides.onPartialOutput;
|
||||
}
|
||||
|
||||
return baseExtras;
|
||||
};
|
||||
|
||||
it("should execute a command synchronously and capture output", async () => {
|
||||
// Use Node.js for cross-platform output generation
|
||||
const command = `node -e "console.log('real test output')"`;
|
||||
const args = { command, waitForCompletion: true };
|
||||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
// Verify real command output
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
expect(result[0].description).toBe("Terminal command output");
|
||||
expect(result[0].content).toContain("real test output");
|
||||
// Verify status field indicates successful completion
|
||||
expect(result[0].status).toBe("Command completed");
|
||||
});
|
||||
|
||||
it("should stream output when onPartialOutput is provided", async () => {
|
||||
// This test uses Node to create a command that outputs data incrementally
|
||||
const command = `node -e "
|
||||
console.log('first output');
|
||||
setTimeout(() => {
|
||||
console.log('second output');
|
||||
console.error('error output');
|
||||
}, 50);
|
||||
"`;
|
||||
|
||||
const args = { command, waitForCompletion: true };
|
||||
const mockOutputFn = jest.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
// Execute the command with streaming
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
// Verify onPartialOutput was called with increasing content
|
||||
expect(mockOutputFn).toHaveBeenCalled();
|
||||
|
||||
// Verify final result has all output
|
||||
expect(result[0].content).toContain('first output');
|
||||
expect(result[0].content).toContain('second output');
|
||||
expect(result[0].content).toContain('error output');
|
||||
// Verify status field indicates successful completion
|
||||
expect(result[0].status).toBe("Command completed");
|
||||
|
||||
// Verify that initial streaming updates have empty status for regular commands
|
||||
const firstCall = mockOutputFn.mock.calls[0][0];
|
||||
if (firstCall && typeof firstCall === 'object') {
|
||||
const contextItems = (firstCall as any).contextItems;
|
||||
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
|
||||
// For commands with waitForCompletion=true, status should be empty while streaming
|
||||
expect(contextItems[0].status).toBe("");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("should run commands in background when waitForCompletion is false", async () => {
|
||||
// Create a self-identifying background process that writes its PID
|
||||
// to a file we can access to kill it later
|
||||
const pidFile = path.join(tempDir, 'test-pid.txt');
|
||||
|
||||
// This script creates a long-running process and writes its PID to our file
|
||||
// Using a fixed duration timeout so we can be sure to clean it up
|
||||
const command = `node -e "
|
||||
const fs = require('fs');
|
||||
console.log('starting background process with PID: ' + process.pid);
|
||||
fs.writeFileSync('${pidFile}', process.pid.toString());
|
||||
setTimeout(() => {
|
||||
console.log('background process completed');
|
||||
}, 500);
|
||||
"`;
|
||||
|
||||
const args = { command, waitForCompletion: false };
|
||||
const mockOutputFn = jest.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
// Result should indicate background running in either content or status
|
||||
expect(result[0].content || result[0].status).toContain("running in the background");
|
||||
// Verify status field indicates background running
|
||||
expect(result[0].status).toBe("Command is running in the background...");
|
||||
|
||||
// Initial notification should indicate background running
|
||||
expect(mockOutputFn).toHaveBeenCalled();
|
||||
// Check the first call contains background running message
|
||||
const firstCallData = mockOutputFn.mock.calls[0][0];
|
||||
if (firstCallData && typeof firstCallData === 'object') {
|
||||
const contextItems = (firstCallData as any).contextItems;
|
||||
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
|
||||
expect(contextItems[0].content).toContain("");
|
||||
expect(contextItems[0].status).toMatch(/Command is running in the background.../);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait a bit to make sure the PID file is written
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Read the PID file to get the process ID so we can kill it later
|
||||
if (fs.existsSync(pidFile)) {
|
||||
testPid = Number(fs.readFileSync(pidFile, 'utf-8'));
|
||||
}
|
||||
|
||||
// Wait a bit longer for the process to complete and onPartialOutput to be called again
|
||||
await new Promise(resolve => setTimeout(resolve, 400));
|
||||
|
||||
// Check for background process completion message in mockOutputFn calls
|
||||
// Note: This is optional and depends on timing, so we don't want to strictly enforce it
|
||||
let foundCompletionMessage = false;
|
||||
|
||||
for (let i = 0; i < mockOutputFn.mock.calls.length; i++) {
|
||||
const call = mockOutputFn.mock.calls[i][0];
|
||||
if (call && typeof call === 'object') {
|
||||
const contextItems = (call as any).contextItems;
|
||||
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
|
||||
if (contextItems[0].status === "\nBackground command completed" ||
|
||||
(contextItems[0].status && contextItems[0].status.includes("Background command"))) {
|
||||
foundCompletionMessage = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we found any completion message in the output, great!
|
||||
// But we won't fail the test if we didn't, since it may be timing-dependent
|
||||
if (mockOutputFn.mock.calls.length > 1) {
|
||||
expect(foundCompletionMessage || true).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it("should handle remote environments", async () => {
|
||||
// We'll keep mocking for remote environments as we can't test those directly
|
||||
const args = { command: "echo 'test'", waitForCompletion: true };
|
||||
const extras = createMockExtras({ remoteName: "ssh" });
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
// In remote environments, it should use the IDE's runCommand
|
||||
expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'");
|
||||
// Match the actual output message
|
||||
expect(result[0].content).toContain("Terminal output not available");
|
||||
expect(result[0].content).toContain("SSH environments");
|
||||
// Verify status field indicates command failed in remote environments
|
||||
expect(result[0].status).toBe("Command failed");
|
||||
});
|
||||
|
||||
it("should handle errors when executing invalid commands", async () => {
|
||||
// Use a command that should fail on any platform
|
||||
const args = { command: "non-existent-command-xyz", waitForCompletion: true };
|
||||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
expect(result[0].description).toBe("Terminal command output");
|
||||
|
||||
// The exact error message varies by platform, but should contain error information
|
||||
const errorContent = result[0].content;
|
||||
expect(
|
||||
errorContent.includes("Command failed") ||
|
||||
errorContent.includes("not found") ||
|
||||
errorContent.includes("recognized") ||
|
||||
/error/i.test(errorContent)
|
||||
).toBe(true);
|
||||
|
||||
// Verify status field indicates command failure
|
||||
expect(result[0].status).toContain("Command failed with:");
|
||||
});
|
||||
|
||||
it("should handle error situations gracefully", async () => {
|
||||
// Use Node.js script that writes to stderr for cross-platform testing
|
||||
const command = `node -e "process.stderr.write('This is an error message'); process.exit(1)"`;
|
||||
const args = { command, waitForCompletion: true };
|
||||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
// Verify we still get a result with a name and description
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
expect(result[0].description).toBe("Terminal command output");
|
||||
|
||||
// The command should have executed and returned content
|
||||
expect(result[0].content).toBeDefined();
|
||||
|
||||
// We should see the error message we wrote to stderr
|
||||
expect(result[0].content).toContain("This is an error message");
|
||||
|
||||
// Verify status field indicates command failure - the exact message format can vary
|
||||
// between different node versions and platforms
|
||||
expect(result[0].status).toContain("Command failed");
|
||||
});
|
||||
|
||||
it("should set appropriate status when a command completes successfully", async () => {
|
||||
// Use a simple command that will succeed
|
||||
const command = `node -e "console.log('success test')"`;
|
||||
const args = { command, waitForCompletion: true };
|
||||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
expect(result[0].content).toContain("success test");
|
||||
// Verify status field for successful command
|
||||
expect(result[0].status).toBe("Command completed");
|
||||
});
|
||||
|
||||
it("should include status info for background commands in non-streaming mode", async () => {
|
||||
// Use a simple background command
|
||||
const command = `node -e "setTimeout(() => console.log('done'), 300)"`;
|
||||
const args = { command, waitForCompletion: false };
|
||||
// No streaming in this test (no onPartialOutput)
|
||||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
// Verify both content and status fields for background commands
|
||||
expect(result[0].content).toBe("Command is running in the background...");
|
||||
expect(result[0].status).toBe("Command is running in the background...");
|
||||
});
|
||||
});
|
||||
|
|
@ -3,42 +3,270 @@ import util from "node:util";
|
|||
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ToolImpl } from ".";
|
||||
import { isProcessBackgrounded, removeBackgroundedProcess } from "../../util/processTerminalBackgroundStates";
|
||||
|
||||
const asyncExec = util.promisify(childProcess.exec);
|
||||
|
||||
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
||||
// Default to waiting for completion if not specified
|
||||
const waitForCompletion = args.waitForCompletion !== false;
|
||||
const ideInfo = await extras.ide.getIdeInfo();
|
||||
const toolCallId = extras.toolCallId || "";
|
||||
|
||||
if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") {
|
||||
try {
|
||||
const output = await asyncExec(args.command, {
|
||||
cwd: fileURLToPath((await extras.ide.getWorkspaceDirs())[0]),
|
||||
// For streaming output
|
||||
if (extras.onPartialOutput) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const getWorkspaceDirsPromise = extras.ide.getWorkspaceDirs();
|
||||
getWorkspaceDirsPromise
|
||||
.then((workspaceDirs) => {
|
||||
const cwd = fileURLToPath(workspaceDirs[0]);
|
||||
let terminalOutput = "";
|
||||
|
||||
if (!waitForCompletion) {
|
||||
const status = "Command is running in the background...";
|
||||
if (extras.onPartialOutput) {
|
||||
extras.onPartialOutput({
|
||||
toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: "",
|
||||
status: status,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Use spawn instead of exec to get streaming output
|
||||
const childProc = childProcess.spawn(args.command, {
|
||||
cwd,
|
||||
shell: true,
|
||||
});
|
||||
|
||||
childProc.stdout?.on("data", (data) => {
|
||||
// Skip if this process has been backgrounded
|
||||
if (isProcessBackgrounded(toolCallId)) return;
|
||||
|
||||
const newOutput = data.toString();
|
||||
terminalOutput += newOutput;
|
||||
|
||||
// Send partial output to UI
|
||||
if (extras.onPartialOutput) {
|
||||
const status = waitForCompletion ? "" : "Command is running in the background...";
|
||||
extras.onPartialOutput({
|
||||
toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: terminalOutput,
|
||||
status: status,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
childProc.stderr?.on("data", (data) => {
|
||||
// Skip if this process has been backgrounded
|
||||
if (isProcessBackgrounded(toolCallId)) return;
|
||||
|
||||
const newOutput = data.toString();
|
||||
terminalOutput += newOutput;
|
||||
|
||||
// Send partial output to UI, status is not required
|
||||
if (extras.onPartialOutput) {
|
||||
extras.onPartialOutput({
|
||||
toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: terminalOutput,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// If we don't need to wait for completion, resolve immediately
|
||||
if (!waitForCompletion) {
|
||||
const status = "Command is running in the background...";
|
||||
resolve([
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: terminalOutput,
|
||||
status: status,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
childProc.on("close", (code) => {
|
||||
// If this process has been backgrounded, clean it up from the map and return
|
||||
if (isProcessBackgrounded(toolCallId)) {
|
||||
removeBackgroundedProcess(toolCallId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!waitForCompletion) {
|
||||
// Already resolved, just update the UI with final output
|
||||
if (extras.onPartialOutput) {
|
||||
const status = (code === 0 || !code
|
||||
? "\nBackground command completed"
|
||||
: `\nBackground command failed with exit code ${code}`)
|
||||
extras.onPartialOutput({
|
||||
toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: terminalOutput,
|
||||
status: status,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Normal completion, resolve now
|
||||
if (code === 0) {
|
||||
const status = "Command completed";
|
||||
resolve([
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: terminalOutput,
|
||||
status: status
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
const status = `Command failed with exit code ${code}`;
|
||||
resolve([
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content:
|
||||
terminalOutput,
|
||||
status: status,
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
childProc.on("error", (error) => {
|
||||
// If this process has been backgrounded, clean it up from the map and return
|
||||
if (isProcessBackgrounded(toolCallId)) {
|
||||
removeBackgroundedProcess(toolCallId);
|
||||
return;
|
||||
}
|
||||
|
||||
reject(error);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(error);
|
||||
});
|
||||
} catch (error: any) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: output.stdout ?? "",
|
||||
},
|
||||
];
|
||||
} catch (error: any) {
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: error.stderr || error.stdout || error.toString(),
|
||||
},
|
||||
];
|
||||
} else {
|
||||
// Fallback to non-streaming for older clients
|
||||
const workspaceDirs = await extras.ide.getWorkspaceDirs();
|
||||
const cwd = fileURLToPath(workspaceDirs[0]);
|
||||
|
||||
if (!waitForCompletion) {
|
||||
// For non-streaming but also not waiting for completion, use spawn
|
||||
// but don't attach any listeners other than error
|
||||
try {
|
||||
// Use spawn instead of exec but don't wait
|
||||
const childProc = childProcess.spawn(args.command, {
|
||||
cwd,
|
||||
shell: true,
|
||||
// Detach the process so it's not tied to the parent
|
||||
detached: true,
|
||||
// Redirect to /dev/null equivalent (works cross-platform)
|
||||
stdio: 'ignore',
|
||||
});
|
||||
|
||||
// Even for detached processes, add event handlers to clean up the background process map
|
||||
childProc.on("close", () => {
|
||||
if (isProcessBackgrounded(toolCallId)) {
|
||||
removeBackgroundedProcess(toolCallId);
|
||||
}
|
||||
});
|
||||
|
||||
childProc.on("error", () => {
|
||||
if (isProcessBackgrounded(toolCallId)) {
|
||||
removeBackgroundedProcess(toolCallId);
|
||||
}
|
||||
});
|
||||
|
||||
// Unref the child to allow the Node.js process to exit
|
||||
childProc.unref();
|
||||
const status = "Command is running in the background...";
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: status,
|
||||
status: status,
|
||||
},
|
||||
];
|
||||
} catch (error: any) {
|
||||
const status = `Command failed with: ${error.message || error.toString()}`;
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: status,
|
||||
status: status
|
||||
},
|
||||
];
|
||||
}
|
||||
} else {
|
||||
// Standard execution, waiting for completion
|
||||
try {
|
||||
const output = await asyncExec(args.command, { cwd });
|
||||
const status = "Command completed";
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: output.stdout ?? "",
|
||||
status: status,
|
||||
},
|
||||
];
|
||||
} catch (error: any) {
|
||||
const status = `Command failed with: ${error.message || error.toString()}`;
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: error.stderr ?? error.toString(),
|
||||
status: status,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For remote environments, just run the command
|
||||
// Note: waitForCompletion is not supported in remote environments yet
|
||||
await extras.ide.runCommand(args.command);
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content:
|
||||
"[Terminal output not available. This is only available in local development environments and not in SSH environments for example.]",
|
||||
"Terminal output not available. This is only available in local development environments and not in SSH environments for example.",
|
||||
status: "Command failed",
|
||||
},
|
||||
];
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { createNewFileTool } from "./definitions/createNewFile";
|
||||
import { createRuleBlock } from "./definitions/createRuleBlock";
|
||||
import { editFileTool } from "./definitions/editFile";
|
||||
import { globSearchTool } from "./definitions/globSearch";
|
||||
import { grepSearchTool } from "./definitions/grepSearch";
|
||||
|
|
@ -14,14 +15,13 @@ export const allTools = [
|
|||
editFileTool,
|
||||
createNewFileTool,
|
||||
runTerminalCommandTool,
|
||||
|
||||
grepSearchTool,
|
||||
globSearchTool,
|
||||
searchWebTool,
|
||||
viewDiffTool,
|
||||
readCurrentlyOpenFileTool,
|
||||
|
||||
lsTool,
|
||||
createRuleBlock,
|
||||
// replacing with ls tool for now
|
||||
// viewSubdirectoryTool,
|
||||
// viewRepoMapTool,
|
||||
|
|
|
|||
|
|
@ -52,7 +52,6 @@ class FileSystemIde implements IDE {
|
|||
remoteConfigServerUrl: undefined,
|
||||
remoteConfigSyncPeriod: 60,
|
||||
userToken: "",
|
||||
enableControlServerBeta: false,
|
||||
continueTestEnvironment: "none",
|
||||
pauseCodebaseIndexOnStart: false,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -4,7 +4,11 @@ import { Session, SessionMetadata } from "../index.js";
|
|||
import { ListHistoryOptions } from "../protocol/core.js";
|
||||
|
||||
import { NEW_SESSION_TITLE } from "./constants.js";
|
||||
import { getSessionFilePath, getSessionsListPath } from "./paths.js";
|
||||
import {
|
||||
getSessionFilePath,
|
||||
getSessionsFolderPath,
|
||||
getSessionsListPath,
|
||||
} from "./paths.js";
|
||||
function safeParseArray<T>(
|
||||
value: string,
|
||||
errorMessage: string = "Error parsing array",
|
||||
|
|
@ -67,6 +71,10 @@ class HistoryManager {
|
|||
);
|
||||
}
|
||||
|
||||
clearAll() {
|
||||
fs.rmSync(getSessionsFolderPath(), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
load(sessionId: string): Session {
|
||||
try {
|
||||
const sessionFile = getSessionFilePath(sessionId);
|
||||
|
|
|
|||
71
core/util/processTerminalBackgroundStates.test.ts
Normal file
71
core/util/processTerminalBackgroundStates.test.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import {
|
||||
markProcessAsBackgrounded,
|
||||
isProcessBackgrounded,
|
||||
removeBackgroundedProcess
|
||||
} from './processTerminalBackgroundStates';
|
||||
|
||||
describe('processTerminalBackgroundStates', () => {
|
||||
beforeEach(() => {
|
||||
// Clear any backgrounded processes before each test
|
||||
const backgroundedProcesses = Array.from(
|
||||
Object.getOwnPropertySymbols(global)
|
||||
).find(symbol => String(symbol) === 'Symbol(processTerminalBackgroundStates)');
|
||||
|
||||
if (backgroundedProcesses) {
|
||||
// Reset the map by reimporting the module
|
||||
jest.resetModules();
|
||||
}
|
||||
});
|
||||
|
||||
test('should mark a process as backgrounded', () => {
|
||||
const toolCallId = 'test-123';
|
||||
markProcessAsBackgrounded(toolCallId);
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(true);
|
||||
});
|
||||
|
||||
test('should correctly identify non-backgrounded processes', () => {
|
||||
const toolCallId = 'test-123';
|
||||
const anotherToolCallId = 'test-456';
|
||||
|
||||
markProcessAsBackgrounded(toolCallId);
|
||||
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(true);
|
||||
expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
|
||||
});
|
||||
|
||||
test('should remove a process from backgrounded state', () => {
|
||||
const toolCallId = 'test-123';
|
||||
|
||||
markProcessAsBackgrounded(toolCallId);
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(true);
|
||||
|
||||
removeBackgroundedProcess(toolCallId);
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(false);
|
||||
});
|
||||
|
||||
test('should handle removing non-existent processes', () => {
|
||||
const toolCallId = 'test-123';
|
||||
|
||||
// Should not throw an error
|
||||
removeBackgroundedProcess(toolCallId);
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(false);
|
||||
});
|
||||
|
||||
test('should handle multiple processes', () => {
|
||||
const toolCallId1 = 'test-123';
|
||||
const toolCallId2 = 'test-456';
|
||||
const toolCallId3 = 'test-789';
|
||||
|
||||
markProcessAsBackgrounded(toolCallId1);
|
||||
markProcessAsBackgrounded(toolCallId2);
|
||||
|
||||
expect(isProcessBackgrounded(toolCallId1)).toBe(true);
|
||||
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
|
||||
expect(isProcessBackgrounded(toolCallId3)).toBe(false);
|
||||
|
||||
removeBackgroundedProcess(toolCallId1);
|
||||
|
||||
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
|
||||
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
|
||||
});
|
||||
});
|
||||
17
core/util/processTerminalBackgroundStates.ts
Normal file
17
core/util/processTerminalBackgroundStates.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// Track which processes have been backgrounded
|
||||
const processTerminalBackgroundStates = new Map<string, boolean>();
|
||||
|
||||
// Function to mark a process as backgrounded
|
||||
export function markProcessAsBackgrounded(toolCallId: string): void {
|
||||
processTerminalBackgroundStates.set(toolCallId, true);
|
||||
}
|
||||
|
||||
// Function to check if a process is backgrounded
|
||||
export function isProcessBackgrounded(toolCallId: string): boolean {
|
||||
return processTerminalBackgroundStates.has(toolCallId);
|
||||
}
|
||||
|
||||
// Function to remove a process from the backgrounded processes map
|
||||
export function removeBackgroundedProcess(toolCallId: string): void {
|
||||
processTerminalBackgroundStates.delete(toolCallId);
|
||||
}
|
||||
|
|
@ -9,9 +9,10 @@ Agent offers the same functionality as Chat, while also including tools in the r
|
|||
|
||||
## The tool handshake
|
||||
|
||||
Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file.
|
||||
Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file.
|
||||
|
||||
The following handshake describes how Agent uses tools:
|
||||
|
||||
1. In Agent mode, available tools are sent along with `user` chat requests
|
||||
2. The model can choose to include a tool call in its response
|
||||
3. The user gives permission. This step is skipped if the policy for that tool is set to `Automatic`
|
||||
|
|
@ -32,7 +33,8 @@ Continue includes several built-in tools which provide the model access to IDE f
|
|||
- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model
|
||||
- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project
|
||||
- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root
|
||||
- **Search web** (`builtin_search_web`): Perform a web search to get top results
|
||||
- **Search web** (`builtin_search_web`): Perform a web search to get top results
|
||||
- **View diff** (`builtin_view_diff`): View the current working git diff
|
||||
- **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map)
|
||||
- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project
|
||||
- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project
|
||||
- **Create Rule Block** (`builtin_create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ To add a single documentation site, we recommend using the **Add Documentation**
|
|||
|
||||
In the **Add Documentation** Form, enter a `Title` and `Start URL` for the site.
|
||||
|
||||
- `Title`: The name of the documentation site, used for identification in the UI
|
||||
- `Title`: The name of the documentation site, used for identification in the UI.
|
||||
- `Start URL`: The URL where the indexing process should begin.
|
||||
|
||||
Indexing will begin upon submission. Progress can be viewed in the form or later in the `@docs indexes` section of the `More` page.
|
||||
|
|
@ -154,9 +154,9 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo
|
|||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### Github
|
||||
### GitHub
|
||||
|
||||
The Github API rate limits public requests to 60 per hour. If you want to reliably index Github repos, you can add a github token to your config file:
|
||||
The GitHub API rate limits public requests to 60 per hour. If you want to reliably index GitHub repos, you can add a github token to your config file:
|
||||
|
||||
<Tabs groupId="config-example">
|
||||
<TabItem value="yaml" label="YAML">
|
||||
|
|
@ -223,7 +223,7 @@ Chromium crawling has been deprecated
|
|||
Further notes:
|
||||
|
||||
- If the site is only locally accessible, the default crawler will fail anyways and fall back to the local crawler. `useLocalCrawling` is especially useful if the URL itself is confidential.
|
||||
- For Github Repos this has no effect because only the Github Crawler will be used, and if the repo is private it can only be accessed with a priveleged Github token anyways.
|
||||
- For GitHub Repos this has no effect because only the GitHub Crawler will be used, and if the repo is private it can only be accessed with a priveleged GitHub token anyways.
|
||||
|
||||
## Managing your docs indexes
|
||||
|
||||
|
|
@ -237,6 +237,7 @@ You can view indexing statuses and manage your documentation sites from the `@do
|
|||

|
||||
|
||||
You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page
|
||||
|
||||

|
||||
|
||||
You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`.
|
||||
|
|
@ -327,7 +328,7 @@ The following configuration example includes:
|
|||
- Examples of both public and private documentation sources
|
||||
- A custom embeddings provider
|
||||
- A reranker model available, with reranking parameters customized
|
||||
- A Github token to enable Github crawling
|
||||
- A GitHub token to enable GitHub crawling
|
||||
|
||||
<Tabs groupId="config-example">
|
||||
<TabItem value="yaml" label="YAML">
|
||||
|
|
|
|||
|
|
@ -5,15 +5,55 @@ keywords: [rules, .continuerules, system, prompt, message]
|
|||
|
||||
# Rules
|
||||
|
||||
Rules are used to provide instructions to **chat** models. They are inserted into the system message for all chat requests. Rules are _only_ used during Chat, they are not used for autocomplete or other roles.
|
||||
Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests.
|
||||
|
||||
## Hub `rules` blocks
|
||||
Rules are **_NOT_** included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx).
|
||||
|
||||
Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
|
||||
You can view the current rules by clicking the pen icon above the main toolbar:
|
||||
|
||||

|
||||
|
||||
To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#chat-system-message)).
|
||||
|
||||
## `rules` blocks
|
||||
|
||||
Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally.
|
||||
|
||||
:::info Automatically create local rule blocks
|
||||
When in Agent mode, you can simply prompt the agent to create a rule for you.
|
||||
|
||||
For example, you can say "Create a rule for this", and a rule will be created for you in `~/.continue/rules` based on your conversation.
|
||||
:::
|
||||
|
||||
Rules blocks can be simple text, or have the following properties:
|
||||
|
||||
- `name` (**required**): A display name/title for the rule
|
||||
- `rule` (**required**): The text content of the rule
|
||||
|
||||
Examples:
|
||||
|
||||
```yaml title="config.yaml"
|
||||
rules:
|
||||
- uses: myprofile/my-mood-setter
|
||||
with:
|
||||
TONE: consise
|
||||
- Always annotate Python functions with their parameter and return types
|
||||
- Always write Google style docstrings for functions and classes
|
||||
- name: Server-side components
|
||||
rule: When writing Next.js React components, use server-side components where possible instead of client components.
|
||||
```
|
||||
|
||||
## Chat System Message
|
||||
|
||||
Continue includes a simple default system message for [Chat](../../chat/how-to-use-it.md) and [Agent](../../agent/how-to-use-it.md) requests, to help the model provide reliable codeblock formats in its output.
|
||||
|
||||
This can be viewed in the rules section of the toolbar (see above), or visit the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4)
|
||||
|
||||
Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](../../reference.md#models).
|
||||
|
||||
## `.continuerules`
|
||||
|
||||
You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules.
|
||||
You can create project-specific rules by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules.
|
||||
|
||||
### Simple Examples
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import TabItem from "@theme/TabItem";
|
|||
import Tabs from "@theme/Tabs";
|
||||
|
||||
:::info
|
||||
To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs:[Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html)
|
||||
To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs: [Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html)
|
||||
:::
|
||||
|
||||
## Configuration
|
||||
|
|
@ -55,7 +55,7 @@ Currently, the setup for the models provided by Ask Sage is to support the follo
|
|||
|
||||
More models, functionalities and documentation will be added in the future for Ask Sage Integration.
|
||||
|
||||
> We recommend to utilize the`OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities.
|
||||
> We recommend to utilize the `OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities.
|
||||
|
||||
## Ask Sage Documentation
|
||||
|
||||
|
|
|
|||
|
|
@ -81,8 +81,8 @@ We recommend configuring **Qwen/Qwen2.5-Coder-7B-Instruct** as your autocomplete
|
|||
|
||||
## Embeddings model
|
||||
|
||||
SiliconFlow provide some embeddings models, [Click here](https://siliconflow.cn/models) to see a list of embeddings models.
|
||||
SiliconFlow provide some embeddings models. [Click here](https://siliconflow.cn/models) to see a list of embeddings models.
|
||||
|
||||
## Reranking model
|
||||
|
||||
SiliconFlow provide some reranking models, [Click here](https://siliconflow.cn/models) to see a list of reranking models.
|
||||
SiliconFlow provide some reranking models. [Click here](https://siliconflow.cn/models) to see a list of reranking models.
|
||||
|
|
|
|||
|
|
@ -10,6 +10,36 @@ import Tabs from "@theme/Tabs";
|
|||
|
||||
When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file.
|
||||
|
||||
Generally speaking, models proficient in chat and edit can also be used for applying code.
|
||||
## Recommended Apply models
|
||||
|
||||
Explore apply models in [the hub](https://hub.continue.dev/explore/models?roles=apply).
|
||||
We recommend [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can get an API key [here](https://app.relace.ai/settings/api-keys).
|
||||
|
||||
However, most Chat models can also be used for applying code changes. We recommend smaller/cheaper models for the task, such as Claude 3.5 Haiku.
|
||||
|
||||
:::info
|
||||
Explore all apply models in [the Hub](https://hub.continue.dev/explore/models?roles=apply)
|
||||
:::
|
||||
|
||||
## Prompt templating
|
||||
|
||||
You can customize the prompt template used for applying code changes by setting the `promptTemplates.apply` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating.
|
||||
|
||||
Available variables for the apply template:
|
||||
|
||||
- `{{{original_code}}}` - The original code before changes
|
||||
- `{{{new_code}}}` - The new code after changes
|
||||
|
||||
Example:
|
||||
|
||||
```yaml
|
||||
models:
|
||||
- name: My Custom Apply Template
|
||||
provider: anthropic
|
||||
model: claude-3-5-sonnet-latest
|
||||
promptTemplates:
|
||||
apply: |
|
||||
Original: {{{original_code}}}
|
||||
New: {{{new_code}}}
|
||||
|
||||
Please generate the final code without any markers or explanations.
|
||||
```
|
||||
|
|
|
|||
|
|
@ -257,6 +257,14 @@ If your local machine can run an 8B parameter model, then we recommend running L
|
|||
model: llama3.1:8b
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="Msty">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Llama 3.1 8B
|
||||
provider: msty
|
||||
model: llama3.1:8b
|
||||
```
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
</TabItem>
|
||||
<TabItem value="json" label="JSON">
|
||||
|
|
@ -287,6 +295,19 @@ If your local machine can run an 8B parameter model, then we recommend running L
|
|||
}
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="Msty">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama 3.1 8B",
|
||||
"provider": "msty",
|
||||
"model": "llama3.1-8b"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
|
@ -325,6 +346,14 @@ If your local machine can run a 16B parameter model, then we recommend running D
|
|||
model: deepseek-coder-v2:16b
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="Msty">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: DeepSeek Coder 2 16B
|
||||
provider: msty
|
||||
model: deepseek-coder-v2:16b
|
||||
```
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
</TabItem>
|
||||
<TabItem value="json" label="JSON">
|
||||
|
|
@ -356,6 +385,19 @@ If your local machine can run a 16B parameter model, then we recommend running D
|
|||
}
|
||||
```
|
||||
</TabItem>
|
||||
<TabItem value="Msty">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "DeepSeek Coder 2 16B",
|
||||
"provider": "msty",
|
||||
"model": "deepseek-coder-v2:16b"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue