Merge branch 'main' into autocomplete-fixes
This commit is contained in:
commit
9eae04bd69
419 changed files with 16572 additions and 8307 deletions
2
.github/pull_request_template.md
vendored
2
.github/pull_request_template.md
vendored
|
|
@ -9,7 +9,7 @@
|
|||
|
||||
## Screenshots
|
||||
|
||||
[ For visual changes, include screenshots. ]
|
||||
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
|
||||
|
||||
## Testing instructions
|
||||
|
||||
|
|
|
|||
99
.github/workflows/auto-release.yml
vendored
Normal file
99
.github/workflows/auto-release.yml
vendored
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
name: Create Automatic Release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday
|
||||
workflow_dispatch: # Keep manual trigger option
|
||||
|
||||
jobs:
|
||||
create-vscode-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # Needed for creating releases
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Important for getting all tags and commits
|
||||
|
||||
- name: Get latest tag
|
||||
id: get_latest_tag
|
||||
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"
|
||||
echo "New version will be: $new_version"
|
||||
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Create a new draft release with auto-generated release notes
|
||||
gh release create "$NEW_VERSION" \
|
||||
--generate-notes \
|
||||
--title "$NEW_VERSION" \
|
||||
--draft \
|
||||
--latest
|
||||
--prerelease
|
||||
|
||||
create-jetbrains-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # Needed for creating releases
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Important for getting all tags and commits
|
||||
|
||||
- name: Get latest tag
|
||||
id: get_latest_tag
|
||||
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"
|
||||
echo "New version will be: $new_version"
|
||||
echo "NEW_VERSION=$new_version" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Create a new draft release with auto-generated release notes
|
||||
gh release create "$NEW_VERSION" \
|
||||
--generate-notes \
|
||||
--title "$NEW_VERSION" \
|
||||
--draft \
|
||||
--latest
|
||||
--prerelease
|
||||
2
.github/workflows/jetbrains-release.yaml
vendored
2
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -54,7 +54,7 @@ jobs:
|
|||
ref: ${{ github.event.release.tag_name }}
|
||||
|
||||
- name: Import Apple certificate
|
||||
uses: apple-actions/import-codesign-certs@v3
|
||||
uses: apple-actions/import-codesign-certs@v5
|
||||
with:
|
||||
keychain: ${{ github.run_id }}
|
||||
keychain-password: ${{ github.run_id }}
|
||||
|
|
|
|||
39
.github/workflows/preview.yaml
vendored
39
.github/workflows/preview.yaml
vendored
|
|
@ -1,4 +1,4 @@
|
|||
name: Publish Preview Extension
|
||||
name: Publish Pre-release Extension
|
||||
|
||||
on:
|
||||
release:
|
||||
|
|
@ -207,6 +207,7 @@ jobs:
|
|||
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
# 0. Setup git
|
||||
- name: Checkout
|
||||
|
|
@ -242,12 +243,44 @@ jobs:
|
|||
cd extensions/vscode
|
||||
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
|
||||
|
||||
# 4. Update the package.json version and push changes
|
||||
# 4. Create PR with version bump
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Create PR branch
|
||||
run: |
|
||||
BRANCH_NAME="chore/bump-vscode-version-$(date +%Y%m%d-%H%M%S)"
|
||||
git checkout -b $BRANCH_NAME
|
||||
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
|
||||
|
||||
- name: Bump version in package.json
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npm version patch --no-git-tag-version
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@v5
|
||||
with:
|
||||
token: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
|
||||
title: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
|
||||
body: |
|
||||
Automated PR to bump the VS Code extension version after successful pre-release publication.
|
||||
|
||||
- Bumped version in extensions/vscode/package.json to ${{ env.NEW_VERSION }}
|
||||
branch: ${{ env.BRANCH_NAME }}
|
||||
base: main
|
||||
delete-branch: true
|
||||
|
||||
# 5. Update version in package.json
|
||||
# - name: Update version in package.json
|
||||
# run: |
|
||||
# cd extensions/vscode
|
||||
# npm version patch
|
||||
|
||||
# - name: Commit changes
|
||||
# run: |
|
||||
# git config --local user.email "action@github.com"
|
||||
|
|
|
|||
46
.github/workflows/release-config-yaml.yml
vendored
Normal file
46
.github/workflows/release-config-yaml.yml
vendored
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
name: Release @continuedev/config-yaml
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "packages/config-yaml/**"
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm test
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npx semantic-release
|
||||
111
.github/workflows/vscode-version-bump.yml
vendored
Normal file
111
.github/workflows/vscode-version-bump.yml
vendored
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
name: VS Code Extension Version Bump
|
||||
on:
|
||||
schedule:
|
||||
# Runs at 7 AM PST (15:00 UTC) every Friday
|
||||
- cron: "0 15 * * 5"
|
||||
workflow_dispatch:
|
||||
# Allows manual triggering
|
||||
|
||||
jobs:
|
||||
version-bump:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history and tags
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Find and process version tags
|
||||
run: |
|
||||
echo "Starting version bump process..."
|
||||
|
||||
# Find last v1.1.x-vscode tag that's at least 6 days old
|
||||
CURRENT_TIMESTAMP=$(date +%s)
|
||||
SIX_DAYS_AGO=$((CURRENT_TIMESTAMP - 6*24*60*60))
|
||||
echo "Current timestamp: $(date -d @${CURRENT_TIMESTAMP})"
|
||||
echo "Six days ago: $(date -d @${SIX_DAYS_AGO})"
|
||||
|
||||
echo "Looking for v1.1.x-vscode tags..."
|
||||
git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:iso)' refs/tags | grep 'v1\.1\.[0-9]\+-vscode' || echo "No matching tags found"
|
||||
|
||||
LAST_1_1_TAG=$(git for-each-ref --sort=-creatordate --format '%(refname:short) %(creatordate:unix)' refs/tags \
|
||||
| grep 'v1\.1\.[0-9]\+-vscode' \
|
||||
| while read tag timestamp; do
|
||||
if [ $timestamp -le $SIX_DAYS_AGO ]; then
|
||||
echo ${tag% *}
|
||||
break
|
||||
fi
|
||||
done)
|
||||
|
||||
echo "Selected v1.1.x tag: $LAST_1_1_TAG"
|
||||
if [ -z "$LAST_1_1_TAG" ]; then
|
||||
echo "::error::No suitable v1.1.x-vscode tag found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Find last v1.0.y-vscode tag
|
||||
echo "Looking for v1.0.y-vscode tags..."
|
||||
git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' || echo "No matching tags found"
|
||||
|
||||
LAST_1_0_TAG=$(git tag --sort=-v:refname | grep '^v1\.0\.[0-9]\+-vscode' | head -n1)
|
||||
echo "Selected v1.0.y tag: $LAST_1_0_TAG"
|
||||
if [ -z "$LAST_1_0_TAG" ]; then
|
||||
echo "::error::No v1.0.y-vscode tag found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract the y number and increment it
|
||||
Y_NUMBER=$(echo $LAST_1_0_TAG | sed 's/v1\.0\.\([0-9]\+\)-vscode/\1/')
|
||||
NEXT_Y=$((Y_NUMBER + 1))
|
||||
NEW_BRANCH="v1.0.${NEXT_Y}-vscode"
|
||||
NEW_VERSION="1.0.${NEXT_Y}"
|
||||
echo "Current Y number: $Y_NUMBER"
|
||||
echo "Next Y number: $NEXT_Y"
|
||||
echo "New branch name: $NEW_BRANCH"
|
||||
echo "New version: $NEW_VERSION"
|
||||
|
||||
# Create new branch from the v1.1.x tag
|
||||
echo "Creating new branch from $LAST_1_1_TAG..."
|
||||
git checkout $LAST_1_1_TAG
|
||||
git checkout -b $NEW_BRANCH
|
||||
|
||||
# Update the version in package.json
|
||||
echo "Current package.json version:"
|
||||
cat extensions/vscode/package.json | grep version
|
||||
|
||||
echo "Updating version in package.json..."
|
||||
jq ".version = \"$NEW_VERSION\"" extensions/vscode/package.json > temp.json && mv temp.json extensions/vscode/package.json
|
||||
|
||||
echo "New package.json version:"
|
||||
cat extensions/vscode/package.json | grep version
|
||||
|
||||
# Configure git
|
||||
echo "Configuring git..."
|
||||
git config user.name "GitHub Actions Bot"
|
||||
git config user.email "actions@github.com"
|
||||
|
||||
# Commit and push changes
|
||||
echo "Committing changes..."
|
||||
git add extensions/vscode/package.json
|
||||
git commit -m "Bump VS Code extension to ${NEW_VERSION}"
|
||||
|
||||
echo "Pushing branch to origin..."
|
||||
git push origin $NEW_BRANCH
|
||||
|
||||
echo "Version bump process completed successfully!"
|
||||
|
||||
- name: Check for errors
|
||||
if: failure()
|
||||
run: |
|
||||
echo "::error::Failed to process version tags and create new branch"
|
||||
echo "Last few lines of git log:"
|
||||
git log -n 5 --oneline
|
||||
echo "Current git status:"
|
||||
git status
|
||||
echo "Current branches:"
|
||||
git branch -a
|
||||
1
.node-version
Normal file
1
.node-version
Normal file
|
|
@ -0,0 +1 @@
|
|||
20.11.0
|
||||
|
|
@ -26,7 +26,6 @@
|
|||
- [Writing Context Providers](#writing-context-providers)
|
||||
- [Adding an LLM Provider](#adding-an-llm-provider)
|
||||
- [Adding Models](#adding-models)
|
||||
- [Adding Pre-indexed Documentation](#adding-pre-indexed-documentation)
|
||||
- [📐 Continue Architecture](#-continue-architecture)
|
||||
- [Continue VS Code Extension](#continue-vs-code-extension)
|
||||
- [Continue JetBrains Extension](#continue-jetbrains-extension)
|
||||
|
|
@ -140,7 +139,7 @@ Similarly, any changes to `core` or `extensions/vscode` will be automatically in
|
|||
|
||||
#### JetBrains
|
||||
|
||||
See the [`CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBrains extension.
|
||||
See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the JetBrains extension.
|
||||
|
||||
### Our Git Workflow
|
||||
|
||||
|
|
@ -148,7 +147,7 @@ We keep a single permanent branch: `main`. When we are ready to create a "pre-re
|
|||
|
||||
### Testing
|
||||
|
||||
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you resolve the issue before we merge.
|
||||
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge.
|
||||
|
||||
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
|
||||
|
||||
|
|
@ -212,17 +211,13 @@ While any model that works with a supported provider can be used with Continue,
|
|||
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
|
||||
- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
|
||||
|
||||
### Adding Pre-indexed Documentation
|
||||
|
||||
Continue's @docs context provider lets you easily reference entire documentation sites and then uses embeddings to add the most relevant pages to context. To make the experience as smooth as possible, we pre-index many of the most popular documentation sites. If you'd like to add new documentation to this list, just add an object to the list in [preIndexedDocs.ts](./core/indexing/docs/preIndexedDocs.ts). `startUrl` is where the crawler will start and `rootUrl` will filter out any pages not on that site and under the path of `rootUrl`.
|
||||
|
||||
## 📐 Continue Architecture
|
||||
|
||||
Continue consists of 2 parts that are split so that it can be extended to work in other IDEs as easily as possible:
|
||||
|
||||
1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs.
|
||||
|
||||
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/ideProtocol.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
|
||||
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/VsCodeIde.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
|
||||
|
||||
### Continue VS Code Extension
|
||||
|
||||
|
|
|
|||
|
|
@ -44,11 +44,11 @@
|
|||
|
||||

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

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -243,7 +243,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
console.log(`[info] Building ${target}...`);
|
||||
execCmdSync(
|
||||
`npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}`,
|
||||
`npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`,
|
||||
);
|
||||
|
||||
// Download and unzip prebuilt sqlite3 binary for the target
|
||||
|
|
|
|||
21
binary/package-lock.json
generated
21
binary/package-lock.json
generated
|
|
@ -44,13 +44,13 @@
|
|||
"version": "1.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
|
||||
"@aws-sdk/credential-providers": "^3.758.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.63",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
"@modelcontextprotocol/sdk": "^1.5.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
|
|
@ -67,6 +67,7 @@
|
|||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
@ -135,7 +136,8 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"ts-jest": "^29.1.1"
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
|
|
@ -6404,10 +6406,11 @@
|
|||
}
|
||||
},
|
||||
"node_modules/tar-fs": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
|
||||
"integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
|
||||
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chownr": "^1.1.1",
|
||||
"mkdirp-classic": "^0.5.2",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
process.env.IS_BINARY = "true";
|
||||
import { Command } from "commander";
|
||||
import { Core } from "core/core";
|
||||
import { LLMLogFormatter } from "core/llm/logFormatter";
|
||||
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
|
||||
import { IMessenger } from "core/protocol/messenger";
|
||||
import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths";
|
||||
|
|
@ -33,9 +34,8 @@ program.action(async () => {
|
|||
const ide = new IpcIde(messenger);
|
||||
const promptLogsPath = getPromptLogsPath();
|
||||
|
||||
new Core(messenger, ide, async (text) => {
|
||||
fs.appendFileSync(promptLogsPath, text + "\n\n");
|
||||
});
|
||||
const core = new Core(messenger, ide);
|
||||
new LLMLogFormatter(core.llmLogger, fs.createWriteStream(promptLogsPath));
|
||||
|
||||
console.log("[binary] Core started");
|
||||
} catch (e) {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
"eqeqeq": "error",
|
||||
"complexity": ["error", { "max": 38 }],
|
||||
"max-lines-per-function": ["error", { "max": 996 }],
|
||||
"max-statements": ["error", { "max": 112 }],
|
||||
"max-statements": ["error", { "max": 114 }],
|
||||
"max-depth": ["error", { "max": 6 }],
|
||||
"max-nested-callbacks": ["error", { "max": 4 }],
|
||||
"max-params": ["error", { "max": 11 }]
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
getParserForFile,
|
||||
getQueryForFile,
|
||||
} from "../../util/treeSitter";
|
||||
import { findUriInDirs } from "../../util/uri";
|
||||
|
||||
interface FileInfo {
|
||||
imports: { [key: string]: RangeInFileWithContents[] };
|
||||
|
|
@ -44,7 +45,15 @@ export class ImportDefinitionsService {
|
|||
|
||||
let fileContents: string | undefined = undefined;
|
||||
try {
|
||||
fileContents = await this.ide.readFile(filepath);
|
||||
const { foundInDir } = findUriInDirs(
|
||||
filepath,
|
||||
await this.ide.getWorkspaceDirs(),
|
||||
);
|
||||
if (!foundInDir) {
|
||||
return null;
|
||||
} else {
|
||||
fileContents = await this.ide.readFile(filepath);
|
||||
}
|
||||
} catch (err) {
|
||||
// File removed
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -88,7 +88,6 @@ export class RootPathContextService {
|
|||
default:
|
||||
// const type = node.type;
|
||||
// console.log(getSyntaxTreeString(node));
|
||||
// debugger;
|
||||
|
||||
query = await getQueryForFile(
|
||||
filepath,
|
||||
|
|
@ -165,7 +164,6 @@ export class RootPathContextService {
|
|||
)) {
|
||||
const key = RootPathContextService.keyFromNode(parentKey, astNode);
|
||||
// const type = astNode.type;
|
||||
// debugger;
|
||||
|
||||
const foundInCache = this.cache.get(key);
|
||||
const newSnippets =
|
||||
|
|
|
|||
|
|
@ -39,20 +39,28 @@ export class AutocompleteLruCache {
|
|||
// If the query is "co" and we have "c" -> "ontinue" in the cache,
|
||||
// we should return "ntinue" as the completion.
|
||||
// Have to make sure we take the key with shortest length
|
||||
const result = await this.db.get(
|
||||
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
|
||||
truncateSqliteLikePattern(prefix),
|
||||
);
|
||||
|
||||
// Validate that the cached compeltion is a valid completion for the prefix
|
||||
if (result && result.value.startsWith(prefix.slice(result.key.length))) {
|
||||
await this.db.run(
|
||||
"UPDATE cache SET timestamp = ? WHERE key = ?",
|
||||
Date.now(),
|
||||
prefix,
|
||||
const truncatedPrefix = truncateSqliteLikePattern(prefix);
|
||||
try {
|
||||
const result = await this.db.get(
|
||||
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
|
||||
truncatedPrefix,
|
||||
);
|
||||
// And then truncate so we aren't writing something that's already there
|
||||
return result.value.slice(prefix.length - result.key.length);
|
||||
// Validate that the cached completion is a valid completion for the prefix
|
||||
if (
|
||||
result &&
|
||||
result.value.startsWith(truncatedPrefix.slice(result.key.length))
|
||||
) {
|
||||
await this.db.run(
|
||||
"UPDATE cache SET timestamp = ? WHERE key = ?",
|
||||
Date.now(),
|
||||
truncatedPrefix,
|
||||
);
|
||||
// And then truncate so we aren't writing something that's already there
|
||||
return result.value.slice(truncatedPrefix.length - result.key.length);
|
||||
}
|
||||
} catch (e) {
|
||||
// catches e.g. old SQLITE LIKE OR GLOB PATTERN TOO COMPLEX
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
@ -60,13 +68,15 @@ export class AutocompleteLruCache {
|
|||
|
||||
async put(prefix: string, completion: string) {
|
||||
const release = await this.mutex.acquire();
|
||||
|
||||
const truncatedPrefix = truncateSqliteLikePattern(prefix);
|
||||
try {
|
||||
await this.db.run("BEGIN TRANSACTION");
|
||||
|
||||
try {
|
||||
const result = await this.db.get(
|
||||
"SELECT key FROM cache WHERE key = ?",
|
||||
prefix,
|
||||
truncatedPrefix,
|
||||
);
|
||||
|
||||
if (result) {
|
||||
|
|
@ -74,7 +84,7 @@ export class AutocompleteLruCache {
|
|||
"UPDATE cache SET value = ?, timestamp = ? WHERE key = ?",
|
||||
completion,
|
||||
Date.now(),
|
||||
prefix,
|
||||
truncatedPrefix,
|
||||
);
|
||||
} else {
|
||||
const count = await this.db.get(
|
||||
|
|
@ -89,7 +99,7 @@ export class AutocompleteLruCache {
|
|||
|
||||
await this.db.run(
|
||||
"INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)",
|
||||
prefix,
|
||||
truncatedPrefix,
|
||||
completion,
|
||||
Date.now(),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
|
||||
import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
|
||||
import { renderChatMessage } from "../util/messageContent";
|
||||
|
||||
import SlashCommands from "./slash";
|
||||
|
|
@ -7,68 +9,57 @@ import SlashCommands from "./slash";
|
|||
export function slashFromCustomCommand(
|
||||
customCommand: CustomCommand,
|
||||
): SlashCommand {
|
||||
const commandName = customCommand.name.startsWith("/")
|
||||
? customCommand.name.substring(1)
|
||||
: customCommand.name;
|
||||
return {
|
||||
name: customCommand.name,
|
||||
name: commandName,
|
||||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
run: async function* ({ input, llm, history, ide, completionOptions }) {
|
||||
// Remove slash command prefix from input
|
||||
let userInput = input;
|
||||
if (userInput.startsWith(`/${customCommand.name}`)) {
|
||||
userInput = userInput
|
||||
.slice(customCommand.name.length + 1, userInput.length)
|
||||
.trimStart();
|
||||
}
|
||||
|
||||
run: async function* ({
|
||||
input,
|
||||
llm,
|
||||
history,
|
||||
ide,
|
||||
completionOptions,
|
||||
config,
|
||||
selectedCode,
|
||||
fetch,
|
||||
}) {
|
||||
// Render prompt template
|
||||
let promptUserInput: string;
|
||||
let renderedPrompt: string;
|
||||
if (customCommand.prompt.includes("{{{ input }}}")) {
|
||||
promptUserInput = await renderTemplatedString(
|
||||
renderedPrompt = await renderTemplatedString(
|
||||
customCommand.prompt,
|
||||
ide.readFile.bind(ide),
|
||||
{ input: userInput },
|
||||
{ input },
|
||||
);
|
||||
} else {
|
||||
promptUserInput = customCommand.prompt + "\n\n" + userInput;
|
||||
const renderedPromptFile = await renderPromptFileV2(
|
||||
customCommand.prompt,
|
||||
{
|
||||
config,
|
||||
llm,
|
||||
ide,
|
||||
selectedCode,
|
||||
fetch,
|
||||
fullInput: input,
|
||||
embeddingsProvider: config.modelsByRole.embed[0],
|
||||
reranker: config.modelsByRole.rerank[0],
|
||||
},
|
||||
);
|
||||
|
||||
renderedPrompt = renderedPromptFile[1];
|
||||
}
|
||||
|
||||
const messages = [...history];
|
||||
// Find the last chat message with this slash command and replace it with the user input
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const message = messages[i];
|
||||
const { role, content } = message;
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
Array.isArray(content) &&
|
||||
content.some(
|
||||
(part) =>
|
||||
"text" in part && part.text?.startsWith(`/${customCommand.name}`),
|
||||
)
|
||||
) {
|
||||
messages[i] = {
|
||||
...message,
|
||||
content: content.map((part) => {
|
||||
if (
|
||||
"text" in part &&
|
||||
part.text.startsWith(`/${customCommand.name}`)
|
||||
) {
|
||||
return { type: "text", text: promptUserInput };
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
};
|
||||
break;
|
||||
} else if (
|
||||
typeof content === "string" &&
|
||||
content.startsWith(`/${customCommand.name}`)
|
||||
) {
|
||||
messages[i] = { ...message, content: promptUserInput };
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Replaces slash command messages with the rendered prompt
|
||||
// which INCLUDES the input
|
||||
const messages = replaceSlashCommandWithPromptInChatHistory(
|
||||
history,
|
||||
commandName,
|
||||
renderedPrompt,
|
||||
undefined,
|
||||
);
|
||||
|
||||
for await (const chunk of llm.streamChat(
|
||||
messages,
|
||||
|
|
|
|||
|
|
@ -9,9 +9,9 @@ import { defaultConfig } from "./default";
|
|||
|
||||
describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
||||
test("should show only local profile", () => {
|
||||
const profiles = testConfigHandler.listProfiles();
|
||||
const profiles = testConfigHandler.currentOrg.profiles;
|
||||
expect(profiles?.length).toBe(1);
|
||||
expect(profiles?.[0].id).toBe("local");
|
||||
expect(profiles?.[0].profileDescription.id).toBe("local");
|
||||
|
||||
const currentProfile = testConfigHandler.currentProfile;
|
||||
expect(currentProfile?.profileDescription.id).toBe("local");
|
||||
|
|
@ -19,7 +19,7 @@ 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!.models.length).toBe(defaultConfig.models?.length);
|
||||
});
|
||||
|
||||
test.skip("should add a system message from config.ts", async () => {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
||||
import {
|
||||
ControlPlaneClient,
|
||||
|
|
@ -12,6 +12,7 @@ import {
|
|||
IDE,
|
||||
IdeSettings,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
} from "../index.js";
|
||||
import Ollama from "../llm/llms/Ollama.js";
|
||||
import { GlobalContext } from "../util/GlobalContext.js";
|
||||
|
|
@ -25,360 +26,297 @@ import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
|
|||
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
|
||||
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
|
||||
import {
|
||||
OrganizationDescription,
|
||||
OrgWithProfiles,
|
||||
ProfileDescription,
|
||||
ProfileLifecycleManager,
|
||||
SerializedOrgWithProfiles,
|
||||
} from "./ProfileLifecycleManager.js";
|
||||
|
||||
export type { ProfileDescription };
|
||||
|
||||
type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
|
||||
|
||||
// Separately manages saving/reloading each profile
|
||||
|
||||
export class ConfigHandler {
|
||||
private readonly globalContext = new GlobalContext();
|
||||
private additionalContextProviders: IContextProvider[] = [];
|
||||
private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded
|
||||
private selectedProfileId: string | null = null;
|
||||
private localProfileManager: ProfileLifecycleManager;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
private readonly globalContext = new GlobalContext();
|
||||
private globalLocalProfileManager: ProfileLifecycleManager;
|
||||
|
||||
initializedPromise: Promise<void>;
|
||||
private organizations: OrgWithProfiles[] = [];
|
||||
currentProfile: ProfileLifecycleManager | null;
|
||||
currentOrg: OrgWithProfiles;
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly writeLog: (text: string) => Promise<void>,
|
||||
private llmLogger: ILLMLogger,
|
||||
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
|
||||
private readonly didSelectOrganization?: (orgId: string | null) => void,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
this.writeLog = writeLog;
|
||||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
sessionInfoPromise,
|
||||
ideSettingsPromise,
|
||||
);
|
||||
|
||||
// Set local profile as default
|
||||
const localProfileLoader = new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
writeLog,
|
||||
);
|
||||
this.localProfileManager = new ProfileLifecycleManager(
|
||||
localProfileLoader,
|
||||
// This profile manager will always be available
|
||||
this.globalLocalProfileManager = new ProfileLifecycleManager(
|
||||
new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.llmLogger,
|
||||
),
|
||||
this.ide,
|
||||
);
|
||||
|
||||
// Profiles are loaded asynchronously
|
||||
this.initializedPromise = new Promise((resolve, reject) => {
|
||||
this.init()
|
||||
.then(() => {
|
||||
resolve();
|
||||
})
|
||||
.catch((e) => {
|
||||
reject(e);
|
||||
});
|
||||
});
|
||||
// Just to be safe, always force a default personal org with local profile manager
|
||||
this.currentProfile = this.globalLocalProfileManager;
|
||||
const personalOrg: OrgWithProfiles = {
|
||||
currentProfile: this.globalLocalProfileManager,
|
||||
profiles: [this.globalLocalProfileManager],
|
||||
...this.PERSONAL_ORG_DESC,
|
||||
};
|
||||
|
||||
this.currentOrg = personalOrg;
|
||||
this.organizations = [personalOrg];
|
||||
|
||||
void this.cascadeInit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
private async getLocalAssistantProfiles() {
|
||||
private workspaceDirs: string[] | null = null;
|
||||
async getWorkspaceId() {
|
||||
if (!this.workspaceDirs) {
|
||||
this.workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
}
|
||||
return this.workspaceDirs.join("&");
|
||||
}
|
||||
|
||||
async getProfileKey(orgId: string) {
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return `${workspaceId}:::${orgId}`;
|
||||
}
|
||||
|
||||
private async cascadeInit() {
|
||||
this.workspaceDirs = null; // forces workspace dirs reload
|
||||
|
||||
const orgs = await this.getOrgs();
|
||||
|
||||
// Figure out selected org
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const currentSelection = selectedOrgs[workspaceId];
|
||||
|
||||
const firstNonPersonal = orgs.find(
|
||||
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
|
||||
);
|
||||
const fallback = firstNonPersonal ?? orgs[0];
|
||||
// note, ignoring case of zero orgs since should never happen
|
||||
|
||||
let selectedOrg: OrgWithProfiles;
|
||||
if (!currentSelection) {
|
||||
selectedOrg = fallback;
|
||||
} else {
|
||||
const match = orgs.find((org) => org.id === currentSelection);
|
||||
if (match) {
|
||||
selectedOrg = match;
|
||||
} else {
|
||||
selectedOrg = fallback;
|
||||
}
|
||||
}
|
||||
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
...selectedOrgs,
|
||||
[workspaceId]: selectedOrg.id,
|
||||
});
|
||||
|
||||
this.organizations = orgs;
|
||||
this.currentOrg = selectedOrg;
|
||||
this.currentProfile = selectedOrg.currentProfile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
|
||||
private async getOrgs(): Promise<OrgWithProfiles[]> {
|
||||
const userId = await this.controlPlaneClient.userId;
|
||||
if (userId) {
|
||||
const orgDescs = await this.controlPlaneClient.listOrganizations();
|
||||
if (await useHub(this.ideSettingsPromise)) {
|
||||
const personalHubOrg = await this.getPersonalHubOrg();
|
||||
const hubOrgs = await Promise.all(
|
||||
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
|
||||
);
|
||||
return [...hubOrgs, personalHubOrg];
|
||||
} else {
|
||||
// Should only ever be one teams org. Will be removed soon anyways
|
||||
return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org)));
|
||||
}
|
||||
} else {
|
||||
return [await this.getLocalOrg()];
|
||||
}
|
||||
}
|
||||
|
||||
getSerializedOrgs(): SerializedOrgWithProfiles[] {
|
||||
return this.organizations.map((org) => ({
|
||||
iconUrl: org.iconUrl,
|
||||
id: org.id,
|
||||
name: org.name,
|
||||
slug: org.slug,
|
||||
profiles: org.profiles.map((profile) => profile.profileDescription),
|
||||
selectedProfileId: org.currentProfile?.profileDescription.id || null,
|
||||
}));
|
||||
}
|
||||
|
||||
private async getHubProfiles(orgScopeId: string | null) {
|
||||
const assistants = await this.controlPlaneClient.listAssistants(orgScopeId);
|
||||
|
||||
return await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create(
|
||||
{
|
||||
...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,
|
||||
);
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async getNonPersonalHubOrg(
|
||||
org: OrganizationDescription,
|
||||
): Promise<OrgWithProfiles> {
|
||||
const profiles = await this.getHubProfiles(org.id);
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
private PERSONAL_ORG_DESC: OrganizationDescription = {
|
||||
iconUrl: "",
|
||||
id: "personal",
|
||||
name: "Personal",
|
||||
slug: undefined,
|
||||
};
|
||||
private async getPersonalHubOrg() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
const hubProfiles = await this.getHubProfiles(null);
|
||||
const profiles = [...hubProfiles, ...allLocalProfiles];
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
|
||||
}
|
||||
|
||||
private async getLocalOrg() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles);
|
||||
}
|
||||
|
||||
async getTeamsOrg(org: OrganizationDescription): Promise<OrgWithProfiles> {
|
||||
const workspaces = await this.controlPlaneClient.listWorkspaces();
|
||||
const profiles = await this.getAllLocalProfiles();
|
||||
workspaces.forEach((workspace) => {
|
||||
const profileLoader = new ControlPlaneProfileLoader(
|
||||
workspace.id,
|
||||
workspace.name,
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.llmLogger,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
|
||||
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
|
||||
});
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
private async rectifyProfilesForOrg(
|
||||
org: OrganizationDescription,
|
||||
profiles: ProfileLifecycleManager[],
|
||||
): Promise<OrgWithProfiles> {
|
||||
const profileKey = await this.getProfileKey(org.id);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
|
||||
const currentSelection = selectedProfiles[profileKey];
|
||||
|
||||
const firstNonLocal = profiles.find(
|
||||
(profile) => profile.profileDescription.profileType !== "local",
|
||||
);
|
||||
const fallback =
|
||||
firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
|
||||
|
||||
let currentProfile: ProfileLifecycleManager | null;
|
||||
if (!currentSelection) {
|
||||
currentProfile = fallback;
|
||||
} else {
|
||||
const match = profiles.find(
|
||||
(profile) => profile.profileDescription.id === currentSelection,
|
||||
);
|
||||
if (match) {
|
||||
currentProfile = match;
|
||||
} else {
|
||||
currentProfile = fallback;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentProfile) {
|
||||
this.globalContext.update("lastSelectedProfileForWorkspace", {
|
||||
...selectedProfiles,
|
||||
[profileKey]: selectedProfiles.id ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
...org,
|
||||
profiles,
|
||||
currentProfile,
|
||||
};
|
||||
}
|
||||
|
||||
async getAllLocalProfiles() {
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
const assistantFiles = await getAllAssistantFiles(this.ide);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
this.llmLogger,
|
||||
assistant,
|
||||
);
|
||||
});
|
||||
return profiles.map(
|
||||
const localAssistantProfiles = profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
);
|
||||
return [this.globalLocalProfileManager, ...localAssistantProfiles];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the titles of additional context providers that are of type "submenu".
|
||||
*
|
||||
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
|
||||
*/
|
||||
getAdditionalSubmenuContextProviders(): string[] {
|
||||
return this.additionalContextProviders
|
||||
.filter((provider) => provider.description.type === "submenu")
|
||||
.map((provider) => provider.description.title);
|
||||
//////////////////
|
||||
// External actions that can cause a cascading config refresh
|
||||
// Should not be used internally
|
||||
//////////////////
|
||||
async refreshAll() {
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
private async init() {
|
||||
try {
|
||||
await this.fetchControlPlaneProfiles();
|
||||
} catch (e) {
|
||||
// If this fails, make sure at least local profile is loaded
|
||||
console.error("Failed to fetch control plane profiles in init: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
|
||||
try {
|
||||
const configResult = await this.loadConfig();
|
||||
this.notifyConfigListeners(configResult);
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
get currentProfile() {
|
||||
if (!this.selectedProfileId) {
|
||||
return null;
|
||||
}
|
||||
// IMPORTANT
|
||||
// We must fall back to null, not the first or local profiles
|
||||
// Because GUI must be the source of truth for selected profile
|
||||
return (
|
||||
this.profiles?.find(
|
||||
(p) => p.profileDescription.id === this.selectedProfileId,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
get inactiveProfiles() {
|
||||
return (this.profiles ?? []).filter(
|
||||
(p) => p.profileDescription.id !== this.selectedProfileId,
|
||||
);
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.selectedProfileId;
|
||||
const profile = this.profiles?.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async listOrganizations() {
|
||||
return await this.controlPlaneClient.listOrganizations();
|
||||
}
|
||||
|
||||
async loadAssistantsForSelectedOrg() {
|
||||
// Get the profiles and create their lifecycle managers
|
||||
const userId = await this.controlPlaneClient.userId;
|
||||
const selectedOrgId = await this.getSelectedOrgId();
|
||||
|
||||
let profiles: ProfileLifecycleManager[] | null = null;
|
||||
if (!userId) {
|
||||
// Not logged in
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
profiles = [...allLocalProfiles];
|
||||
} else {
|
||||
// Logged in
|
||||
const assistants =
|
||||
await this.controlPlaneClient.listAssistants(selectedOrgId);
|
||||
|
||||
const hubProfiles = await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create(
|
||||
{
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
assistant.ownerSlug,
|
||||
assistant.packageSlug,
|
||||
assistant.iconUrl,
|
||||
assistant.configResult.config?.version ?? "latest",
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
assistant.rawYaml,
|
||||
);
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
|
||||
if (selectedOrgId === null) {
|
||||
// Personal
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
profiles = [...hubProfiles, ...allLocalProfiles];
|
||||
} else {
|
||||
// Organization
|
||||
profiles = hubProfiles;
|
||||
}
|
||||
}
|
||||
|
||||
await this.updateAvailableProfiles(profiles);
|
||||
}
|
||||
|
||||
private async getAllLocalProfiles() {
|
||||
const localAssistantProfiles = await this.getLocalAssistantProfiles();
|
||||
return [this.localProfileManager, ...localAssistantProfiles];
|
||||
}
|
||||
|
||||
private async loadLocalProfilesOnly() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
await this.updateAvailableProfiles(allLocalProfiles);
|
||||
}
|
||||
|
||||
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
|
||||
this.profiles = profiles;
|
||||
|
||||
// If the last selected profile is in the list choose that
|
||||
// Otherwise, choose the first profile
|
||||
const previouslySelectedProfileId =
|
||||
await this.getPersistedSelectedProfileId();
|
||||
|
||||
// Check if the previously selected profile exists in the current profiles
|
||||
const profileExists = profiles.some(
|
||||
(profile) =>
|
||||
profile.profileDescription.id === previouslySelectedProfileId,
|
||||
);
|
||||
|
||||
const selectedProfileId = profileExists
|
||||
? previouslySelectedProfileId
|
||||
: (profiles[0]?.profileDescription.id ?? null);
|
||||
|
||||
// Notify listeners
|
||||
const profileDescriptions = profiles.map(
|
||||
(profile) => profile.profileDescription,
|
||||
);
|
||||
this.notifyProfileListeners(profileDescriptions, selectedProfileId);
|
||||
await this.setSelectedProfile(selectedProfileId);
|
||||
}
|
||||
|
||||
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
|
||||
// We use this to keep track of whether we should reload the assistants
|
||||
private lastFullSlugsList: FullSlug[] = [];
|
||||
|
||||
private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean {
|
||||
if (a.length !== b.length) {
|
||||
return true;
|
||||
}
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i].ownerSlug !== b[i].ownerSlug) {
|
||||
return true;
|
||||
}
|
||||
if (a[i].packageSlug !== b[i].packageSlug) {
|
||||
return true;
|
||||
}
|
||||
if (a[i].versionSlug !== b[i].versionSlug) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private async reloadHubAssistants() {
|
||||
const selectedOrgId = await this.getSelectedOrgId();
|
||||
const newFullSlugsList =
|
||||
await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId);
|
||||
|
||||
if (newFullSlugsList) {
|
||||
const shouldReload = this.fullSlugsListsDiffer(
|
||||
newFullSlugsList,
|
||||
this.lastFullSlugsList,
|
||||
);
|
||||
if (shouldReload) {
|
||||
await this.loadAssistantsForSelectedOrg();
|
||||
}
|
||||
this.lastFullSlugsList = newFullSlugsList;
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchControlPlaneProfiles() {
|
||||
if (await useHub(this.ideSettingsPromise)) {
|
||||
clearInterval(this.platformProfilesRefreshInterval);
|
||||
await this.loadAssistantsForSelectedOrg();
|
||||
|
||||
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
|
||||
// If so, we do the full (more expensive) reload
|
||||
this.platformProfilesRefreshInterval = setInterval(
|
||||
this.reloadHubAssistants.bind(this),
|
||||
PlatformProfileLoader.RELOAD_INTERVAL,
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
const workspaces = await this.controlPlaneClient.listWorkspaces();
|
||||
const profiles = await this.getAllLocalProfiles();
|
||||
workspaces.forEach((workspace) => {
|
||||
const profileLoader = new ControlPlaneProfileLoader(
|
||||
workspace.id,
|
||||
workspace.name,
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
|
||||
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
|
||||
});
|
||||
|
||||
await this.updateAvailableProfiles(profiles);
|
||||
} catch (e: any) {
|
||||
console.error("Failed to load profiles: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getPersistedSelectedProfileId(): Promise<string | null> {
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const lastSelectedIds =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
return lastSelectedIds[workspaceId] ?? null;
|
||||
}
|
||||
|
||||
async getSelectedOrgId(): Promise<string | null> {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return selectedOrgs[workspaceId] ?? null;
|
||||
}
|
||||
|
||||
async setSelectedOrgId(orgId: string | null) {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
selectedOrgs[await this.getWorkspaceId()] = orgId;
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
|
||||
this.didSelectOrganization?.(orgId);
|
||||
}
|
||||
|
||||
async setSelectedProfile(profileId: string | null) {
|
||||
this.selectedProfileId = profileId;
|
||||
const result = await this.loadConfig();
|
||||
this.notifyConfigListeners(result);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
selectedProfiles[await this.getWorkspaceId()] = profileId;
|
||||
this.globalContext.update(
|
||||
"lastSelectedProfileForWorkspace",
|
||||
selectedProfiles,
|
||||
);
|
||||
}
|
||||
|
||||
// A unique ID for the current workspace, built from folder names
|
||||
private async getWorkspaceId(): Promise<string> {
|
||||
const dirs = await this.ide.getWorkspaceDirs();
|
||||
return dirs.join("&");
|
||||
}
|
||||
|
||||
// Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed
|
||||
updateIdeSettings(ideSettings: IdeSettings) {
|
||||
// Ide settings change: refresh session and cascade refresh from the top
|
||||
async updateIdeSettings(ideSettings: IdeSettings) {
|
||||
this.ideSettingsPromise = Promise.resolve(ideSettings);
|
||||
void this.reloadConfig();
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
// Session change: refresh session and cascade refresh from the top
|
||||
async updateControlPlaneSessionInfo(
|
||||
sessionInfo: ControlPlaneSessionInfo | undefined,
|
||||
) {
|
||||
|
|
@ -386,38 +324,97 @@ export class ConfigHandler {
|
|||
Promise.resolve(sessionInfo),
|
||||
this.ideSettingsPromise,
|
||||
);
|
||||
await this.cascadeInit();
|
||||
}
|
||||
|
||||
this.fetchControlPlaneProfiles().catch(async (e) => {
|
||||
console.error("Failed to fetch control plane profiles: ", e);
|
||||
await this.loadLocalProfilesOnly();
|
||||
await this.reloadConfig();
|
||||
// Org id: check id validity, save selection, switch and reload
|
||||
async setSelectedOrgId(orgId: string, profileId?: string) {
|
||||
if (orgId === this.currentOrg.id) {
|
||||
return;
|
||||
}
|
||||
const org = this.organizations.find((org) => org.id === orgId);
|
||||
if (!org) {
|
||||
throw new Error(`Org ${orgId} not found`);
|
||||
}
|
||||
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
...selectedOrgs,
|
||||
[workspaceId]: org.id,
|
||||
});
|
||||
}
|
||||
|
||||
private profilesListeners: ((
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) => void)[] = [];
|
||||
onDidChangeAvailableProfiles(
|
||||
listener: (
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) => void,
|
||||
) {
|
||||
this.profilesListeners.push(listener);
|
||||
}
|
||||
this.currentOrg = org;
|
||||
|
||||
private notifyProfileListeners(
|
||||
profiles: ProfileDescription[],
|
||||
selectedProfileId: string | null,
|
||||
) {
|
||||
for (const listener of this.profilesListeners) {
|
||||
listener(profiles, selectedProfileId);
|
||||
if (profileId) {
|
||||
this.setSelectedProfileId(profileId);
|
||||
} else {
|
||||
this.currentProfile = org.currentProfile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
}
|
||||
|
||||
// Profile id: check id validity, save selection, switch and reload
|
||||
async setSelectedProfileId(profileId: string) {
|
||||
if (
|
||||
this.currentProfile &&
|
||||
profileId === this.currentProfile.profileDescription.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const profile = this.currentOrg.profiles.find(
|
||||
(profile) => profile.profileDescription.id === profileId,
|
||||
);
|
||||
if (!profile) {
|
||||
throw new Error(`Profile ${profileId} not found in current org`);
|
||||
}
|
||||
|
||||
const profileKey = await this.getProfileKey(this.currentOrg.id);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
this.globalContext.update("lastSelectedProfileForWorkspace", {
|
||||
...selectedProfiles,
|
||||
[profileKey]: profileId,
|
||||
});
|
||||
|
||||
this.currentProfile = profile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
|
||||
// Bottom level of cascade: refresh the current profile
|
||||
// IMPORTANT - must always refresh when switching profiles
|
||||
// Because of e.g. MCP singleton and docs service using things from config
|
||||
// Could improve this
|
||||
async reloadConfig() {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
||||
for (const org of this.organizations) {
|
||||
for (const profile of org.profiles) {
|
||||
if (
|
||||
profile.profileDescription.id !==
|
||||
this.currentProfile.profileDescription.id
|
||||
) {
|
||||
profile.clearConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { config, errors, configLoadInterrupted } =
|
||||
await this.currentProfile.reloadConfig(this.additionalContextProviders);
|
||||
|
||||
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
|
||||
return { config, errors, configLoadInterrupted };
|
||||
}
|
||||
|
||||
// Listeners setup - can listen to current profile updates
|
||||
private notifyConfigListeners(result: ConfigResult<ContinueConfig>) {
|
||||
// Notify listeners that config changed
|
||||
for (const listener of this.updateListeners) {
|
||||
listener(result);
|
||||
}
|
||||
|
|
@ -429,27 +426,9 @@ export class ConfigHandler {
|
|||
this.updateListeners.push(listener);
|
||||
}
|
||||
|
||||
// TODO: this isn't right, there are two different senses in which you want to "reload"
|
||||
async reloadConfig() {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
||||
const { config, errors, configLoadInterrupted } =
|
||||
await this.currentProfile.reloadConfig(this.additionalContextProviders);
|
||||
|
||||
if (config) {
|
||||
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
|
||||
}
|
||||
|
||||
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
|
||||
return { config, errors, configLoadInterrupted };
|
||||
}
|
||||
|
||||
// Methods for loading (without reloading) config
|
||||
// Serialized for passing to GUI
|
||||
// Load for just awaiting current config load promise for the profile
|
||||
async getSerializedConfig(): Promise<
|
||||
ConfigResult<BrowserSerializedContinueConfig>
|
||||
> {
|
||||
|
|
@ -465,10 +444,6 @@ export class ConfigHandler {
|
|||
);
|
||||
}
|
||||
|
||||
listProfiles(): ProfileDescription[] | null {
|
||||
return this.profiles?.map((p) => p.profileDescription) ?? null;
|
||||
}
|
||||
|
||||
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
|
|
@ -482,6 +457,23 @@ export class ConfigHandler {
|
|||
);
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
|
||||
if (!openProfileId) {
|
||||
return;
|
||||
}
|
||||
const profile = this.currentOrg.profiles.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
|
@ -502,8 +494,20 @@ export class ConfigHandler {
|
|||
return model;
|
||||
}
|
||||
|
||||
// Ancient method of adding custom providers through vs code
|
||||
private additionalContextProviders: IContextProvider[] = [];
|
||||
registerCustomContextProvider(contextProvider: IContextProvider) {
|
||||
this.additionalContextProviders.push(contextProvider);
|
||||
void this.reloadConfig();
|
||||
}
|
||||
/**
|
||||
* Retrieves the titles of additional context providers that are of type "submenu".
|
||||
*
|
||||
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
|
||||
*/
|
||||
getAdditionalSubmenuContextProviders(): string[] {
|
||||
return this.additionalContextProviders
|
||||
.filter((provider) => provider.description.type === "submenu")
|
||||
.map((provider) => provider.description.title);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,16 @@ export interface OrganizationDescription {
|
|||
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
|
||||
}
|
||||
|
||||
export type OrgWithProfiles = OrganizationDescription & {
|
||||
profiles: ProfileLifecycleManager[];
|
||||
currentProfile: ProfileLifecycleManager | null;
|
||||
};
|
||||
|
||||
export type SerializedOrgWithProfiles = OrganizationDescription & {
|
||||
profiles: ProfileDescription[];
|
||||
selectedProfileId: string | null;
|
||||
};
|
||||
|
||||
export class ProfileLifecycleManager {
|
||||
private savedConfigResult: ConfigResult<ContinueConfig> | undefined;
|
||||
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
|
|
|
|||
|
|
@ -1,93 +1,37 @@
|
|||
import {
|
||||
ContextProviderWithParams,
|
||||
ModelDescription,
|
||||
SerializedContinueConfig,
|
||||
SlashCommandDescription,
|
||||
} from "../";
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
|
||||
export const FREE_TRIAL_MODELS: ModelDescription[] = [
|
||||
{
|
||||
title: "Claude 3.5 Sonnet (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
systemMessage:
|
||||
"You are an expert software developer. You give helpful and concise responses.",
|
||||
},
|
||||
{
|
||||
title: "GPT-4o (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4o",
|
||||
systemMessage:
|
||||
"You are an expert software developer. You give helpful and concise responses.",
|
||||
},
|
||||
{
|
||||
title: "Llama3.1 70b (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "llama3.1-70b",
|
||||
systemMessage:
|
||||
"You are an expert software developer. You give helpful and concise responses.",
|
||||
},
|
||||
{
|
||||
title: "Codestral (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "codestral-latest",
|
||||
systemMessage:
|
||||
"You are an expert software developer. You give helpful and concise responses.",
|
||||
},
|
||||
export const defaultContextProvidersVsCode: NonNullable<
|
||||
ConfigYaml["context"]
|
||||
>[number][] = [
|
||||
{ provider: "code" },
|
||||
{ provider: "docs" },
|
||||
{ provider: "diff" },
|
||||
{ provider: "terminal" },
|
||||
{ provider: "problems" },
|
||||
{ provider: "folder" },
|
||||
{ provider: "codebase" },
|
||||
];
|
||||
|
||||
export const defaultContextProvidersVsCode: ContextProviderWithParams[] = [
|
||||
{ name: "code", params: {} },
|
||||
{ name: "docs", params: {} },
|
||||
{ name: "diff", params: {} },
|
||||
{ name: "terminal", params: {} },
|
||||
{ name: "problems", params: {} },
|
||||
{ name: "folder", params: {} },
|
||||
{ name: "codebase", params: {} },
|
||||
export const defaultContextProvidersJetBrains: NonNullable<
|
||||
ConfigYaml["context"]
|
||||
>[number][] = [
|
||||
{ provider: "diff" },
|
||||
{ provider: "folder" },
|
||||
{ provider: "codebase" },
|
||||
];
|
||||
|
||||
export const defaultContextProvidersJetBrains: ContextProviderWithParams[] = [
|
||||
{ name: "diff", params: {} },
|
||||
{ name: "folder", params: {} },
|
||||
{ name: "codebase", params: {} },
|
||||
];
|
||||
|
||||
export const defaultSlashCommandsVscode: SlashCommandDescription[] = [
|
||||
{
|
||||
name: "share",
|
||||
description: "Export the current chat session to markdown",
|
||||
},
|
||||
{
|
||||
name: "cmd",
|
||||
description: "Generate a shell command",
|
||||
},
|
||||
{
|
||||
name: "commit",
|
||||
description: "Generate a git commit message",
|
||||
},
|
||||
];
|
||||
|
||||
export const defaultSlashCommandsJetBrains = [
|
||||
{
|
||||
name: "share",
|
||||
description: "Export the current chat session to markdown",
|
||||
},
|
||||
{
|
||||
name: "commit",
|
||||
description: "Generate a git commit message",
|
||||
},
|
||||
];
|
||||
|
||||
export const defaultConfig: SerializedContinueConfig = {
|
||||
export const defaultConfig: ConfigYaml = {
|
||||
name: "Local Assistant",
|
||||
version: "1.0.0",
|
||||
schema: "v1",
|
||||
models: [],
|
||||
contextProviders: defaultContextProvidersVsCode,
|
||||
slashCommands: defaultSlashCommandsVscode,
|
||||
data: [],
|
||||
context: defaultContextProvidersVsCode,
|
||||
};
|
||||
|
||||
export const defaultConfigJetBrains: SerializedContinueConfig = {
|
||||
export const defaultConfigJetBrains: ConfigYaml = {
|
||||
name: "Local Assistant",
|
||||
version: "1.0.0",
|
||||
schema: "v1",
|
||||
models: [],
|
||||
contextProviders: defaultContextProvidersJetBrains,
|
||||
slashCommands: defaultSlashCommandsJetBrains,
|
||||
data: [],
|
||||
context: defaultContextProvidersJetBrains,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import {
|
|||
IdeSettings,
|
||||
IdeType,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
LLMOptions,
|
||||
ModelDescription,
|
||||
RerankerDescription,
|
||||
|
|
@ -70,12 +71,6 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import {
|
||||
defaultContextProvidersJetBrains,
|
||||
defaultContextProvidersVsCode,
|
||||
defaultSlashCommandsJetBrains,
|
||||
defaultSlashCommandsVscode,
|
||||
} from "./default";
|
||||
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util";
|
||||
|
|
@ -122,7 +117,7 @@ function loadSerializedConfig(
|
|||
let config: SerializedContinueConfig = overrideConfigJson!;
|
||||
if (!config) {
|
||||
try {
|
||||
config = resolveSerializedConfig(getConfigJsonPath(ideType));
|
||||
config = resolveSerializedConfig(getConfigJsonPath());
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to parse config.json: ${e}`);
|
||||
}
|
||||
|
|
@ -162,16 +157,6 @@ function loadSerializedConfig(
|
|||
);
|
||||
}
|
||||
|
||||
// Set defaults if undefined (this lets us keep config.json uncluttered for new users)
|
||||
config.contextProviders ??=
|
||||
ideType === "vscode"
|
||||
? [...defaultContextProvidersVsCode]
|
||||
: [...defaultContextProvidersJetBrains];
|
||||
config.slashCommands ??=
|
||||
ideType === "vscode"
|
||||
? [...defaultSlashCommandsVscode]
|
||||
: [...defaultSlashCommandsJetBrains];
|
||||
|
||||
if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) {
|
||||
config.disableIndexing = true;
|
||||
}
|
||||
|
|
@ -238,7 +223,7 @@ async function intermediateToFinalConfig(
|
|||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
llmLogger: ILLMLogger,
|
||||
workOsAccessToken: string | undefined,
|
||||
loadPromptFiles: boolean = true,
|
||||
allowFreeTrial: boolean = true,
|
||||
|
|
@ -254,7 +239,7 @@ async function intermediateToFinalConfig(
|
|||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
config.systemMessage,
|
||||
);
|
||||
|
|
@ -276,7 +261,7 @@ async function intermediateToFinalConfig(
|
|||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
copyOf(config.completionOptions),
|
||||
config.systemMessage,
|
||||
);
|
||||
|
|
@ -296,7 +281,7 @@ async function intermediateToFinalConfig(
|
|||
} else {
|
||||
const llm = new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, writeLog } as any,
|
||||
options: { ...desc.options, logger: llmLogger } as any,
|
||||
});
|
||||
if (llm.model === "AUTODETECT") {
|
||||
try {
|
||||
|
|
@ -305,7 +290,11 @@ async function intermediateToFinalConfig(
|
|||
(modelName) =>
|
||||
new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, model: modelName, writeLog },
|
||||
options: {
|
||||
...desc.options,
|
||||
model: modelName,
|
||||
logger: llmLogger,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
@ -359,7 +348,7 @@ async function intermediateToFinalConfig(
|
|||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
config.systemMessage,
|
||||
);
|
||||
|
|
@ -516,7 +505,7 @@ async function intermediateToFinalConfig(
|
|||
...config,
|
||||
contextProviders,
|
||||
models,
|
||||
tools: allTools,
|
||||
tools: [...allTools],
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: config.slashCommands ?? [],
|
||||
modelsByRole: {
|
||||
|
|
@ -545,7 +534,7 @@ async function intermediateToFinalConfig(
|
|||
(config.experimental?.modelContextProtocolServers ?? []).map(
|
||||
(server, index) => ({
|
||||
id: `continue-mcp-server-${index + 1}`,
|
||||
name: `MCP Server ${index + 1}`,
|
||||
name: `MCP Server`,
|
||||
...server,
|
||||
}),
|
||||
),
|
||||
|
|
@ -847,7 +836,7 @@ async function loadContinueConfigFromJson(
|
|||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
llmLogger: ILLMLogger,
|
||||
workOsAccessToken: string | undefined,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
|
|
@ -947,7 +936,7 @@ async function loadContinueConfigFromJson(
|
|||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
);
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { IDE } from "..";
|
||||
import { deduplicateArray } from "../util";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigJson } from "../util/paths";
|
||||
import { resolveSerializedConfig } from "./load";
|
||||
import { SharedConfigSchema } from "./sharedConfig";
|
||||
|
||||
|
|
@ -196,11 +195,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
|
|||
|
||||
if (effected) {
|
||||
new GlobalContext().updateSharedConfig(shareConfigUpdates);
|
||||
editConfigJson(() => config);
|
||||
// void ide.showToast(
|
||||
// "warning",
|
||||
// "Migrated deprecated Continue JSON settings. Edit in the Settings Page",
|
||||
// );
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`Migration: Failed to parse config.json: ${e}`);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
import { SerializedContinueConfig } from "../";
|
||||
|
||||
import { FREE_TRIAL_MODELS } from "./default";
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
|
||||
export const TRIAL_FIM_MODEL = "codestral-latest";
|
||||
export const LOCAL_ONBOARDING_PROVIDER_TITLE = "Ollama";
|
||||
|
|
@ -9,64 +7,46 @@ export const LOCAL_ONBOARDING_FIM_TITLE = "Qwen2.5-Coder 1.5B";
|
|||
export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b";
|
||||
export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";
|
||||
export const LOCAL_ONBOARDING_EMBEDDINGS_MODEL = "nomic-embed-text:latest";
|
||||
export const LOCAL_ONBOARDING_EMBEDDINGS_TITLE = "Nomic Embed";
|
||||
|
||||
/**
|
||||
* We set the "best" chat + autocopmlete models by default
|
||||
* whenever a user doesn't have a config.json
|
||||
*/
|
||||
export function setupBestConfig(
|
||||
config: SerializedContinueConfig,
|
||||
): SerializedContinueConfig {
|
||||
export function setupBestConfig(config: ConfigYaml): ConfigYaml {
|
||||
return {
|
||||
...config,
|
||||
models: config.models.filter((model) => model.provider !== "free-trial"),
|
||||
models: config.models,
|
||||
};
|
||||
}
|
||||
|
||||
export function setupLocalConfig(
|
||||
config: SerializedContinueConfig,
|
||||
): SerializedContinueConfig {
|
||||
export function setupLocalConfig(config: ConfigYaml): ConfigYaml {
|
||||
return {
|
||||
...config,
|
||||
models: [
|
||||
{
|
||||
title: LOCAL_ONBOARDING_CHAT_TITLE,
|
||||
name: LOCAL_ONBOARDING_CHAT_TITLE,
|
||||
provider: "ollama",
|
||||
model: LOCAL_ONBOARDING_CHAT_MODEL,
|
||||
roles: ["chat", "edit", "apply"],
|
||||
},
|
||||
...config.models.filter((model) => model.provider !== "free-trial"),
|
||||
{
|
||||
name: LOCAL_ONBOARDING_FIM_TITLE,
|
||||
provider: "ollama",
|
||||
model: LOCAL_ONBOARDING_FIM_MODEL,
|
||||
roles: ["autocomplete"],
|
||||
},
|
||||
{
|
||||
name: LOCAL_ONBOARDING_EMBEDDINGS_TITLE,
|
||||
provider: "ollama",
|
||||
model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL,
|
||||
roles: ["embed"],
|
||||
},
|
||||
...(config.models ?? []),
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: LOCAL_ONBOARDING_FIM_TITLE,
|
||||
provider: "ollama",
|
||||
model: LOCAL_ONBOARDING_FIM_MODEL,
|
||||
},
|
||||
embeddingsProvider: {
|
||||
provider: "ollama",
|
||||
model: LOCAL_ONBOARDING_EMBEDDINGS_MODEL,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function setupQuickstartConfig(
|
||||
config: SerializedContinueConfig,
|
||||
): SerializedContinueConfig {
|
||||
return {
|
||||
...config,
|
||||
models: [
|
||||
...FREE_TRIAL_MODELS,
|
||||
...config.models.filter((model) => model.provider !== "free-trial"),
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: "Tab Autocomplete",
|
||||
provider: "free-trial",
|
||||
model: TRIAL_FIM_MODEL,
|
||||
},
|
||||
embeddingsProvider: {
|
||||
provider: "free-trial",
|
||||
},
|
||||
reranker: {
|
||||
name: "free-trial",
|
||||
},
|
||||
};
|
||||
export function setupQuickstartConfig(config: ConfigYaml): ConfigYaml {
|
||||
return config;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
ContinueConfig,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
SerializedContinueConfig,
|
||||
} from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
|
@ -27,7 +28,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
private readonly controlPlaneClient: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
private llmLogger: ILLMLogger,
|
||||
private readonly onReload: () => void,
|
||||
) {
|
||||
this.description = {
|
||||
|
|
@ -65,12 +66,13 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
this.llmLogger,
|
||||
serializedConfig,
|
||||
undefined,
|
||||
undefined,
|
||||
this.workspaceId,
|
||||
undefined,
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import { getPrimaryConfigFilePath } from "../../util/paths.js";
|
||||
|
|
@ -17,7 +17,7 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
private ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
private llmLogger: ILLMLogger,
|
||||
private overrideAssistantFile?:
|
||||
| { path: string; content: string }
|
||||
| undefined,
|
||||
|
|
@ -59,12 +59,13 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
this.llmLogger,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
this.description.id,
|
||||
this.overrideAssistantFile?.path,
|
||||
null,
|
||||
);
|
||||
|
||||
this.description.errors = result.errors;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
|
|||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
|
|
@ -30,9 +30,9 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
private readonly controlPlaneClient: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
private readonly onReload: () => void,
|
||||
private llmLogger: ILLMLogger,
|
||||
readonly description: ProfileDescription,
|
||||
private readonly orgScopeId: string | null,
|
||||
) {}
|
||||
|
||||
static async create(
|
||||
|
|
@ -44,9 +44,9 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
controlPlaneClient: ControlPlaneClient,
|
||||
ide: IDE,
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
writeLog: (message: string) => Promise<void>,
|
||||
onReload: () => void,
|
||||
llmLogger: ILLMLogger,
|
||||
rawYaml: string,
|
||||
orgScopeId: string | null,
|
||||
): Promise<PlatformProfileLoader> {
|
||||
const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
|
||||
|
||||
|
|
@ -74,9 +74,9 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
controlPlaneClient,
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
writeLog,
|
||||
onReload,
|
||||
llmLogger,
|
||||
description,
|
||||
orgScopeId,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -93,7 +93,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
this.llmLogger,
|
||||
undefined,
|
||||
this.configResult.config,
|
||||
{
|
||||
|
|
@ -102,6 +102,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
},
|
||||
this.description.id,
|
||||
undefined,
|
||||
this.orgScopeId,
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
ContinueRcJson,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
SerializedContinueConfig,
|
||||
Tool,
|
||||
} from "../../";
|
||||
|
|
@ -39,12 +40,13 @@ export default async function doLoadConfig(
|
|||
ide: IDE,
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
writeLog: (message: string) => Promise<void>,
|
||||
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();
|
||||
|
|
@ -54,7 +56,7 @@ export default async function doLoadConfig(
|
|||
|
||||
// Migrations for old config files
|
||||
// Removes
|
||||
const configJsonPath = getConfigJsonPath(ideInfo.ideType);
|
||||
const configJsonPath = getConfigJsonPath();
|
||||
if (fs.existsSync(configJsonPath)) {
|
||||
migrateJsonSharedConfig(configJsonPath, ide);
|
||||
}
|
||||
|
|
@ -70,16 +72,16 @@ export default async function doLoadConfig(
|
|||
if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
|
||||
const result = await loadContinueConfigFromYaml(
|
||||
ide,
|
||||
workspaceConfigs.map((c) => JSON.stringify(c)),
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
configYamlPath,
|
||||
orgScopeId,
|
||||
);
|
||||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
|
|
@ -91,7 +93,7 @@ export default async function doLoadConfig(
|
|||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigJson,
|
||||
);
|
||||
|
|
@ -134,7 +136,6 @@ export default async function doLoadConfig(
|
|||
faviconUrl: server.faviconUrl,
|
||||
readonly: false,
|
||||
type: "function" as const,
|
||||
wouldLikeTo: "",
|
||||
uri: encodeMCPToolUri(server.id, tool.name),
|
||||
group: server.name,
|
||||
}));
|
||||
|
|
@ -160,6 +161,7 @@ export default async function doLoadConfig(
|
|||
const serverContextProvider = new MCPContextProvider({
|
||||
submenuItems,
|
||||
mcpId: server.id,
|
||||
serverName: server.name,
|
||||
});
|
||||
newConfig.contextProviders.push(serverContextProvider);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ declare global {
|
|||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
llmLogger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
|
|
@ -433,6 +433,94 @@ declare global {
|
|||
|
||||
export type ToastType = "info" | "error" | "warning";
|
||||
|
||||
export interface LLMInteractionBase {
|
||||
interactionId: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartChat extends LLMInteractionBase {
|
||||
kind: "startChat";
|
||||
messages: ChatMessage[];
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartComplete extends LLMInteractionBase {
|
||||
kind: "startComplete";
|
||||
prompt: string;
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartFim extends LLMInteractionBase {
|
||||
kind: "startFim";
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionChunk extends LLMInteractionBase {
|
||||
kind: "chunk";
|
||||
chunk: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionMessage extends LLMInteractionBase {
|
||||
kind: "message";
|
||||
message: ChatMessage;
|
||||
}
|
||||
|
||||
export interface LLMInteractionEnd extends LLMInteractionBase {
|
||||
promptTokens: number;
|
||||
generatedTokens: number;
|
||||
thinkingTokens: number;
|
||||
}
|
||||
|
||||
export interface LLMInteractionSuccess extends LLMInteractionEnd {
|
||||
kind: "success";
|
||||
}
|
||||
|
||||
export interface LLMInteractionCancel extends LLMInteractionEnd {
|
||||
kind: "cancel";
|
||||
}
|
||||
|
||||
export interface LLMInteractionError extends LLMInteractionEnd {
|
||||
kind: "error";
|
||||
name: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type LLMInteractionItem =
|
||||
| LLMInteractionStartChat
|
||||
| LLMInteractionStartComplete
|
||||
| LLMInteractionStartFim
|
||||
| LLMInteractionChunk
|
||||
| LLMInteractionMessage
|
||||
| LLMInteractionSuccess
|
||||
| LLMInteractionCancel
|
||||
| LLMInteractionError;
|
||||
|
||||
// When we log a LLM interaction, we want to add the interactionId and timestamp
|
||||
// in the logger code, so we need a type that omits these members from *each*
|
||||
// member of the union. This can be done by using the distributive behavior of
|
||||
// conditional types in Typescript.
|
||||
//
|
||||
// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
|
||||
// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s
|
||||
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
|
||||
? Omit<T, K>
|
||||
: never;
|
||||
|
||||
export type LLMInteractionItemDetails = DistributiveOmit<
|
||||
LLMInteractionItem,
|
||||
"interactionId" | "timestamp"
|
||||
>;
|
||||
|
||||
export interface ILLMInteractionLog {
|
||||
logItem(item: LLMInteractionItemDetails): void;
|
||||
}
|
||||
|
||||
export interface ILLMLogger {
|
||||
createInteractionLog(): ILLMInteractionLog;
|
||||
}
|
||||
|
||||
export interface LLMOptions {
|
||||
model: string;
|
||||
|
||||
|
|
@ -446,7 +534,7 @@ declare global {
|
|||
template?: TemplateType;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
aiGatewaySlug?: string;
|
||||
|
|
|
|||
|
|
@ -2,17 +2,14 @@ import fs from "fs";
|
|||
import os from "os";
|
||||
|
||||
import {
|
||||
ContextProviderWithParams,
|
||||
ContinueConfig,
|
||||
ExperimentalModelRoles,
|
||||
IDE,
|
||||
ILLM,
|
||||
ModelDescription,
|
||||
ExperimentalModelRoles,
|
||||
} from "../";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigJson } from "../util/paths";
|
||||
|
||||
import { ConfigHandler } from "./ConfigHandler";
|
||||
import { editConfigFile } from "../util/paths";
|
||||
|
||||
function stringify(obj: any, indentation?: number): string {
|
||||
return JSON.stringify(
|
||||
|
|
@ -24,78 +21,67 @@ function stringify(obj: any, indentation?: number): string {
|
|||
);
|
||||
}
|
||||
|
||||
export function addContextProvider(provider: ContextProviderWithParams, configHandler?: ConfigHandler) {
|
||||
let isAdded = false;
|
||||
editConfigJson((config) => {
|
||||
|
||||
if (!config.contextProviders) {
|
||||
config.contextProviders = [];
|
||||
}
|
||||
if (!config.contextProviders.some((p) => p.name === provider.name)) {
|
||||
config.contextProviders.push(provider);
|
||||
isAdded = true;
|
||||
}
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
if (isAdded && configHandler) {
|
||||
void configHandler.reloadConfig();
|
||||
}
|
||||
}
|
||||
|
||||
export function addModel(
|
||||
model: ModelDescription,
|
||||
role?: keyof ExperimentalModelRoles,
|
||||
) {
|
||||
editConfigJson((config) => {
|
||||
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
|
||||
return config;
|
||||
}
|
||||
if (config.models?.some((m: any) => m?.title === model.title)) {
|
||||
model.title = `${model.title} (1)`;
|
||||
}
|
||||
|
||||
config.models.push(model);
|
||||
|
||||
// Set the role for the model
|
||||
if (role) {
|
||||
if (!config.experimental) {
|
||||
config.experimental = {};
|
||||
editConfigFile(
|
||||
(config) => {
|
||||
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
|
||||
return config;
|
||||
}
|
||||
if (!config.experimental.modelRoles) {
|
||||
config.experimental.modelRoles = {};
|
||||
if (config.models?.some((m: any) => m?.title === model.title)) {
|
||||
model.title = `${model.title} (1)`;
|
||||
}
|
||||
config.experimental.modelRoles[role] = model.title;
|
||||
}
|
||||
|
||||
return config;
|
||||
});
|
||||
}
|
||||
config.models.push(model);
|
||||
|
||||
export function addOpenAIKey(key: string) {
|
||||
editConfigJson((config) => {
|
||||
config.models = config.models
|
||||
.filter(
|
||||
(model) =>
|
||||
model.provider !== "free-trial" || model.model.startsWith("gpt"),
|
||||
)
|
||||
.map((m: ModelDescription) => {
|
||||
if (m.provider === "free-trial") {
|
||||
m.apiKey = key;
|
||||
m.provider = "openai";
|
||||
// Set the role for the model
|
||||
if (role) {
|
||||
if (!config.experimental) {
|
||||
config.experimental = {};
|
||||
}
|
||||
return m;
|
||||
if (!config.experimental.modelRoles) {
|
||||
config.experimental.modelRoles = {};
|
||||
}
|
||||
config.experimental.modelRoles[role] = model.title;
|
||||
}
|
||||
|
||||
return config;
|
||||
},
|
||||
(config) => {
|
||||
if (config.models?.some((m: any) => m?.title === model.title)) {
|
||||
model.title = `${model.title} (1)`;
|
||||
}
|
||||
|
||||
if (!config.models) {
|
||||
config.models = [];
|
||||
}
|
||||
|
||||
config.models.push({
|
||||
name: model.title,
|
||||
provider: model.provider,
|
||||
model: model.model,
|
||||
apiKey: model.apiKey,
|
||||
apiBase: model.apiBase,
|
||||
defaultCompletionOptions: model.completionOptions,
|
||||
});
|
||||
return config;
|
||||
});
|
||||
return config;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function deleteModel(title: string) {
|
||||
editConfigJson((config) => {
|
||||
config.models = config.models.filter((m: any) => m.title !== title);
|
||||
return config;
|
||||
});
|
||||
editConfigFile(
|
||||
(config) => {
|
||||
config.models = config.models.filter((m: any) => m.title !== title);
|
||||
return config;
|
||||
},
|
||||
(config) => {
|
||||
config.models = config.models?.filter((m: any) => m.name !== title);
|
||||
return config;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function getModelByRole<T extends keyof ExperimentalModelRoles>(
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
|||
|
||||
import { SerializedContinueConfig } from "../..";
|
||||
|
||||
/*
|
||||
TODO this is not functional
|
||||
*/
|
||||
export function convertConfigJsonToConfigYaml(
|
||||
configJson: SerializedContinueConfig,
|
||||
): AssistantUnrolled {
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import {
|
|||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
} from "../..";
|
||||
import { slashFromCustomCommand } from "../../commands";
|
||||
import { AllRerankers } from "../../context/allRerankers";
|
||||
|
|
@ -41,22 +42,31 @@ import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
|
|||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
|
||||
export class LocalPlatformClient implements PlatformClient {
|
||||
constructor(
|
||||
private orgScopeId: string | null,
|
||||
private readonly client: ControlPlaneClient,
|
||||
) {}
|
||||
|
||||
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
|
||||
return fqsns.map((fqsn) => {
|
||||
return undefined;
|
||||
});
|
||||
if (fqsns.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const response = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConfigYaml(
|
||||
workspaceConfigs: string[],
|
||||
rawYaml: string,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
ide: IDE,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
orgScopeId: string | null,
|
||||
ideSettings: IdeSettings,
|
||||
): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
let config =
|
||||
overrideConfigYaml ??
|
||||
|
|
@ -68,12 +78,18 @@ async function loadConfigYaml(
|
|||
versionSlug: "",
|
||||
},
|
||||
rawYaml,
|
||||
new RegistryClient(),
|
||||
new RegistryClient(
|
||||
await controlPlaneClient.getAccessToken(),
|
||||
getControlPlaneEnvSync(
|
||||
ideSettings.continueTestEnvironment,
|
||||
ideSettings.enableControlServerBeta,
|
||||
).CONTROL_PLANE_URL,
|
||||
),
|
||||
{
|
||||
currentUserSlug: "",
|
||||
onPremProxyUrl: null,
|
||||
orgScopeId: null,
|
||||
platformClient: new LocalPlatformClient(),
|
||||
orgScopeId,
|
||||
platformClient: new LocalPlatformClient(orgScopeId, controlPlaneClient),
|
||||
renderSecrets: true,
|
||||
},
|
||||
));
|
||||
|
|
@ -101,7 +117,7 @@ async function configYamlToContinueConfig(
|
|||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
llmLogger: ILLMLogger,
|
||||
workOsAccessToken: string | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
allowFreeTrial: boolean = true,
|
||||
|
|
@ -112,7 +128,7 @@ async function configYamlToContinueConfig(
|
|||
models: [],
|
||||
tools: [...allTools],
|
||||
mcpServerStatuses: [],
|
||||
systemMessage: config.rules?.join("\n"),
|
||||
systemMessage: undefined,
|
||||
experimental: {
|
||||
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
|
||||
transport: {
|
||||
|
|
@ -196,17 +212,16 @@ async function configYamlToContinueConfig(
|
|||
for (const model of config.models ?? []) {
|
||||
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
|
||||
try {
|
||||
const llms = await llmsFromModelConfig(
|
||||
const llms = await llmsFromModelConfig({
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
continueConfig.systemMessage,
|
||||
);
|
||||
config: continueConfig,
|
||||
});
|
||||
|
||||
//
|
||||
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
|
||||
continueConfig.models.push(...llms);
|
||||
}
|
||||
|
|
@ -244,7 +259,10 @@ async function configYamlToContinueConfig(
|
|||
} else {
|
||||
continueConfig.modelsByRole.embed.push(
|
||||
new embeddingsProviderClass(
|
||||
options,
|
||||
{
|
||||
...options,
|
||||
title: options.name,
|
||||
},
|
||||
(url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
|
|
@ -265,10 +283,15 @@ async function configYamlToContinueConfig(
|
|||
const rerankerClass = AllRerankers[provider];
|
||||
if (rerankerClass) {
|
||||
continueConfig.modelsByRole.rerank.push(
|
||||
new rerankerClass(options, (url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
}),
|
||||
new rerankerClass(
|
||||
{
|
||||
...options,
|
||||
title: options.name,
|
||||
},
|
||||
(url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
}),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
|
|
@ -387,16 +410,16 @@ async function configYamlToContinueConfig(
|
|||
|
||||
export async function loadContinueConfigFromYaml(
|
||||
ide: IDE,
|
||||
workspaceConfigs: string[],
|
||||
ideSettings: IdeSettings,
|
||||
ideInfo: IdeInfo,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
llmLogger: ILLMLogger,
|
||||
workOsAccessToken: string | undefined,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
configYamlPath: string | undefined,
|
||||
orgScopeId: string | null,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const rawYaml =
|
||||
overrideConfigYaml === undefined
|
||||
|
|
@ -407,11 +430,11 @@ export async function loadContinueConfigFromYaml(
|
|||
: "";
|
||||
|
||||
const configYamlResult = await loadConfigYaml(
|
||||
workspaceConfigs,
|
||||
rawYaml,
|
||||
overrideConfigYaml,
|
||||
ide,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
ideSettings,
|
||||
);
|
||||
|
||||
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
|
||||
|
|
@ -429,7 +452,7 @@ export async function loadContinueConfigFromYaml(
|
|||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
platformConfigMetadata,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,12 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
|
||||
import { IDE, IdeSettings, LLMOptions } from "../..";
|
||||
import {
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
LLMOptions,
|
||||
} from "../..";
|
||||
import { BaseLLM } from "../../llm";
|
||||
import { LLMClasses } from "../../llm/llms";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
|
|
@ -13,22 +19,29 @@ function getModelClass(
|
|||
return LLMClasses.find((llm) => llm.providerName === model.provider);
|
||||
}
|
||||
|
||||
function getContinueProxyModelName(
|
||||
ownerSlug: string,
|
||||
packageSlug: string,
|
||||
model: ModelConfig,
|
||||
): string {
|
||||
return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
|
||||
}
|
||||
// function getContinueProxyModelName(
|
||||
// ownerSlug: string,
|
||||
// packageSlug: string,
|
||||
// model: ModelConfig,
|
||||
// ): string {
|
||||
// return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
|
||||
// }
|
||||
|
||||
async function modelConfigToBaseLLM(
|
||||
model: ModelConfig,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM | undefined> {
|
||||
async function modelConfigToBaseLLM({
|
||||
model,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM | undefined> {
|
||||
const cls = getModelClass(model);
|
||||
|
||||
if (!cls) {
|
||||
|
|
@ -39,7 +52,7 @@ async function modelConfigToBaseLLM(
|
|||
|
||||
let options: LLMOptions = {
|
||||
...rest,
|
||||
// contextLength: model.defaultCompletionOptions?.contextLength ?? undefined,
|
||||
contextLength: model.defaultCompletionOptions?.contextLength,
|
||||
completionOptions: {
|
||||
...(model.defaultCompletionOptions ?? {}),
|
||||
model: model.model,
|
||||
|
|
@ -47,10 +60,11 @@ async function modelConfigToBaseLLM(
|
|||
model.defaultCompletionOptions?.maxTokens ??
|
||||
cls.defaultOptions?.completionOptions?.maxTokens,
|
||||
},
|
||||
writeLog,
|
||||
logger: llmLogger,
|
||||
uniqueId,
|
||||
title: model.name,
|
||||
systemMessage,
|
||||
systemMessage: config.systemMessage,
|
||||
rules: config.rules,
|
||||
promptTemplates: model.promptTemplates,
|
||||
capabilities: {
|
||||
tools: model.capabilities?.includes("tool_use"),
|
||||
|
|
@ -127,16 +141,25 @@ async function modelConfigToBaseLLM(
|
|||
return llm;
|
||||
}
|
||||
|
||||
async function autodetectModels(
|
||||
llm: BaseLLM,
|
||||
model: ModelConfig,
|
||||
ide: IDE,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM[]> {
|
||||
async function autodetectModels({
|
||||
llm,
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
llm: BaseLLM;
|
||||
model: ModelConfig;
|
||||
ide: IDE;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const detectedModels = await Promise.all(
|
||||
|
|
@ -146,18 +169,18 @@ async function autodetectModels(
|
|||
return undefined;
|
||||
}
|
||||
|
||||
return await modelConfigToBaseLLM(
|
||||
{
|
||||
return await modelConfigToBaseLLM({
|
||||
model: {
|
||||
...model,
|
||||
model: modelName,
|
||||
name: modelName,
|
||||
},
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
config,
|
||||
});
|
||||
}),
|
||||
);
|
||||
return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[];
|
||||
|
|
@ -167,38 +190,46 @@ async function autodetectModels(
|
|||
}
|
||||
}
|
||||
|
||||
export async function llmsFromModelConfig(
|
||||
model: ModelConfig,
|
||||
ide: IDE,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM(
|
||||
export async function llmsFromModelConfig({
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
ide: IDE;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM({
|
||||
model,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
config,
|
||||
});
|
||||
if (!baseLlm) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (model.model === AUTODETECT) {
|
||||
const models = await autodetectModels(
|
||||
baseLlm,
|
||||
const models = await autodetectModels({
|
||||
llm: baseLlm,
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
config,
|
||||
});
|
||||
return models;
|
||||
} else {
|
||||
return [baseLlm];
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ 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";
|
||||
|
|
@ -16,4 +17,5 @@ export const AllRerankers: { [key: string]: any } = {
|
|||
"free-trial": FreeTrial,
|
||||
"huggingface-tei": HuggingFaceTEI,
|
||||
"continue-proxy": ContinueProxy,
|
||||
siliconflow: SiliconFlow,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import {
|
|||
LoadSubmenuItemsArgs,
|
||||
} from "../..";
|
||||
import DocsService from "../../indexing/docs/DocsService";
|
||||
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
|
||||
|
||||
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
|
||||
|
||||
|
|
@ -64,23 +63,12 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
return chunksCopy;
|
||||
}
|
||||
|
||||
private _sortByPreIndexedDocs(
|
||||
private _sortAlphabetically(
|
||||
submenuItems: ContextSubmenuItem[],
|
||||
): ContextSubmenuItem[] {
|
||||
// Sort submenuItems such that the objects with titles which don't occur in configs occur first, and alphabetized
|
||||
// Sort submenu items alphabetically by title
|
||||
return submenuItems.sort((a, b) => {
|
||||
const aTitleInConfigs = a.metadata?.preIndexed ?? false;
|
||||
const bTitleInConfigs = b.metadata?.preIndexed ?? false;
|
||||
|
||||
// Primary criterion: Items not in configs come first
|
||||
if (!aTitleInConfigs && bTitleInConfigs) {
|
||||
return -1;
|
||||
} else if (aTitleInConfigs && !bTitleInConfigs) {
|
||||
return 1;
|
||||
} else {
|
||||
// Secondary criterion: Alphabetical order when both items are in the same category
|
||||
return a.title.toString().localeCompare(b.title.toString());
|
||||
}
|
||||
return a.title.toString().localeCompare(b.title.toString());
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -165,13 +153,13 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
}
|
||||
await docsService.isInitialized;
|
||||
|
||||
// Create map of docs url -> submenu item
|
||||
const submenuItemsMap = new Map<string, ContextSubmenuItem>();
|
||||
// Create an array to hold submenu items
|
||||
const submenuItems: ContextSubmenuItem[] = [];
|
||||
|
||||
// Add custom docs from config
|
||||
// Get all indexed docs from the database
|
||||
const docs = (await docsService.listMetadata()) ?? [];
|
||||
for (const { startUrl, title, favicon } of docs) {
|
||||
submenuItemsMap.set(startUrl, {
|
||||
submenuItems.push({
|
||||
title,
|
||||
id: startUrl,
|
||||
description: new URL(startUrl).hostname,
|
||||
|
|
@ -179,32 +167,8 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
});
|
||||
}
|
||||
|
||||
// Add pre-indexed docs if supported
|
||||
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
|
||||
if (canUsePreindexedDocs) {
|
||||
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
|
||||
// Skip if overridden in config
|
||||
if (docs.find((d) => d.startUrl === startUrl)) {
|
||||
continue;
|
||||
}
|
||||
submenuItemsMap.set(startUrl, {
|
||||
title,
|
||||
id: startUrl,
|
||||
description: new URL(startUrl).hostname,
|
||||
metadata: {
|
||||
preIndexed: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Create array and sort if pre-indexed is supported
|
||||
const submenuItems = Array.from(submenuItemsMap.values());
|
||||
if (canUsePreindexedDocs) {
|
||||
return this._sortByPreIndexedDocs(submenuItems);
|
||||
}
|
||||
|
||||
return submenuItems;
|
||||
// Sort alphabetically
|
||||
return this._sortAlphabetically(submenuItems);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ class FolderContextProvider extends BaseContextProvider {
|
|||
const folders = await walkDirs(
|
||||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
include: "dirs",
|
||||
source: "load submenu items - folder",
|
||||
},
|
||||
workspaceDirs,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,40 @@
|
|||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
import { fileURLToPath} from "node:url";
|
||||
|
||||
const runGitCommand = (args: string[], cwd: string): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// First argument is the command, rest are arguments
|
||||
const gitProcess = spawn("git", args, {
|
||||
cwd,
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
gitProcess.stdout.on("data", (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
gitProcess.stderr.on("data", (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
gitProcess.on("close", (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`Git command failed: ${stderr}`));
|
||||
return;
|
||||
}
|
||||
resolve(stdout);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
class GitCommitContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
|
|
@ -16,29 +44,55 @@ class GitCommitContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
async getContextItems(query: string, extras: ContextProviderExtras): Promise<ContextItem[]> {
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10;
|
||||
if (typeof lastXCommitsDepth !== "number") {
|
||||
throw new Error("LastXCommitsDepth must be a number");
|
||||
}
|
||||
const topLevelDir = fileURLToPath((await extras.ide.getWorkspaceDirs())[0]);
|
||||
try{
|
||||
if(query.includes("last ")){
|
||||
|
||||
try {
|
||||
if (query.includes("last ")) {
|
||||
const content = await runGitCommand(
|
||||
[
|
||||
"--no-pager",
|
||||
"log",
|
||||
'--pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b"',
|
||||
"-p",
|
||||
"-n",
|
||||
lastXCommitsDepth.toString(),
|
||||
],
|
||||
topLevelDir,
|
||||
);
|
||||
return [
|
||||
{
|
||||
name: query,
|
||||
description: query,
|
||||
content: (await extras.ide.subprocess(`git --no-pager log --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" -p -n ${lastXCommitsDepth}`, topLevelDir))[0],
|
||||
}
|
||||
]
|
||||
}
|
||||
else{
|
||||
name: query,
|
||||
description: query,
|
||||
content,
|
||||
},
|
||||
];
|
||||
} else {
|
||||
const content = await runGitCommand(
|
||||
[
|
||||
"--no-pager",
|
||||
"show",
|
||||
'--pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b"',
|
||||
query,
|
||||
],
|
||||
topLevelDir,
|
||||
);
|
||||
return [
|
||||
{
|
||||
name: query,
|
||||
description: `commit ${query}`,
|
||||
content: (await extras.ide.subprocess(`git --no-pager show --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" ${query}`, topLevelDir))[0],
|
||||
}
|
||||
]
|
||||
content,
|
||||
},
|
||||
];
|
||||
}
|
||||
}catch(err){
|
||||
} catch (err) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
@ -48,24 +102,48 @@ class GitCommitContextProvider extends BaseContextProvider {
|
|||
): Promise<ContextSubmenuItem[]> {
|
||||
const depth = this.options?.Depth ?? 50;
|
||||
const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10;
|
||||
const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]);
|
||||
try{
|
||||
const [gitResult] = await args.ide.subprocess(`git --no-pager log --pretty=format:"%H%x00%s" -n ${depth}`, topLevelDir);
|
||||
const recentCommits = [{ id: `last ${lastXCommitsDepth} commits`, title: `last ${lastXCommitsDepth} commits`, description: "recent commits" }];
|
||||
const allCommits = gitResult
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(line => {
|
||||
const [hash, message] = line.split("\0");
|
||||
return {
|
||||
id: hash,
|
||||
title: message,
|
||||
description: hash
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof depth !== "number") {
|
||||
throw new Error("Depth must be a number");
|
||||
}
|
||||
if (typeof lastXCommitsDepth !== "number") {
|
||||
throw new Error("LastXCommitsDepth must be a number");
|
||||
}
|
||||
|
||||
const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]);
|
||||
try {
|
||||
const gitResult = await runGitCommand(
|
||||
[
|
||||
"--no-pager",
|
||||
"log",
|
||||
'--pretty=format:"%H%x00%s"',
|
||||
`-n`,
|
||||
depth.toString(),
|
||||
],
|
||||
topLevelDir,
|
||||
);
|
||||
const recentCommits = [
|
||||
{
|
||||
id: `last ${lastXCommitsDepth} commits`,
|
||||
title: `last ${lastXCommitsDepth} commits`,
|
||||
description: "recent commits",
|
||||
},
|
||||
];
|
||||
const allCommits = gitResult
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => {
|
||||
let [hash, message] = line.split("\0");
|
||||
hash = hash.replace(/"/g, "");
|
||||
message = message.replace(/"/g, "");
|
||||
return {
|
||||
id: hash,
|
||||
title: message,
|
||||
description: hash,
|
||||
};
|
||||
});
|
||||
return recentCommits.concat(allCommits);
|
||||
}catch(err: any){
|
||||
} catch (err: any) {
|
||||
//could be nice to toast the error eg. not a git repo or git is not installed
|
||||
return [];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { MCPManagerSingleton } from "../mcp";
|
|||
|
||||
interface MCPContextProviderOptions {
|
||||
mcpId: string;
|
||||
serverName: string;
|
||||
submenuItems: ContextSubmenuItem[];
|
||||
}
|
||||
|
||||
|
|
@ -20,6 +21,16 @@ class MCPContextProvider extends BaseContextProvider {
|
|||
description: "Model Context Protocol",
|
||||
type: "submenu",
|
||||
};
|
||||
override get description(): ContextProviderDescription {
|
||||
return {
|
||||
title: `${MCPContextProvider.description.title}-${this.options["mcpId"]}`,
|
||||
displayTitle: this.options["serverName"]
|
||||
? `${this.options["serverName"]} resources`
|
||||
: "MCP",
|
||||
description: "Model Context Protocol",
|
||||
type: "submenu",
|
||||
};
|
||||
}
|
||||
|
||||
static encodeMCPResourceId(mcpId: string, uri: string): string {
|
||||
return JSON.stringify({ mcpId, uri });
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ class RepoMapContextProvider extends BaseContextProvider {
|
|||
const folders = await walkDirs(
|
||||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
include: "dirs",
|
||||
source: "load submenu items - repo map",
|
||||
},
|
||||
workspaceDirs,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class SearchContextProvider extends BaseContextProvider {
|
||||
|
|
@ -19,10 +20,11 @@ class SearchContextProvider extends BaseContextProvider {
|
|||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const results = await extras.ide.getSearchResults(query);
|
||||
const formatted = formatGrepSearchResults(results);
|
||||
return [
|
||||
{
|
||||
description: "Search results",
|
||||
content: `Results of searching codebase for "${query}":\n\n${results}`,
|
||||
content: `Results of searching codebase for "${query}":\n\n${formatted}`,
|
||||
name: "Search results",
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
IContextProvider,
|
||||
} from "../..";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { LLMLogger } from "../../llm/logger";
|
||||
import { TEST_DIR } from "../../test/testDir";
|
||||
import FileSystemIde from "../../util/filesystem";
|
||||
|
||||
|
|
@ -26,13 +27,13 @@ async function getContextProviderExtras(
|
|||
): Promise<ContextProviderExtras> {
|
||||
const ide = new FileSystemIde(TEST_DIR);
|
||||
const ideSettingsPromise = ide.getIdeSettings();
|
||||
const llmLogger = new LLMLogger();
|
||||
const configHandler = new ConfigHandler(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
async (text) => {},
|
||||
llmLogger,
|
||||
Promise.resolve(undefined),
|
||||
);
|
||||
await configHandler.initializedPromise;
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not found");
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
FQSN,
|
||||
FullSlug,
|
||||
SecretResult,
|
||||
SecretType,
|
||||
} from "@continuedev/config-yaml";
|
||||
import fetch, { RequestInit, Response } from "node-fetch";
|
||||
|
||||
|
|
@ -46,7 +47,14 @@ export class ControlPlaneClient {
|
|||
): Promise<(SecretResult | undefined)[]> {
|
||||
const userId = await this.userId;
|
||||
if (!userId) {
|
||||
throw new Error("No user id");
|
||||
return fqsns.map((fqsn) => ({
|
||||
found: false,
|
||||
fqsn,
|
||||
secretLocation: {
|
||||
secretName: fqsn.secretName,
|
||||
secretType: SecretType.NotFound,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
const resp = await this.request("ide/sync-secrets", {
|
||||
|
|
|
|||
115
core/core.ts
115
core/core.ts
|
|
@ -10,7 +10,7 @@ import {
|
|||
setupLocalConfig,
|
||||
setupQuickstartConfig,
|
||||
} from "./config/onboarding";
|
||||
import { addContextProvider, addModel, deleteModel } from "./config/util";
|
||||
import { addModel, deleteModel } from "./config/util";
|
||||
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
|
||||
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
|
||||
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
|
||||
|
|
@ -29,7 +29,7 @@ import { ChatDescriber } from "./util/chatDescriber";
|
|||
import { clipboardCache } from "./util/clipboardCache";
|
||||
import { GlobalContext } from "./util/GlobalContext";
|
||||
import historyManager from "./util/history";
|
||||
import { editConfigJson, migrateV1DevDataFiles } from "./util/paths";
|
||||
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
|
||||
import { Telemetry } from "./util/posthog";
|
||||
import { getSymbolsForManyFiles } from "./util/treeSitter";
|
||||
import { TTS } from "./util/tts";
|
||||
|
|
@ -41,10 +41,12 @@ import {
|
|||
type IndexingProgressUpdate,
|
||||
} from ".";
|
||||
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
|
||||
import { MCPManagerSingleton } from "./context/mcp";
|
||||
import { shouldIgnore } from "./indexing/shouldIgnore";
|
||||
import { walkDirCache } from "./indexing/walkDir";
|
||||
import { LLMLogger } from "./llm/logger";
|
||||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
|
@ -57,6 +59,7 @@ export class Core {
|
|||
codebaseIndexingState: IndexingProgressUpdate;
|
||||
private docsService: DocsService;
|
||||
private globalContext = new GlobalContext();
|
||||
llmLogger = new LLMLogger();
|
||||
|
||||
private readonly indexingPauseToken = new PauseToken(
|
||||
this.globalContext.get("indexingPaused") === true,
|
||||
|
|
@ -84,7 +87,6 @@ export class Core {
|
|||
constructor(
|
||||
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
private readonly ide: IDE,
|
||||
private readonly onWrite: (text: string) => Promise<void> = async () => {},
|
||||
) {
|
||||
// Ensure .continue directory is created
|
||||
migrateV1DevDataFiles();
|
||||
|
|
@ -105,13 +107,8 @@ export class Core {
|
|||
this.configHandler = new ConfigHandler(
|
||||
this.ide,
|
||||
ideSettingsPromise,
|
||||
this.onWrite,
|
||||
this.llmLogger,
|
||||
sessionInfoPromise,
|
||||
(orgId: string | null) => {
|
||||
void messenger.request("didSelectOrganization", {
|
||||
orgId,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
this.docsService = DocsService.createSingleton(
|
||||
|
|
@ -122,8 +119,6 @@ export class Core {
|
|||
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.onConnectionsRefreshed = async () => {
|
||||
// This ensures that it triggers a NEW load after waiting for config promise to finish
|
||||
await this.configHandler.loadConfig();
|
||||
await this.configHandler.reloadConfig();
|
||||
};
|
||||
|
||||
|
|
@ -132,7 +127,11 @@ export class Core {
|
|||
this.messenger.send("configUpdate", {
|
||||
result: serializedResult,
|
||||
profileId:
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null,
|
||||
this.configHandler.currentProfile?.profileDescription.id || null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
usingContinueForTeams: (await ideSettingsPromise)
|
||||
.enableControlServerBeta,
|
||||
});
|
||||
|
||||
// update additional submenu context providers registered via VSCode API
|
||||
|
|
@ -145,14 +144,6 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
this.configHandler.onDidChangeAvailableProfiles(
|
||||
(profiles, selectedProfileId) =>
|
||||
this.messenger.send("didChangeAvailableProfiles", {
|
||||
profiles,
|
||||
selectedProfileId,
|
||||
}),
|
||||
);
|
||||
|
||||
// Dev Data Logger
|
||||
const dataLogger = DataLogger.getInstance();
|
||||
dataLogger.core = this;
|
||||
|
|
@ -307,19 +298,8 @@ export class Core {
|
|||
this.configHandler.updateIdeSettings(msg.data);
|
||||
});
|
||||
|
||||
on("config/listProfiles", async (msg) => {
|
||||
const profiles = this.configHandler.listProfiles();
|
||||
const selectedProfileId =
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null;
|
||||
return { profiles, selectedProfileId };
|
||||
});
|
||||
|
||||
on("config/refreshProfiles", async (msg) => {
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
});
|
||||
|
||||
on("config/addContextProvider", async (msg) => {
|
||||
addContextProvider(msg.data, this.configHandler);
|
||||
await this.configHandler.refreshAll();
|
||||
});
|
||||
|
||||
on("config/updateSharedConfig", async (msg) => {
|
||||
|
|
@ -347,10 +327,6 @@ export class Core {
|
|||
await this.messenger.request("openUrl", url);
|
||||
});
|
||||
|
||||
on("controlPlane/listOrganizations", async (msg) => {
|
||||
return await this.configHandler.listOrganizations();
|
||||
});
|
||||
|
||||
on("mcp/reloadServer", async (msg) => {
|
||||
mcpManager.refreshConnection(msg.data.id);
|
||||
});
|
||||
|
|
@ -483,6 +459,10 @@ export class Core {
|
|||
result: await this.configHandler.getSerializedConfig(),
|
||||
profileId:
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
usingContinueForTeams: (await ideSettingsPromise)
|
||||
.enableControlServerBeta,
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -607,38 +587,55 @@ export class Core {
|
|||
return;
|
||||
}
|
||||
|
||||
let editConfigJsonCallback: Parameters<typeof editConfigJson>[0];
|
||||
let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
|
||||
|
||||
switch (mode) {
|
||||
case "Local":
|
||||
editConfigJsonCallback = setupLocalConfig;
|
||||
editConfigYamlCallback = setupLocalConfig;
|
||||
break;
|
||||
|
||||
case "Quickstart":
|
||||
editConfigJsonCallback = setupQuickstartConfig;
|
||||
editConfigYamlCallback = setupQuickstartConfig;
|
||||
break;
|
||||
|
||||
case "Best":
|
||||
editConfigJsonCallback = setupBestConfig;
|
||||
editConfigYamlCallback = setupBestConfig;
|
||||
break;
|
||||
|
||||
default:
|
||||
console.error(`Invalid mode: ${mode}`);
|
||||
editConfigJsonCallback = (config) => config;
|
||||
editConfigYamlCallback = (config) => config;
|
||||
}
|
||||
|
||||
editConfigJson(editConfigJsonCallback);
|
||||
editConfigFile((c) => c, editConfigYamlCallback);
|
||||
|
||||
void this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("addAutocompleteModel", (msg) => {
|
||||
editConfigJson((config) => {
|
||||
return {
|
||||
const model = msg.data.model;
|
||||
editConfigFile(
|
||||
(config) => {
|
||||
return {
|
||||
...config,
|
||||
tabAutocompleteModel: model,
|
||||
};
|
||||
},
|
||||
(config) => ({
|
||||
...config,
|
||||
tabAutocompleteModel: msg.data.model,
|
||||
};
|
||||
});
|
||||
models: [
|
||||
...(config.models ?? []),
|
||||
{
|
||||
name: model.title,
|
||||
provider: model.provider,
|
||||
model: model.model,
|
||||
apiKey: model.apiKey,
|
||||
roles: ["autocomplete"],
|
||||
apiBase: model.apiBase,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
void this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
|
|
@ -761,11 +758,15 @@ export class Core {
|
|||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
|
||||
let localAssistantCreated = false;
|
||||
for (const uri of data.uris) {
|
||||
if (isLocalAssistantFile(uri)) {
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
localAssistantCreated = true;
|
||||
}
|
||||
}
|
||||
if (localAssistantCreated) {
|
||||
await this.configHandler.refreshAll();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -815,20 +816,14 @@ export class Core {
|
|||
//
|
||||
|
||||
on("didChangeSelectedProfile", async (msg) => {
|
||||
await this.configHandler.setSelectedProfile(msg.data.id);
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.setSelectedProfileId(msg.data.id);
|
||||
});
|
||||
|
||||
on("didChangeSelectedOrg", async (msg) => {
|
||||
await this.configHandler.setSelectedOrgId(msg.data.id);
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
if (msg.data.profileId) {
|
||||
this.invoke("didChangeSelectedProfile", {
|
||||
id: msg.data.profileId,
|
||||
});
|
||||
} else {
|
||||
await this.configHandler.reloadConfig();
|
||||
}
|
||||
await this.configHandler.setSelectedOrgId(
|
||||
msg.data.id,
|
||||
msg.data.profileId,
|
||||
);
|
||||
});
|
||||
|
||||
on("didChangeControlPlaneSessionInfo", async (msg) => {
|
||||
|
|
@ -836,6 +831,7 @@ export class Core {
|
|||
msg.data.sessionInfo,
|
||||
);
|
||||
});
|
||||
|
||||
on("auth/getAuthUrl", async (msg) => {
|
||||
const url = await getAuthUrlForTokenPage(
|
||||
ideSettingsPromise,
|
||||
|
|
@ -979,4 +975,3 @@ export class Core {
|
|||
|
||||
// private
|
||||
}
|
||||
|
||||
|
|
|
|||
109
core/index.d.ts
vendored
109
core/index.d.ts
vendored
|
|
@ -1,6 +1,7 @@
|
|||
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
|
||||
import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
|
|
@ -89,7 +90,7 @@ export interface ILLM extends LLMOptions {
|
|||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
llmLogger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
|
|
@ -236,7 +237,6 @@ export interface SiteIndexingConfig {
|
|||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
useLocalCrawling?: boolean;
|
||||
rootUrl?: string; // Currently only used by preindexed docs
|
||||
}
|
||||
|
||||
export interface DocsIndexingDetails {
|
||||
|
|
@ -244,7 +244,6 @@ export interface DocsIndexingDetails {
|
|||
config: SiteIndexingConfig;
|
||||
indexingStatus: IndexingStatus | undefined;
|
||||
chunks: Chunk[];
|
||||
isPreIndexedDoc: boolean;
|
||||
}
|
||||
|
||||
export interface IContextProvider {
|
||||
|
|
@ -484,6 +483,94 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions {
|
|||
|
||||
export type ToastType = "info" | "error" | "warning";
|
||||
|
||||
export interface LLMInteractionBase {
|
||||
interactionId: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartChat extends LLMInteractionBase {
|
||||
kind: "startChat";
|
||||
messages: ChatMessage[];
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartComplete extends LLMInteractionBase {
|
||||
kind: "startComplete";
|
||||
prompt: string;
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartFim extends LLMInteractionBase {
|
||||
kind: "startFim";
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
options: CompletionOptions;
|
||||
}
|
||||
|
||||
export interface LLMInteractionChunk extends LLMInteractionBase {
|
||||
kind: "chunk";
|
||||
chunk: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionMessage extends LLMInteractionBase {
|
||||
kind: "message";
|
||||
message: ChatMessage;
|
||||
}
|
||||
|
||||
export interface LLMInteractionEnd extends LLMInteractionBase {
|
||||
promptTokens: number;
|
||||
generatedTokens: number;
|
||||
thinkingTokens: number;
|
||||
}
|
||||
|
||||
export interface LLMInteractionSuccess extends LLMInteractionEnd {
|
||||
kind: "success";
|
||||
}
|
||||
|
||||
export interface LLMInteractionCancel extends LLMInteractionEnd {
|
||||
kind: "cancel";
|
||||
}
|
||||
|
||||
export interface LLMInteractionError extends LLMInteractionEnd {
|
||||
kind: "error";
|
||||
name: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type LLMInteractionItem =
|
||||
| LLMInteractionStartChat
|
||||
| LLMInteractionStartComplete
|
||||
| LLMInteractionStartFim
|
||||
| LLMInteractionChunk
|
||||
| LLMInteractionMessage
|
||||
| LLMInteractionSuccess
|
||||
| LLMInteractionCancel
|
||||
| LLMInteractionError;
|
||||
|
||||
// When we log a LLM interaction, we want to add the interactionId and timestamp
|
||||
// in the logger code, so we need a type that omits these members from *each*
|
||||
// member of the union. This can be done by using the distributive behavior of
|
||||
// conditional types in Typescript.
|
||||
//
|
||||
// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
|
||||
// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s
|
||||
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
|
||||
? Omit<T, K>
|
||||
: never;
|
||||
|
||||
export type LLMInteractionItemDetails = DistributiveOmit<
|
||||
LLMInteractionItem,
|
||||
"interactionId" | "timestamp"
|
||||
>;
|
||||
|
||||
export interface ILLMInteractionLog {
|
||||
logItem(item: LLMInteractionItemDetails): void;
|
||||
}
|
||||
|
||||
export interface ILLMLogger {
|
||||
createInteractionLog(): ILLMInteractionLog;
|
||||
}
|
||||
|
||||
export interface LLMOptions {
|
||||
model: string;
|
||||
|
||||
|
|
@ -497,8 +584,9 @@ export interface LLMOptions {
|
|||
template?: TemplateType;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
rules?: Rule[];
|
||||
apiKey?: string;
|
||||
|
||||
// continueProperties
|
||||
|
|
@ -711,6 +799,8 @@ export interface IDE {
|
|||
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
|
||||
getFileResults(pattern: string): Promise<string[]>;
|
||||
|
||||
subprocess(command: string, cwd?: string): Promise<[string, string]>;
|
||||
|
||||
getProblems(fileUri?: string | undefined): Promise<Problem[]>;
|
||||
|
|
@ -905,7 +995,9 @@ export interface Tool {
|
|||
};
|
||||
|
||||
displayTitle: string;
|
||||
wouldLikeTo: string;
|
||||
wouldLikeTo?: string;
|
||||
isCurrently?: string;
|
||||
hasAlready?: string;
|
||||
readonly: boolean;
|
||||
uri?: string;
|
||||
faviconUrl?: string;
|
||||
|
|
@ -1142,6 +1234,7 @@ export interface ApplyState {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
toolCallId?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
|
|
@ -1313,7 +1406,7 @@ export interface ContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: string[];
|
||||
rules?: Rule[];
|
||||
modelsByRole: Record<ModelRole, ILLM[]>;
|
||||
selectedModelByRole: Record<ModelRole, ILLM | null>;
|
||||
data?: DataDestination[];
|
||||
|
|
@ -1336,7 +1429,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: string[];
|
||||
rules?: Rule[];
|
||||
usePlatform: boolean;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
modelsByRole: Record<ModelRole, ModelDescription[]>;
|
||||
|
|
|
|||
25
core/indexing/docs/DocsCache.test.ts
Normal file
25
core/indexing/docs/DocsCache.test.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import OpenAI from "../../llm/llms/OpenAI";
|
||||
import { DocsCache } from "./DocsCache"; // adjust import path as needed
|
||||
|
||||
describe("DocsCache", () => {
|
||||
let openAIEmbeddings: OpenAI;
|
||||
|
||||
beforeAll(() => {
|
||||
openAIEmbeddings = new OpenAI({
|
||||
apiKey: "",
|
||||
model: "text-embedding-ada-002",
|
||||
});
|
||||
});
|
||||
|
||||
test("normalizeEmbeddingId() produces a valid ID without constructor name", async () => {
|
||||
// Get the embedding ID from OpenAI embeddings provider
|
||||
const embeddingId = DocsCache.normalizeEmbeddingId(
|
||||
openAIEmbeddings.embeddingId,
|
||||
);
|
||||
|
||||
// The ID should not contain the constructor name (OpenAI)
|
||||
expect(embeddingId).toEqual(
|
||||
`${openAIEmbeddings.model}::${openAIEmbeddings.maxEmbeddingChunkSize}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
83
core/indexing/docs/DocsCache.ts
Normal file
83
core/indexing/docs/DocsCache.ts
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
import request from "request";
|
||||
import { Chunk } from "../..";
|
||||
|
||||
export interface SiteIndexingResults {
|
||||
chunks: (Chunk & { embedding: number[] })[];
|
||||
url: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export class DocsCache {
|
||||
static readonly AWS_REGION: string = "us-west-1";
|
||||
static readonly BUCKET_NAME: string = "continue-preindexed-docs";
|
||||
|
||||
/**
|
||||
* Normalizes an embedding ID by stripping the constructor name part.
|
||||
* This is done because we don't care about the provider, just the
|
||||
* model and the max embedding chunk size.
|
||||
*/
|
||||
static normalizeEmbeddingId(embeddingId: string): string {
|
||||
// Split by "::" and remove the first part (constructor name)
|
||||
const parts = embeddingId.split("::");
|
||||
if (parts.length <= 1) return embeddingId; // Return original if no "::" found
|
||||
|
||||
// Return everything except the first part, joining with "::"
|
||||
return parts.slice(1).join("::");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the filepath for a given embedding ID and URL
|
||||
*/
|
||||
static getFilepathForEmbeddingIdAndUrl(
|
||||
embeddingId: string,
|
||||
url: string,
|
||||
): string {
|
||||
const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
|
||||
const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_"));
|
||||
return normalizedEmbeddingId + "/" + normalizedUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the fully qualified S3 URL for a given filepath
|
||||
*/
|
||||
private static getS3Url(filepath: string): string {
|
||||
const pathname = filepath.split("/").map(encodeURIComponent).join("/");
|
||||
return `https://${this.BUCKET_NAME}.s3.${this.AWS_REGION}.amazonaws.com/${pathname}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads cached site indexing results from S3 for a given embedding ID and URL
|
||||
* @param embeddingId The embedding ID
|
||||
* @param url The URL of the document
|
||||
* @returns The downloaded data as a string
|
||||
*/
|
||||
static async getDocsCacheForUrl(
|
||||
embeddingId: string,
|
||||
url: string,
|
||||
): Promise<string> {
|
||||
const filepath = DocsCache.getFilepathForEmbeddingIdAndUrl(
|
||||
embeddingId,
|
||||
url,
|
||||
);
|
||||
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
let data = "";
|
||||
const url = this.getS3Url(filepath);
|
||||
const download = request({
|
||||
url,
|
||||
});
|
||||
|
||||
download.on("response", (response: any) => {
|
||||
if (response.statusCode !== 200) {
|
||||
reject(
|
||||
new Error("There was an error retrieving the pre-indexed doc"),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
download.on("error", (err: any) => reject(err));
|
||||
download.on("data", (chunk: any) => (data += chunk));
|
||||
download.on("end", () => resolve(data));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,156 +1,157 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { ConfigHandler } from "../../config/ConfigHandler.js";
|
||||
import { SiteIndexingConfig } from "../../index.js";
|
||||
import FileSystemIde from "../../util/filesystem.js";
|
||||
import { editConfigJson } from "../../util/paths.js";
|
||||
// /**
|
||||
// * @jest-environment jsdom
|
||||
// */
|
||||
// import { ConfigHandler } from "../../config/ConfigHandler.js";
|
||||
// import { SiteIndexingConfig } from "../../index.js";
|
||||
// import { LLMLogger } from "../../llm/logger.js";
|
||||
// import FileSystemIde from "../../util/filesystem.js";
|
||||
// import { editConfigJson } from "../../util/paths.js";
|
||||
|
||||
import DocsService from "./DocsService.js";
|
||||
import preIndexedDocs from "./preIndexedDocs.js";
|
||||
// import DocsService from "./DocsService.js";
|
||||
// import preIndexedDocs from "./preIndexedDocs.js";
|
||||
|
||||
describe.skip("DocsService Integration Tests", () => {
|
||||
let ide: FileSystemIde;
|
||||
let configHandler: ConfigHandler;
|
||||
let docsService: DocsService;
|
||||
// describe.skip("DocsService Integration Tests", () => {
|
||||
// let ide: FileSystemIde;
|
||||
// let configHandler: ConfigHandler;
|
||||
// let docsService: DocsService;
|
||||
|
||||
const mockSiteConfig: SiteIndexingConfig = {
|
||||
startUrl: "https://amplified.dev/",
|
||||
title: "Test repo",
|
||||
faviconUrl: "https://github.com/favicon.ico",
|
||||
};
|
||||
// const mockSiteConfig: SiteIndexingConfig = {
|
||||
// startUrl: "https://amplified.dev/",
|
||||
// title: "Test repo",
|
||||
// faviconUrl: "https://github.com/favicon.ico",
|
||||
// };
|
||||
|
||||
/**
|
||||
* We need to reload config explicitly to handle the scenario where the
|
||||
* config file update listeners are not called before we attempt to
|
||||
* use the new config
|
||||
*/
|
||||
async function getReloadedConfig() {
|
||||
await configHandler.reloadConfig();
|
||||
const latestConfig = await configHandler.loadConfig();
|
||||
// /**
|
||||
// * We need to reload config explicitly to handle the scenario where the
|
||||
// * config file update listeners are not called before we attempt to
|
||||
// * use the new config
|
||||
// */
|
||||
// async function getReloadedConfig() {
|
||||
// await configHandler.reloadConfig();
|
||||
// const latestConfig = await configHandler.loadConfig();
|
||||
|
||||
return latestConfig;
|
||||
}
|
||||
// return latestConfig;
|
||||
// }
|
||||
|
||||
beforeEach(async () => {
|
||||
ide = new FileSystemIde(process.cwd());
|
||||
// beforeEach(async () => {
|
||||
// ide = new FileSystemIde(process.cwd());
|
||||
|
||||
const ideSettingsPromise = Promise.resolve({
|
||||
remoteConfigSyncPeriod: 60,
|
||||
userToken: "",
|
||||
enableControlServerBeta: false,
|
||||
continueTestEnvironment: "none" as const,
|
||||
pauseCodebaseIndexOnStart: false,
|
||||
ideSettings: {} as any,
|
||||
enableDebugLogs: false,
|
||||
remoteConfigServerUrl: "",
|
||||
});
|
||||
configHandler = new ConfigHandler(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
async () => {},
|
||||
Promise.resolve(undefined),
|
||||
);
|
||||
// const ideSettingsPromise = Promise.resolve({
|
||||
// remoteConfigSyncPeriod: 60,
|
||||
// userToken: "",
|
||||
// enableControlServerBeta: false,
|
||||
// continueTestEnvironment: "none" as const,
|
||||
// pauseCodebaseIndexOnStart: false,
|
||||
// ideSettings: {} as any,
|
||||
// enableDebugLogs: false,
|
||||
// remoteConfigServerUrl: "",
|
||||
// });
|
||||
// configHandler = new ConfigHandler(
|
||||
// ide,
|
||||
// ideSettingsPromise,
|
||||
// new LLMLogger(),
|
||||
// Promise.resolve(undefined),
|
||||
// );
|
||||
|
||||
docsService = DocsService.createSingleton(configHandler, ide);
|
||||
// docsService = DocsService.createSingleton(configHandler, ide);
|
||||
|
||||
await docsService.isInitialized;
|
||||
});
|
||||
// await docsService.isInitialized;
|
||||
// });
|
||||
|
||||
test("Indexing, retrieval, and deletion of a new documentation site", async () => {
|
||||
await docsService.indexAndAdd(mockSiteConfig);
|
||||
// test("Indexing, retrieval, and deletion of a new documentation site", async () => {
|
||||
// await docsService.indexAndAdd(mockSiteConfig);
|
||||
|
||||
let latestConfig = await getReloadedConfig();
|
||||
// let latestConfig = await getReloadedConfig();
|
||||
|
||||
// Sqlite check
|
||||
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
|
||||
// // Sqlite check
|
||||
// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
|
||||
|
||||
// config.json check
|
||||
expect(latestConfig.config!.docs).toContainEqual(mockSiteConfig);
|
||||
// // config.json check
|
||||
// expect(latestConfig.config!.docs).toContainEqual(mockSiteConfig);
|
||||
|
||||
// Lance DB check
|
||||
let retrievedChunks = await docsService.retrieveChunksFromQuery(
|
||||
"test",
|
||||
mockSiteConfig.startUrl,
|
||||
5,
|
||||
);
|
||||
// // Lance DB check
|
||||
// let retrievedChunks = await docsService.retrieveChunksFromQuery(
|
||||
// "test",
|
||||
// mockSiteConfig.startUrl,
|
||||
// 5,
|
||||
// );
|
||||
|
||||
expect(retrievedChunks.length).toBeGreaterThan(0);
|
||||
// expect(retrievedChunks.length).toBeGreaterThan(0);
|
||||
|
||||
await docsService.delete(mockSiteConfig.startUrl);
|
||||
// await docsService.delete(mockSiteConfig.startUrl);
|
||||
|
||||
// Sqlite check
|
||||
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
|
||||
// // Sqlite check
|
||||
// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
|
||||
|
||||
// config.json check
|
||||
latestConfig = await getReloadedConfig();
|
||||
expect(latestConfig.config!.docs).not.toContainEqual(
|
||||
expect.objectContaining(mockSiteConfig),
|
||||
);
|
||||
// // config.json check
|
||||
// latestConfig = await getReloadedConfig();
|
||||
// expect(latestConfig.config!.docs).not.toContainEqual(
|
||||
// expect.objectContaining(mockSiteConfig),
|
||||
// );
|
||||
|
||||
// LanceDB check
|
||||
retrievedChunks = await docsService.retrieveChunksFromQuery(
|
||||
"test",
|
||||
mockSiteConfig.startUrl,
|
||||
5,
|
||||
);
|
||||
expect(retrievedChunks.length).toBe(0);
|
||||
});
|
||||
// // LanceDB check
|
||||
// retrievedChunks = await docsService.retrieveChunksFromQuery(
|
||||
// "test",
|
||||
// mockSiteConfig.startUrl,
|
||||
// 5,
|
||||
// );
|
||||
// expect(retrievedChunks.length).toBe(0);
|
||||
// });
|
||||
|
||||
// test("Reindexes when changing embeddings provider", async () => {
|
||||
// const originalEmbeddingsProvider =
|
||||
// await docsService.getEmbeddingsProvider();
|
||||
// // test("Reindexes when changing embeddings provider", async () => {
|
||||
// // const originalEmbeddingsProvider =
|
||||
// // await docsService.getEmbeddingsProvider();
|
||||
|
||||
// // Change embeddings provider
|
||||
// editConfigJson((config) => ({
|
||||
// ...config,
|
||||
// embeddingsProvider: {
|
||||
// provider: FreeTrial.providerName,
|
||||
// },
|
||||
// }));
|
||||
// // // Change embeddings provider
|
||||
// // editConfigJson((config) => ({
|
||||
// // ...config,
|
||||
// // embeddingsProvider: {
|
||||
// // provider: FreeTrial.providerName,
|
||||
// // },
|
||||
// // }));
|
||||
|
||||
// await getReloadedConfig();
|
||||
// // await getReloadedConfig();
|
||||
|
||||
// const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
|
||||
// // const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
|
||||
|
||||
// // Verify reindexing
|
||||
// const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
|
||||
// const [newMockVector] = await provider.embed(["test"]);
|
||||
// // // Verify reindexing
|
||||
// // const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
|
||||
// // const [newMockVector] = await provider.embed(["test"]);
|
||||
|
||||
// expect(originalVector).not.toEqual(newMockVector);
|
||||
// });
|
||||
// // expect(originalVector).not.toEqual(newMockVector);
|
||||
// // });
|
||||
|
||||
test("Handles pulling down and adding pre-indexed docs", async () => {
|
||||
const preIndexedDoc = Object.values(preIndexedDocs)[0];
|
||||
await docsService.indexAndAdd(preIndexedDoc);
|
||||
});
|
||||
// test("Handles pulling down and adding pre-indexed docs", async () => {
|
||||
// const preIndexedDoc = Object.values(preIndexedDocs)[0];
|
||||
// await docsService.indexAndAdd(preIndexedDoc);
|
||||
// });
|
||||
|
||||
test("Config synchronization with SQLite", async () => {
|
||||
await docsService.indexAndAdd(mockSiteConfig);
|
||||
// test("Config synchronization with SQLite", async () => {
|
||||
// await docsService.indexAndAdd(mockSiteConfig);
|
||||
|
||||
await getReloadedConfig();
|
||||
// await getReloadedConfig();
|
||||
|
||||
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
|
||||
// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
|
||||
|
||||
editConfigJson((config) => {
|
||||
const { docs, ...restConfig } = config;
|
||||
return restConfig;
|
||||
});
|
||||
// editConfigJson((config) => {
|
||||
// const { docs, ...restConfig } = config;
|
||||
// return restConfig;
|
||||
// });
|
||||
|
||||
await getReloadedConfig();
|
||||
// await getReloadedConfig();
|
||||
|
||||
const startTime = Date.now();
|
||||
const maxWaitTimeMs = 10_000;
|
||||
// const startTime = Date.now();
|
||||
// const maxWaitTimeMs = 10_000;
|
||||
|
||||
while (docsService.isSyncing) {
|
||||
if (Date.now() - startTime > maxWaitTimeMs) {
|
||||
throw new Error(
|
||||
`Timeout: docsService.isSyncing did not complete within within ${maxWaitTimeMs}ms`,
|
||||
);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
// while (docsService.isSyncing) {
|
||||
// if (Date.now() - startTime > maxWaitTimeMs) {
|
||||
// throw new Error(
|
||||
// `Timeout: docsService.isSyncing did not complete within within ${maxWaitTimeMs}ms`,
|
||||
// );
|
||||
// }
|
||||
// await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
// }
|
||||
|
||||
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
|
||||
});
|
||||
});
|
||||
// expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
|
||||
// });
|
||||
// });
|
||||
|
|
|
|||
|
|
@ -13,18 +13,15 @@ import {
|
|||
SiteIndexingConfig,
|
||||
} from "../..";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import {
|
||||
addContextProvider,
|
||||
isSupportedLanceDbCpuTargetForLinux,
|
||||
} from "../../config/util";
|
||||
import { isSupportedLanceDbCpuTargetForLinux } from "../../config/util";
|
||||
import DocsContextProvider from "../../context/providers/DocsContextProvider";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
|
||||
import { IMessenger } from "../../protocol/messenger";
|
||||
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
|
||||
import { fetchFavicon } from "../../util/fetchFavicon";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import {
|
||||
editConfigJson,
|
||||
editConfigFile,
|
||||
getDocsSqlitePath,
|
||||
getLanceDbPath,
|
||||
} from "../../util/paths";
|
||||
|
|
@ -37,15 +34,9 @@ import {
|
|||
} from "./article";
|
||||
import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
|
||||
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
|
||||
import {
|
||||
downloadFromS3,
|
||||
getS3Filename,
|
||||
S3Buckets,
|
||||
SiteIndexingResults,
|
||||
} from "./preIndexed";
|
||||
import preIndexedDocs from "./preIndexedDocs";
|
||||
|
||||
import type * as LanceType from "vectordb";
|
||||
import { DocsCache, SiteIndexingResults } from "./DocsCache";
|
||||
|
||||
// Purposefully lowercase because lancedb converts
|
||||
export interface LanceDbDocsRow {
|
||||
|
|
@ -89,8 +80,7 @@ export default class DocsService {
|
|||
static lanceTableName = "docs";
|
||||
static sqlitebTableName = "docs";
|
||||
|
||||
static preIndexedDocsEmbeddingsProvider =
|
||||
new TransformersJsEmbeddingsProvider();
|
||||
static defaultEmbeddingsProvider = new TransformersJsEmbeddingsProvider();
|
||||
|
||||
public isInitialized: Promise<void>;
|
||||
public isSyncing: boolean = false;
|
||||
|
|
@ -250,12 +240,8 @@ export default class DocsService {
|
|||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Currently, we generate and host embeddings for pre-indexed docs using transformers.
|
||||
* However, we don't ship transformers with the JetBrains extension.
|
||||
* So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs.
|
||||
*/
|
||||
async canUsePreindexedDocs() {
|
||||
// Determine if transformers.js embeddings are supported in this environment
|
||||
async canUseTransformersEmbeddings() {
|
||||
const ideInfo = await this.ideInfoPromise;
|
||||
if (ideInfo.ideType === "jetbrains") {
|
||||
return false;
|
||||
|
|
@ -263,28 +249,26 @@ export default class DocsService {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Determines if using preIndexed and returns proper embeddings provider
|
||||
async getEmbeddingsProvider(startUrl: string) {
|
||||
// Conditions for using a pre-indexed doc
|
||||
|
||||
// Must be in pre indexed docs file
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
if (preIndexedDoc) {
|
||||
// Most not be overriden by config
|
||||
if (!this.config?.docs?.find((doc) => doc.startUrl === startUrl)) {
|
||||
// Must be supported
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
if (canUsePreindexedDocs) {
|
||||
return {
|
||||
provider: DocsService.preIndexedDocsEmbeddingsProvider,
|
||||
isPreindexed: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
// Get the appropriate embeddings provider
|
||||
async getEmbeddingsProvider() {
|
||||
// First check if there's a config selected embeddings provider
|
||||
if (this.config.selectedModelByRole.embed) {
|
||||
return {
|
||||
provider: this.config.selectedModelByRole.embed,
|
||||
};
|
||||
}
|
||||
|
||||
// Fall back to transformers if supported
|
||||
const canUseTransformers = await this.canUseTransformersEmbeddings();
|
||||
if (canUseTransformers) {
|
||||
return {
|
||||
provider: DocsService.defaultEmbeddingsProvider,
|
||||
};
|
||||
}
|
||||
|
||||
// No provider available
|
||||
return {
|
||||
provider: this.config.selectedModelByRole.embed,
|
||||
isPreindexed: false,
|
||||
provider: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -312,29 +296,6 @@ export default class DocsService {
|
|||
}
|
||||
|
||||
async syncDocsWithPrompt(reIndex: boolean = false) {
|
||||
if (!this.hasDocsContextProvider()) {
|
||||
const actionMsg = "Add 'docs' context provider";
|
||||
const res = await this.ide.showToast(
|
||||
"info",
|
||||
"Starting docs indexing",
|
||||
actionMsg,
|
||||
);
|
||||
|
||||
if (res === actionMsg) {
|
||||
addContextProvider({
|
||||
name: DocsContextProvider.description.title,
|
||||
params: {},
|
||||
});
|
||||
|
||||
void this.ide.showToast(
|
||||
"info",
|
||||
"Successfuly added docs context provider",
|
||||
);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await this.syncDocs(undefined, this.config, reIndex);
|
||||
|
||||
void this.ide.showToast("info", "Docs indexing completed");
|
||||
|
|
@ -379,6 +340,45 @@ export default class DocsService {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to load document embeddings from cache
|
||||
* @returns true if cache was successfully loaded, false otherwise
|
||||
*/
|
||||
private async tryLoadFromCache(
|
||||
startUrl: string,
|
||||
embeddingId: string,
|
||||
siteIndexingConfig: SiteIndexingConfig,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
|
||||
|
||||
if (cacheHit) {
|
||||
console.log(`Successfully loaded cached embeddings for ${startUrl}`);
|
||||
// Update status to complete
|
||||
this.handleStatusUpdate({
|
||||
type: "docs",
|
||||
id: startUrl,
|
||||
embeddingsProviderId: embeddingId,
|
||||
isReindexing: false,
|
||||
title: siteIndexingConfig.title,
|
||||
debugInfo: "Loaded from cache",
|
||||
icon: siteIndexingConfig.faviconUrl,
|
||||
url: startUrl,
|
||||
progress: 1,
|
||||
description: "Complete",
|
||||
status: "complete",
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(`Error trying to fetch from cache: ${e}`);
|
||||
// Continue with regular indexing
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async indexAndAdd(
|
||||
siteIndexingConfig: SiteIndexingConfig,
|
||||
forceReindex: boolean = false,
|
||||
|
|
@ -392,21 +392,28 @@ export default class DocsService {
|
|||
return;
|
||||
}
|
||||
|
||||
const { isPreindexed, provider } =
|
||||
await this.getEmbeddingsProvider(startUrl);
|
||||
if (isPreindexed) {
|
||||
console.warn("Attempted to indexAndAdd pre-indexed doc");
|
||||
return;
|
||||
}
|
||||
const { provider } = await this.getEmbeddingsProvider();
|
||||
if (!provider) {
|
||||
console.warn("@docs indexAndAdd: no embeddings provider found");
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to fetch from cache first before crawling
|
||||
if (!forceReindex) {
|
||||
const cacheLoaded = await this.tryLoadFromCache(
|
||||
startUrl,
|
||||
provider.embeddingId,
|
||||
siteIndexingConfig,
|
||||
);
|
||||
|
||||
if (cacheLoaded) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const startedWithEmbedder = provider.embeddingId;
|
||||
|
||||
// Check if doc has been successfully indexed with the given embedder
|
||||
// Note at this point we know it's not a pre-indexed doc
|
||||
const indexExists = await this.hasMetadata(startUrl);
|
||||
|
||||
// Build status update - most of it is fixed values
|
||||
|
|
@ -622,7 +629,7 @@ export default class DocsService {
|
|||
progress: 1,
|
||||
});
|
||||
|
||||
void this.ide.showToast("info", `Failed to index ${startUrl}`);
|
||||
// void this.ide.showToast("info", `Failed to index ${startUrl}`);
|
||||
markFailedInGlobalContext();
|
||||
return;
|
||||
}
|
||||
|
|
@ -672,7 +679,12 @@ export default class DocsService {
|
|||
progress: 1,
|
||||
});
|
||||
|
||||
void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
|
||||
// Only show notificaitons if the user manually re-indexed, otherwise
|
||||
// they are too noisy, especially when switching embeddings providers
|
||||
// and we automatically re-index all docs
|
||||
if (forceReindex) {
|
||||
void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
|
||||
}
|
||||
|
||||
this.messenger?.send("refreshSubmenuItems", {
|
||||
providers: ["docs"],
|
||||
|
|
@ -705,36 +717,42 @@ export default class DocsService {
|
|||
}
|
||||
}
|
||||
|
||||
// When user requests a pre-indexed doc for the first time
|
||||
// And pre-indexed embeddings are supported
|
||||
// Fetch pre-indexed embeddings from S3, add to Lance, and then search those
|
||||
private async fetchAndAddPreIndexedDocEmbeddings(title: string) {
|
||||
const data = await downloadFromS3(
|
||||
S3Buckets.continueIndexedDocs,
|
||||
getS3Filename(
|
||||
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId,
|
||||
title,
|
||||
),
|
||||
);
|
||||
/**
|
||||
* Try to fetch embeddings from the S3 cache for any document URL
|
||||
* @param startUrl The URL of the documentation site
|
||||
* @param embeddingsProviderId The ID of the embeddings provider
|
||||
* @returns True if cache hit and successfully loaded, false otherwise
|
||||
*/
|
||||
private async tryFetchFromCache(
|
||||
startUrl: string,
|
||||
embeddingId: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const data = await DocsCache.getDocsCacheForUrl(embeddingId, startUrl);
|
||||
|
||||
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
|
||||
const startUrl = new URL(siteEmbeddings.url).toString();
|
||||
// Parse the cached data
|
||||
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
|
||||
|
||||
const faviconUrl = preIndexedDocs[startUrl].faviconUrl;
|
||||
const favicon =
|
||||
typeof faviconUrl === "string"
|
||||
? await getFaviconBase64(faviconUrl)
|
||||
: undefined;
|
||||
// Try to get a favicon for the site
|
||||
const favicon = await fetchFavicon(new URL(startUrl));
|
||||
|
||||
await this.add({
|
||||
favicon,
|
||||
siteIndexingConfig: {
|
||||
startUrl,
|
||||
title: siteEmbeddings.title,
|
||||
},
|
||||
chunks: siteEmbeddings.chunks,
|
||||
embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
|
||||
});
|
||||
// Add the cached embeddings to our database
|
||||
await this.add({
|
||||
favicon,
|
||||
siteIndexingConfig: {
|
||||
startUrl,
|
||||
title: siteEmbeddings.title || new URL(startUrl).hostname,
|
||||
},
|
||||
chunks: siteEmbeddings.chunks,
|
||||
embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
// Cache miss or error - silently fail
|
||||
console.log(`Cache miss for ${startUrl} with provider ${embeddingId}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Retrieve docs embeds based on user input
|
||||
|
|
@ -743,8 +761,7 @@ export default class DocsService {
|
|||
startUrl: string,
|
||||
nRetrieve: number,
|
||||
) {
|
||||
const { isPreindexed, provider } =
|
||||
await this.getEmbeddingsProvider(startUrl);
|
||||
const { provider } = await this.getEmbeddingsProvider();
|
||||
|
||||
if (!provider) {
|
||||
void this.ide.showToast(
|
||||
|
|
@ -755,15 +772,11 @@ export default class DocsService {
|
|||
return [];
|
||||
}
|
||||
|
||||
if (isPreindexed) {
|
||||
void Telemetry.capture("docs_pre_indexed_doc_used", {
|
||||
doc: preIndexedDocs[startUrl]!["title"],
|
||||
});
|
||||
}
|
||||
|
||||
// Try to get embeddings for the query
|
||||
const [vector] = await provider.embed([query]);
|
||||
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, isPreindexed);
|
||||
// Retrieve chunks using the query vector
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve);
|
||||
}
|
||||
|
||||
private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk {
|
||||
|
|
@ -783,8 +796,7 @@ export default class DocsService {
|
|||
const db = await this.getOrCreateSqliteDb();
|
||||
|
||||
try {
|
||||
const { isPreindexed, provider } =
|
||||
await this.getEmbeddingsProvider(startUrl);
|
||||
const { provider } = await this.getEmbeddingsProvider();
|
||||
|
||||
if (!provider) {
|
||||
throw new Error("No embeddings model set");
|
||||
|
|
@ -819,22 +831,26 @@ export default class DocsService {
|
|||
config: siteIndexingConfig,
|
||||
indexingStatus: this.statuses.get(startUrl),
|
||||
chunks: rows.map(this.lanceDBRowToChunk),
|
||||
isPreIndexedDoc: isPreindexed,
|
||||
};
|
||||
} catch (e) {
|
||||
console.warn("Error getting details", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
// This is split into its own function so that it can be recursive
|
||||
// in the case of fetching preindexed docs from s3
|
||||
// This function attempts to retrieve chunks by vector similarity
|
||||
// It will also attempt to fetch from cache if no results are found
|
||||
async retrieveChunks(
|
||||
startUrl: string,
|
||||
vector: number[],
|
||||
nRetrieve: number,
|
||||
isPreindexed: boolean,
|
||||
isRetry: boolean = false,
|
||||
): Promise<Chunk[]> {
|
||||
// Get the appropriate embeddings provider
|
||||
const { provider } = await this.getEmbeddingsProvider();
|
||||
if (!provider) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Lance doesn't have an embeddingsprovider column, instead it includes it in the table name
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
initializationVector: vector,
|
||||
|
|
@ -852,15 +868,22 @@ export default class DocsService {
|
|||
console.warn("Error retrieving chunks from LanceDB", e);
|
||||
}
|
||||
|
||||
// No docs are found for preindexed? try fetching once
|
||||
if (docs.length === 0 && isPreindexed) {
|
||||
if (isRetry) {
|
||||
return [];
|
||||
// If no docs are found and this isn't a retry, try fetching from cache
|
||||
if (docs.length === 0 && !isRetry) {
|
||||
try {
|
||||
// Try to fetch the document from the S3 cache
|
||||
const cacheHit = await this.tryFetchFromCache(
|
||||
startUrl,
|
||||
provider.embeddingId,
|
||||
);
|
||||
|
||||
if (cacheHit) {
|
||||
// If cache hit, retry the search once
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error trying to fetch from cache:", e);
|
||||
}
|
||||
await this.fetchAndAddPreIndexedDocEmbeddings(
|
||||
preIndexedDocs[startUrl]!["title"],
|
||||
);
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true);
|
||||
}
|
||||
|
||||
return docs.map(this.lanceDBRowToChunk);
|
||||
|
|
@ -912,10 +935,9 @@ export default class DocsService {
|
|||
return result.favicon;
|
||||
}
|
||||
|
||||
/*
|
||||
Sync with no embeddings provider change
|
||||
Ignores pre-indexed docs
|
||||
*/
|
||||
/**
|
||||
* Sync with no embeddings provider change
|
||||
*/
|
||||
private async syncDocs(
|
||||
oldConfig: ContinueConfig | undefined,
|
||||
newConfig: ContinueConfig,
|
||||
|
|
@ -933,11 +955,9 @@ export default class DocsService {
|
|||
const currentlyIndexedDocs = await this.listMetadata();
|
||||
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
|
||||
|
||||
// Anything found in sqlite but not in new config should be deleted if not preindexed
|
||||
// Anything found in sqlite but not in new config should be deleted
|
||||
const deletedDocs = currentlyIndexedDocs.filter(
|
||||
(doc) =>
|
||||
!preIndexedDocs[doc.startUrl] &&
|
||||
!newConfigStartUrls.includes(doc.startUrl),
|
||||
(doc) => !newConfigStartUrls.includes(doc.startUrl),
|
||||
);
|
||||
|
||||
// Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
|
||||
|
|
@ -1063,7 +1083,7 @@ export default class DocsService {
|
|||
|
||||
const conn = await lance.connect(getLanceDbPath());
|
||||
const tableNames = await conn.tableNames();
|
||||
const { provider } = await this.getEmbeddingsProvider(startUrl);
|
||||
const { provider } = await this.getEmbeddingsProvider();
|
||||
|
||||
if (!provider) {
|
||||
throw new Error(
|
||||
|
|
@ -1164,15 +1184,30 @@ export default class DocsService {
|
|||
);
|
||||
|
||||
if (!doesEquivalentDocExist) {
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
docs: [
|
||||
...(config.docs?.filter(
|
||||
(doc) => doc.startUrl !== siteIndexingConfig.startUrl,
|
||||
) ?? []),
|
||||
siteIndexingConfig,
|
||||
],
|
||||
}));
|
||||
editConfigFile(
|
||||
(config) => ({
|
||||
...config,
|
||||
docs: [
|
||||
...(config.docs?.filter(
|
||||
(doc) => doc.startUrl !== siteIndexingConfig.startUrl,
|
||||
) ?? []),
|
||||
siteIndexingConfig,
|
||||
],
|
||||
}),
|
||||
(config) => ({
|
||||
...config,
|
||||
docs: [
|
||||
...(config.docs?.filter(
|
||||
(doc) => (doc as any).startUrl !== siteIndexingConfig.startUrl,
|
||||
) ?? []),
|
||||
{
|
||||
name: siteIndexingConfig.title,
|
||||
faviconUrl: siteIndexingConfig.faviconUrl,
|
||||
startUrl: siteIndexingConfig.startUrl,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1216,10 +1251,19 @@ export default class DocsService {
|
|||
(doc) => doc.startUrl === startUrl,
|
||||
);
|
||||
if (doesDocExist) {
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [],
|
||||
}));
|
||||
editConfigFile(
|
||||
(config) => ({
|
||||
...config,
|
||||
docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [],
|
||||
}),
|
||||
(config) => ({
|
||||
...config,
|
||||
docs:
|
||||
config.docs?.filter(
|
||||
(doc) => "startUrl" in doc && doc.startUrl !== startUrl,
|
||||
) || [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import PCR from "puppeteer-chromium-resolver";
|
|||
|
||||
import { ContinueConfig, IDE } from "../../..";
|
||||
import {
|
||||
editConfigJson,
|
||||
editConfigFile,
|
||||
getChromiumPath,
|
||||
getContinueUtilsPath,
|
||||
} from "../../../util/paths";
|
||||
|
|
@ -26,13 +26,16 @@ export class ChromiumCrawler {
|
|||
) {}
|
||||
|
||||
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
experimental: {
|
||||
...config.experimental,
|
||||
useChromiumForDocsCrawling,
|
||||
},
|
||||
}));
|
||||
editConfigFile(
|
||||
(config) => ({
|
||||
...config,
|
||||
experimental: {
|
||||
...config.experimental,
|
||||
useChromiumForDocsCrawling,
|
||||
},
|
||||
}),
|
||||
(config) => config, // Not used in config.yaml
|
||||
);
|
||||
}
|
||||
|
||||
async *crawl(): AsyncGenerator<PageData> {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { type Database } from "sqlite";
|
||||
import { type Table } from "vectordb";
|
||||
|
||||
import { editConfigJson, migrate } from "../../util/paths.js";
|
||||
import { editConfigFile, migrate } from "../../util/paths.js";
|
||||
|
||||
import DocsService, { SqliteDocsRow } from "./DocsService.js";
|
||||
|
||||
|
|
@ -58,10 +58,22 @@ export async function runSqliteMigrations(db: Database) {
|
|||
const sqliteDocs = await db.all<
|
||||
Array<Pick<SqliteDocsRow, "title" | "startUrl">>
|
||||
>(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`);
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
docs: [...(config.docs || []), ...sqliteDocs],
|
||||
}));
|
||||
editConfigFile(
|
||||
(config) => ({
|
||||
...config,
|
||||
docs: [...(config.docs || []), ...sqliteDocs],
|
||||
}),
|
||||
(config) => ({
|
||||
...config,
|
||||
docs: [
|
||||
...(config.docs || []),
|
||||
...sqliteDocs.map((doc) => ({
|
||||
name: doc.title,
|
||||
startUrl: doc.startUrl,
|
||||
})),
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
resolve(undefined);
|
||||
|
|
|
|||
|
|
@ -1,52 +0,0 @@
|
|||
import request from "request";
|
||||
|
||||
import { Chunk } from "../../";
|
||||
|
||||
export function getS3Filename(
|
||||
embeddingsProviderId: string,
|
||||
title: string,
|
||||
): string {
|
||||
return `_TransformersJsEmbeddingsProvider::all-MiniLM-L6-v2/${title}`;
|
||||
}
|
||||
|
||||
export enum S3Buckets {
|
||||
continueIndexedDocs = "continue-indexed-docs",
|
||||
}
|
||||
|
||||
const AWS_REGION = "us-west-1";
|
||||
|
||||
export async function downloadFromS3(
|
||||
bucket: string,
|
||||
fileName: string,
|
||||
): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
let data = "";
|
||||
|
||||
const download = request({
|
||||
url: `https://${bucket}.s3.${AWS_REGION}.amazonaws.com/${fileName}`,
|
||||
});
|
||||
download.on("response", (response: any) => {
|
||||
if (response.statusCode !== 200) {
|
||||
reject(new Error("There was an error retreiving the pre-indexed doc"));
|
||||
}
|
||||
});
|
||||
|
||||
download.on("error", (err: any) => {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
download.on("data", (chunk: any) => {
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
download.on("end", () => {
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface SiteIndexingResults {
|
||||
chunks: (Chunk & { embedding: number[] })[];
|
||||
url: string;
|
||||
title: string;
|
||||
}
|
||||
|
|
@ -1,368 +0,0 @@
|
|||
import { SiteIndexingConfig } from "../../";
|
||||
|
||||
const preIndexedDocs: Record<
|
||||
SiteIndexingConfig["startUrl"],
|
||||
SiteIndexingConfig
|
||||
> = {
|
||||
"https://jinja.palletsprojects.com/en/3.1.x/": {
|
||||
title: "Jinja",
|
||||
startUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
|
||||
rootUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
|
||||
faviconUrl: "https://jinja.palletsprojects.com/favicon.ico",
|
||||
},
|
||||
"https://react.dev/reference/": {
|
||||
title: "React",
|
||||
startUrl: "https://react.dev/reference/",
|
||||
rootUrl: "https://react.dev/reference/",
|
||||
faviconUrl: "https://react.dev/favicon.ico",
|
||||
},
|
||||
"https://posthog.com/docs": {
|
||||
title: "PostHog",
|
||||
startUrl: "https://posthog.com/docs",
|
||||
rootUrl: "https://posthog.com/docs",
|
||||
faviconUrl: "https://posthog.com/favicon.ico",
|
||||
},
|
||||
"https://expressjs.com/en/5x/api.html": {
|
||||
title: "Express",
|
||||
startUrl: "https://expressjs.com/en/5x/api.html",
|
||||
rootUrl: "https://expressjs.com/en/5x/",
|
||||
faviconUrl: "https://expressjs.com/favicon.ico",
|
||||
},
|
||||
"https://platform.openai.com/docs/": {
|
||||
title: "OpenAI",
|
||||
startUrl: "https://platform.openai.com/docs/",
|
||||
rootUrl: "https://platform.openai.com/docs/",
|
||||
faviconUrl: "https://platform.openai.com/favicon.ico",
|
||||
},
|
||||
"https://www.prisma.io/docs": {
|
||||
title: "Prisma",
|
||||
startUrl: "https://www.prisma.io/docs",
|
||||
rootUrl: "https://www.prisma.io/docs",
|
||||
faviconUrl: "https://www.prisma.io/favicon.ico",
|
||||
},
|
||||
"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html": {
|
||||
title: "Boto3",
|
||||
startUrl:
|
||||
"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html",
|
||||
rootUrl: "https://boto3.amazonaws.com/v1/documentation/api/latest/",
|
||||
faviconUrl: "https://boto3.amazonaws.com/favicon.ico",
|
||||
},
|
||||
"https://pytorch.org/docs/stable/": {
|
||||
title: "Pytorch",
|
||||
startUrl: "https://pytorch.org/docs/stable/",
|
||||
rootUrl: "https://pytorch.org/docs/stable/",
|
||||
faviconUrl: "https://pytorch.org/favicon.ico",
|
||||
},
|
||||
"https://redis.io/docs/": {
|
||||
title: "Redis",
|
||||
startUrl: "https://redis.io/docs/",
|
||||
rootUrl: "https://redis.io/docs/",
|
||||
faviconUrl: "https://redis.io/favicon.ico",
|
||||
},
|
||||
"https://axios-http.com/docs/intro": {
|
||||
title: "Axios",
|
||||
startUrl: "https://axios-http.com/docs/intro",
|
||||
rootUrl: "https://axios-http.com/docs",
|
||||
faviconUrl: "https://axios-http.com/favicon.ico",
|
||||
},
|
||||
"https://redwoodjs.com/docs/introduction": {
|
||||
title: "Redwood JS",
|
||||
startUrl: "https://redwoodjs.com/docs/introduction",
|
||||
rootUrl: "https://redwoodjs.com/docs",
|
||||
faviconUrl: "https://redwoodjs.com/favicon.ico",
|
||||
},
|
||||
"https://graphql.org/learn/": {
|
||||
title: "GraphQL",
|
||||
startUrl: "https://graphql.org/learn/",
|
||||
rootUrl: "https://graphql.org/learn/",
|
||||
faviconUrl: "https://graphql.org/favicon.ico",
|
||||
},
|
||||
"https://www.typescriptlang.org/docs/": {
|
||||
title: "Typescript",
|
||||
startUrl: "https://www.typescriptlang.org/docs/",
|
||||
rootUrl: "https://www.typescriptlang.org/docs/",
|
||||
faviconUrl: "https://www.typescriptlang.org/favicon.ico",
|
||||
},
|
||||
"https://jestjs.io/docs/getting-started": {
|
||||
title: "Jest",
|
||||
startUrl: "https://jestjs.io/docs/getting-started",
|
||||
rootUrl: "https://jestjs.io/docs",
|
||||
faviconUrl: "https://jestjs.io/favicon.ico",
|
||||
},
|
||||
"https://tailwindcss.com/docs/installation": {
|
||||
title: "Tailwind CSS",
|
||||
startUrl: "https://tailwindcss.com/docs/installation",
|
||||
rootUrl: "https://tailwindcss.com/docs",
|
||||
faviconUrl: "https://tailwindcss.com/favicon.ico",
|
||||
},
|
||||
"https://vuejs.org/guide/introduction.html": {
|
||||
title: "Vue.js",
|
||||
startUrl: "https://vuejs.org/guide/introduction.html",
|
||||
rootUrl: "https://vuejs.org",
|
||||
faviconUrl: "https://vuejs.org/favicon.ico",
|
||||
},
|
||||
"https://svelte.dev/docs/introduction": {
|
||||
title: "Svelte",
|
||||
startUrl: "https://svelte.dev/docs/introduction",
|
||||
rootUrl: "https://svelte.dev/docs",
|
||||
faviconUrl: "https://svelte.dev/favicon.ico",
|
||||
},
|
||||
"https://docs.github.com/en/actions": {
|
||||
title: "GitHub Actions",
|
||||
startUrl: "https://docs.github.com/en/actions",
|
||||
rootUrl: "https://docs.github.com/en/actions",
|
||||
faviconUrl: "https://docs.github.com/favicon.ico",
|
||||
},
|
||||
"https://nodejs.org/docs/latest/api/": {
|
||||
title: "NodeJS",
|
||||
startUrl: "https://nodejs.org/docs/latest/api/",
|
||||
rootUrl: "https://nodejs.org/docs/latest/api/",
|
||||
faviconUrl: "https://nodejs.org/favicon.ico",
|
||||
},
|
||||
"https://socket.io/docs/v4/": {
|
||||
title: "Socket.io",
|
||||
startUrl: "https://socket.io/docs/v4/",
|
||||
rootUrl: "https://socket.io/docs/v4/",
|
||||
faviconUrl: "https://socket.io/favicon.ico",
|
||||
},
|
||||
"https://docs.gradle.org/current/userguide/userguide.html": {
|
||||
title: "Gradle",
|
||||
startUrl: "https://docs.gradle.org/current/userguide/userguide.html",
|
||||
rootUrl: "https://docs.gradle.org/current",
|
||||
faviconUrl: "https://docs.gradle.org/favicon.ico",
|
||||
},
|
||||
"https://redux-toolkit.js.org/introduction/getting-started": {
|
||||
title: "Redux Toolkit",
|
||||
startUrl: "https://redux-toolkit.js.org/introduction/getting-started",
|
||||
rootUrl: "https://redux-toolkit.js.org",
|
||||
faviconUrl: "https://redux-toolkit.js.org/favicon.ico",
|
||||
},
|
||||
"https://docs.trychroma.com/": {
|
||||
title: "Chroma",
|
||||
startUrl: "https://docs.trychroma.com/",
|
||||
rootUrl: "https://docs.trychroma.com/",
|
||||
faviconUrl: "https://docs.trychroma.com/favicon.ico",
|
||||
},
|
||||
"https://www.sqlite.org/docs.html": {
|
||||
title: "SQLite",
|
||||
startUrl: "https://www.sqlite.org/docs.html",
|
||||
rootUrl: "https://www.sqlite.org",
|
||||
faviconUrl: "https://www.sqlite.org/favicon.ico",
|
||||
},
|
||||
"https://redux.js.org/introduction/getting-started": {
|
||||
title: "Redux",
|
||||
startUrl: "https://redux.js.org/introduction/getting-started",
|
||||
rootUrl: "https://redux.js.org",
|
||||
faviconUrl: "https://redux.js.org/favicon.ico",
|
||||
},
|
||||
"https://prettier.io/docs/en/": {
|
||||
title: "Prettier",
|
||||
startUrl: "https://prettier.io/docs/en/",
|
||||
rootUrl: "https://prettier.io/docs/en/",
|
||||
faviconUrl: "https://prettier.io/favicon.ico",
|
||||
},
|
||||
"https://code.visualstudio.com/api": {
|
||||
title: "VS Code Extension API",
|
||||
startUrl: "https://code.visualstudio.com/api",
|
||||
rootUrl: "https://code.visualstudio.com/api",
|
||||
faviconUrl: "https://code.visualstudio.com/favicon.ico",
|
||||
},
|
||||
"https://docs.continue.dev/intro": {
|
||||
title: "Continue",
|
||||
startUrl: "https://docs.continue.dev/intro",
|
||||
rootUrl: "https://docs.continue.dev",
|
||||
faviconUrl: "https://docs.continue.dev/favicon.ico",
|
||||
},
|
||||
"https://api.jquery.com/": {
|
||||
title: "jQuery",
|
||||
startUrl: "https://api.jquery.com/",
|
||||
rootUrl: "https://api.jquery.com/",
|
||||
faviconUrl: "https://api.jquery.com/favicon.ico",
|
||||
},
|
||||
"https://docs.python.org/3/": {
|
||||
title: "Python",
|
||||
startUrl: "https://docs.python.org/3/",
|
||||
rootUrl: "https://docs.python.org/3/",
|
||||
faviconUrl: "https://docs.python.org/favicon.ico",
|
||||
},
|
||||
"https://doc.rust-lang.org/book/": {
|
||||
title: "Rust",
|
||||
startUrl: "https://doc.rust-lang.org/book/",
|
||||
rootUrl: "https://doc.rust-lang.org/book/",
|
||||
faviconUrl: "https://doc.rust-lang.org/favicon.ico",
|
||||
},
|
||||
"https://plugins.jetbrains.com/docs/intellij/welcome.html": {
|
||||
title: "IntelliJ Platform SDK",
|
||||
startUrl: "https://plugins.jetbrains.com/docs/intellij/welcome.html",
|
||||
rootUrl: "https://plugins.jetbrains.com/docs/intellij",
|
||||
faviconUrl: "https://plugins.jetbrains.com/favicon.ico",
|
||||
},
|
||||
"https://docs.docker.com/": {
|
||||
title: "Docker",
|
||||
startUrl: "https://docs.docker.com/",
|
||||
rootUrl: "https://docs.docker.com/",
|
||||
faviconUrl: "https://docs.docker.com/favicon.ico",
|
||||
},
|
||||
"https://docs.npmjs.com/": {
|
||||
title: "NPM",
|
||||
startUrl: "https://docs.npmjs.com/",
|
||||
rootUrl: "https://docs.npmjs.com/",
|
||||
faviconUrl: "https://docs.npmjs.com/favicon.ico",
|
||||
},
|
||||
"https://tiptap.dev/docs/editor/introduction": {
|
||||
title: "TipTap",
|
||||
startUrl: "https://tiptap.dev/docs/editor/introduction",
|
||||
rootUrl: "https://tiptap.dev/docs",
|
||||
faviconUrl: "https://tiptap.dev/favicon.ico",
|
||||
},
|
||||
"https://esbuild.github.io/": {
|
||||
title: "esbuild",
|
||||
startUrl: "https://esbuild.github.io/",
|
||||
rootUrl: "https://esbuild.github.io/",
|
||||
faviconUrl: "https://esbuild.github.io/favicon.ico",
|
||||
},
|
||||
"https://tree-sitter.github.io/tree-sitter/": {
|
||||
title: "Tree Sitter",
|
||||
startUrl: "https://tree-sitter.github.io/tree-sitter/",
|
||||
rootUrl: "https://tree-sitter.github.io/tree-sitter/",
|
||||
faviconUrl: "https://tree-sitter.github.io/favicon.ico",
|
||||
},
|
||||
"https://docs.netlify.com/": {
|
||||
title: "Netlify",
|
||||
startUrl: "https://docs.netlify.com/",
|
||||
rootUrl: "https://docs.netlify.com/",
|
||||
faviconUrl: "https://docs.netlify.com/favicon.ico",
|
||||
},
|
||||
"https://replicate.com/docs": {
|
||||
title: "Replicate",
|
||||
startUrl: "https://replicate.com/docs",
|
||||
rootUrl: "https://replicate.com/docs",
|
||||
faviconUrl: "https://replicate.com/favicon.ico",
|
||||
},
|
||||
"https://www.w3schools.com/html/default.asp": {
|
||||
title: "HTML",
|
||||
startUrl: "https://www.w3schools.com/html/default.asp",
|
||||
rootUrl: "https://www.w3schools.com/html",
|
||||
faviconUrl: "https://www.w3schools.com/favicon.ico",
|
||||
},
|
||||
"https://www.w3schools.com/css/default.asp": {
|
||||
title: "CSS",
|
||||
startUrl: "https://www.w3schools.com/css/default.asp",
|
||||
rootUrl: "https://www.w3schools.com/css",
|
||||
faviconUrl: "https://www.w3schools.com/favicon.ico",
|
||||
},
|
||||
"https://python.langchain.com/docs/get_started/introduction": {
|
||||
title: "Langchain",
|
||||
startUrl: "https://python.langchain.com/docs/get_started/introduction",
|
||||
rootUrl: "https://python.langchain.com/docs",
|
||||
faviconUrl: "https://python.langchain.com/favicon.ico",
|
||||
},
|
||||
"https://developer.woocommerce.com/docs/": {
|
||||
title: "WooCommerce",
|
||||
startUrl: "https://developer.woocommerce.com/docs/",
|
||||
rootUrl: "https://developer.woocommerce.com/docs/",
|
||||
faviconUrl: "https://developer.woocommerce.com/favicon.ico",
|
||||
},
|
||||
"https://developer.wordpress.org/reference/": {
|
||||
title: "WordPress",
|
||||
startUrl: "https://developer.wordpress.org/reference/",
|
||||
rootUrl: "https://developer.wordpress.org/reference/",
|
||||
faviconUrl: "https://developer.wordpress.org/favicon.ico",
|
||||
},
|
||||
"https://doc.qt.io/qtforpython-6/quickstart.html": {
|
||||
title: "PySide6",
|
||||
startUrl: "https://doc.qt.io/qtforpython-6/quickstart.html",
|
||||
rootUrl: "https://doc.qt.io/qtforpython-6/api.html",
|
||||
faviconUrl: "https://doc.qt.io/favicon.ico",
|
||||
},
|
||||
"https://getbootstrap.com/docs/5.3/getting-started/introduction/": {
|
||||
title: "Bootstrap",
|
||||
startUrl: "https://getbootstrap.com/docs/5.3/getting-started/introduction/",
|
||||
rootUrl: "https://getbootstrap.com/docs/5.3/",
|
||||
faviconUrl: "https://getbootstrap.com/favicon.ico",
|
||||
},
|
||||
"https://alpinejs.dev/start-here": {
|
||||
title: "Alpine.js",
|
||||
startUrl: "https://alpinejs.dev/start-here",
|
||||
rootUrl: "https://alpinejs.dev/",
|
||||
faviconUrl: "https://alpinejs.dev/favicon.ico",
|
||||
},
|
||||
"https://learn.microsoft.com/en-us/dotnet/csharp/": {
|
||||
title: "C# Language Reference",
|
||||
startUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/",
|
||||
rootUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/",
|
||||
faviconUrl: "https://learn.microsoft.com/favicon.ico",
|
||||
},
|
||||
"https://docs.godotengine.org/en/latest/": {
|
||||
title: "Godot",
|
||||
startUrl: "https://docs.godotengine.org/en/latest/",
|
||||
rootUrl: "https://docs.godotengine.org/en/latest/",
|
||||
faviconUrl: "https://godotengine.org/favicon.ico",
|
||||
},
|
||||
"https://docs.amplify.aws/react/start/": {
|
||||
title: "AWS Amplify (Gen 2)",
|
||||
startUrl: "https://docs.amplify.aws/react/start/",
|
||||
rootUrl: "https://docs.amplify.aws/react/",
|
||||
faviconUrl: "https://docs.amplify.aws/favicon.ico",
|
||||
},
|
||||
"https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/": {
|
||||
title: "AWS SDK for JavaScript v3",
|
||||
startUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/",
|
||||
rootUrl: "https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/",
|
||||
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
|
||||
},
|
||||
"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html": {
|
||||
title: "AWS CDK v2",
|
||||
startUrl:
|
||||
"https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html",
|
||||
rootUrl: "https://docs.aws.amazon.com/cdk/api/v2/docs/",
|
||||
faviconUrl: "https://docs.aws.amazon.com/cdk/api/v2/img/favicon-32x32.png",
|
||||
},
|
||||
"https://awscli.amazonaws.com/v2/documentation/api/latest/index.html": {
|
||||
title: "AWS CLI commands",
|
||||
startUrl:
|
||||
"https://awscli.amazonaws.com/v2/documentation/api/latest/index.html",
|
||||
rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/",
|
||||
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
|
||||
},
|
||||
"https://llama-stack.readthedocs.io/": {
|
||||
title: "Llama Stack",
|
||||
startUrl: "https://llama-stack.readthedocs.io/",
|
||||
rootUrl: "https://llama-stack.readthedocs.io/",
|
||||
},
|
||||
"https://go.dev/doc": {
|
||||
title: "Go",
|
||||
startUrl: "https://go.dev/doc",
|
||||
rootUrl: "https://go.dev",
|
||||
faviconUrl: "https://go.dev/favicon.ico",
|
||||
},
|
||||
"https://api.flutter.dev": {
|
||||
title: "Flutter",
|
||||
startUrl: "https://api.flutter.dev",
|
||||
rootUrl: "https://api.flutter.dev",
|
||||
faviconUrl: "https://api.flutter.dev/flutter/static-assets/favicon.png",
|
||||
},
|
||||
"https://api.dart.dev": {
|
||||
title: "Dart",
|
||||
startUrl: "https://api.dart.dev",
|
||||
rootUrl: "https://api.dart.dev",
|
||||
faviconUrl: "https://api.dart.dev/static-assets/favicon.png",
|
||||
},
|
||||
"https://docs.asksage.ai/": {
|
||||
title: "Ask Sage",
|
||||
startUrl: "https://docs.asksage.ai/",
|
||||
rootUrl: "https://docs.asksage.ai/",
|
||||
},
|
||||
"https://angular.dev/": {
|
||||
title: "Angular",
|
||||
startUrl: "https://angular.dev/",
|
||||
rootUrl: "https://angular.dev/",
|
||||
},
|
||||
"https://docs.djangoproject.com/": {
|
||||
title: "Django",
|
||||
startUrl: "https://docs.djangoproject.com/",
|
||||
rootUrl: "https://docs.djangoproject.com/",
|
||||
}
|
||||
};
|
||||
|
||||
export default preIndexedDocs;
|
||||
|
|
@ -158,18 +158,21 @@ async function getAddRemoveForTag(
|
|||
const updateLastUpdated: PathAndCacheKey[] = [];
|
||||
|
||||
// First, group items by path and find latest timestamp for each
|
||||
const pathGroups = new Map<string, {
|
||||
latest: { lastUpdated: number, cacheKey: string },
|
||||
allVersions: Array<{ cacheKey: string }>
|
||||
}>();
|
||||
const pathGroups = new Map<
|
||||
string,
|
||||
{
|
||||
latest: { lastUpdated: number; cacheKey: string };
|
||||
allVersions: Array<{ cacheKey: string }>;
|
||||
}
|
||||
>();
|
||||
|
||||
for (const item of saved) {
|
||||
const { lastUpdated, path, cacheKey } = item;
|
||||
|
||||
|
||||
if (!pathGroups.has(path)) {
|
||||
pathGroups.set(path, {
|
||||
latest: { lastUpdated, cacheKey },
|
||||
allVersions: [{ cacheKey }]
|
||||
allVersions: [{ cacheKey }],
|
||||
});
|
||||
} else {
|
||||
const group = pathGroups.get(path)!;
|
||||
|
|
@ -530,6 +533,6 @@ export function truncateToLastNBytes(input: string, maxBytes: number): string {
|
|||
return input.substring(startIndex, input.length);
|
||||
}
|
||||
|
||||
export function truncateSqliteLikePattern(input: string) {
|
||||
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH);
|
||||
export function truncateSqliteLikePattern(input: string, safety: number = 100) {
|
||||
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ describe("walkDir functions", () => {
|
|||
);
|
||||
});
|
||||
|
||||
it("should handle onlyDirs option", async () => {
|
||||
it("should handle include option", async () => {
|
||||
addToTestDir([
|
||||
"src/",
|
||||
["src/file1.ts", "content1"],
|
||||
|
|
@ -109,7 +109,7 @@ describe("walkDir functions", () => {
|
|||
(await testIde.getWorkspaceDirs())[0],
|
||||
testIde,
|
||||
{
|
||||
onlyDirs: true,
|
||||
include: "dirs",
|
||||
},
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -10,10 +10,11 @@ import {
|
|||
} from "./ignore";
|
||||
|
||||
export interface WalkerOptions {
|
||||
onlyDirs?: boolean;
|
||||
include?: "dirs" | "files" | "both";
|
||||
returnRelativeUrisPaths?: boolean;
|
||||
source?: string;
|
||||
overrideDefaultIgnores?: Ignore;
|
||||
recursive?: boolean;
|
||||
}
|
||||
|
||||
type Entry = [string, FileType];
|
||||
|
|
@ -195,7 +196,7 @@ class DFSWalker {
|
|||
if (this.entryIsDirectory(entry)) {
|
||||
relPath = `${relPath}/`;
|
||||
} else {
|
||||
if (this.options.onlyDirs) {
|
||||
if (this.options.include === "dirs") {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
|
@ -221,19 +222,22 @@ class DFSWalker {
|
|||
}
|
||||
|
||||
if (this.entryIsDirectory(entry)) {
|
||||
stack.push({
|
||||
walkableEntry,
|
||||
ignoreContexts,
|
||||
});
|
||||
if (this.options.onlyDirs) {
|
||||
// when onlyDirs is enabled the walker will only return directory names
|
||||
if (this.options.recursive) {
|
||||
stack.push({
|
||||
walkableEntry,
|
||||
ignoreContexts,
|
||||
});
|
||||
}
|
||||
if (this.options.include !== "files") {
|
||||
// if yielding dirs or both, walker includes relative paths
|
||||
const trailingSlash = this.options.include === "dirs" ? "" : "/";
|
||||
if (this.options.returnRelativeUrisPaths) {
|
||||
yield walkableEntry.relativeUriPath;
|
||||
yield walkableEntry.relativeUriPath + trailingSlash;
|
||||
} else {
|
||||
yield walkableEntry.uri;
|
||||
yield walkableEntry.uri + trailingSlash;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} else if (this.options.include !== "dirs") {
|
||||
if (this.options.returnRelativeUrisPaths) {
|
||||
yield walkableEntry.relativeUriPath;
|
||||
} else {
|
||||
|
|
@ -257,8 +261,9 @@ class DFSWalker {
|
|||
}
|
||||
|
||||
const defaultOptions: WalkerOptions = {
|
||||
onlyDirs: false,
|
||||
include: "files",
|
||||
returnRelativeUrisPaths: false,
|
||||
recursive: true,
|
||||
};
|
||||
|
||||
export async function* walkDirAsync(
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
const DEFAULT_MAX_TOKENS = 4096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 8096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 8192;
|
||||
const DEFAULT_TEMPERATURE = 0.5;
|
||||
|
||||
const DEFAULT_ARGS = {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// @ts-nocheck
|
||||
// Generated by continue
|
||||
import { ChatMessage, MessagePart } from "../index.js";
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
|
||||
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
UserChatMessage,
|
||||
} from "../index.js";
|
||||
|
||||
import { Rule } from "@continuedev/config-yaml";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
AsyncEncoder,
|
||||
|
|
@ -11,6 +17,8 @@ import {
|
|||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
import { isRuleActive } from "./rules/isRuleActive.js";
|
||||
import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
|
|
@ -27,9 +35,9 @@ class LlamaEncoding implements Encoding {
|
|||
}
|
||||
|
||||
class NonWorkerAsyncEncoder implements AsyncEncoder {
|
||||
constructor(private readonly encoding: Encoding) { }
|
||||
constructor(private readonly encoding: Encoding) {}
|
||||
|
||||
async close(): Promise<void> { }
|
||||
async close(): Promise<void> {}
|
||||
|
||||
async encode(text: string): Promise<number[]> {
|
||||
return this.encoding.encode(text);
|
||||
|
|
@ -251,16 +259,35 @@ function pruneChatHistory(
|
|||
}, 0);
|
||||
|
||||
// 0. Prune any messages that take up more than 1/3 of the context length
|
||||
const longestMessages = [...chatHistory];
|
||||
longestMessages.sort((a, b) => b.content.length - a.content.length);
|
||||
const zippedMessagesAndTokens: [ChatMessage, number][] = [];
|
||||
|
||||
const longerThanOneThird = longestMessages.filter(
|
||||
(message: ChatMessage) =>
|
||||
countTokens(message.content, modelName) > contextLength / 3,
|
||||
// Zipped ChatMessage with its token counts
|
||||
chatHistory.forEach((message) => {
|
||||
const zippedItem: [ChatMessage, number] = [
|
||||
message,
|
||||
countTokens(message.content, modelName),
|
||||
];
|
||||
zippedMessagesAndTokens.push(zippedItem);
|
||||
});
|
||||
|
||||
const zippedLongerThanOneThird = zippedMessagesAndTokens.filter(
|
||||
([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3,
|
||||
);
|
||||
const distanceFromThird = longerThanOneThird.map(
|
||||
(message: ChatMessage) =>
|
||||
countTokens(message.content, modelName) - contextLength / 3,
|
||||
|
||||
zippedLongerThanOneThird.sort(
|
||||
(
|
||||
[_messageA, tokensA]: [ChatMessage, number],
|
||||
[_messageB, tokensB]: [ChatMessage, number],
|
||||
) => {
|
||||
return tokensB - tokensA;
|
||||
},
|
||||
);
|
||||
|
||||
const longerThanOneThird = zippedLongerThanOneThird.map(
|
||||
([message, _token]: [ChatMessage, number]) => message,
|
||||
);
|
||||
const distanceFromThird = zippedLongerThanOneThird.map(
|
||||
([_message, token]: [ChatMessage, number]) => token - contextLength / 3,
|
||||
);
|
||||
|
||||
for (let i = 0; i < longerThanOneThird.length; i++) {
|
||||
|
|
@ -280,7 +307,7 @@ function pruneChatHistory(
|
|||
// 1. Replace beyond last 5 messages with summary
|
||||
let i = 0;
|
||||
while (totalTokens > contextLength && i < chatHistory.length - 5) {
|
||||
const message = chatHistory[0];
|
||||
const message = chatHistory[i];
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
totalTokens += countTokens(summarize(message), modelName);
|
||||
message.content = summarize(message);
|
||||
|
|
@ -288,11 +315,7 @@ function pruneChatHistory(
|
|||
}
|
||||
|
||||
// 2. Remove entire messages until the last 5
|
||||
while (
|
||||
chatHistory.length > 5 &&
|
||||
totalTokens > contextLength &&
|
||||
chatHistory.length > 0
|
||||
) {
|
||||
while (chatHistory.length > 5 && totalTokens > contextLength) {
|
||||
const message = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
}
|
||||
|
|
@ -313,8 +336,21 @@ function pruneChatHistory(
|
|||
|
||||
// 4. Remove entire messages in the last 5, except last 1
|
||||
while (totalTokens > contextLength && chatHistory.length > 1) {
|
||||
const message = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
// If tool call/response detected prune both (can't have response with no call)
|
||||
// TODO prune lines from tool response before pruning both messages
|
||||
if (
|
||||
chatHistory.length > 2 &&
|
||||
messageHasToolCalls(chatHistory[0]) &&
|
||||
chatHistory[1].role === "tool"
|
||||
) {
|
||||
const firstMessage = chatHistory.shift()!;
|
||||
const secondMessage = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(firstMessage.content, modelName);
|
||||
totalTokens -= countTokens(secondMessage.content, modelName);
|
||||
} else {
|
||||
const message = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Truncate last message
|
||||
|
|
@ -328,7 +364,6 @@ function pruneChatHistory(
|
|||
);
|
||||
totalTokens = contextLength;
|
||||
}
|
||||
|
||||
return chatHistory;
|
||||
}
|
||||
|
||||
|
|
@ -372,20 +407,131 @@ function chatMessageIsEmpty(message: ChatMessage): boolean {
|
|||
}
|
||||
}
|
||||
|
||||
function compileChatMessages(
|
||||
modelName: string,
|
||||
msgs: ChatMessage[] | undefined,
|
||||
contextLength: number,
|
||||
maxTokens: number,
|
||||
supportsImages: boolean,
|
||||
prompt: string | undefined = undefined,
|
||||
functions: any[] | undefined = undefined,
|
||||
systemMessage: string | undefined = undefined,
|
||||
): ChatMessage[] {
|
||||
function addSystemMessage({
|
||||
messages,
|
||||
systemMessage,
|
||||
originalMessages,
|
||||
}: {
|
||||
messages: ChatMessage[];
|
||||
systemMessage: string | undefined;
|
||||
originalMessages: ChatMessage[] | undefined;
|
||||
}): ChatMessage[] {
|
||||
if (
|
||||
!(systemMessage && systemMessage.trim() !== "") &&
|
||||
originalMessages?.[0]?.role !== "system"
|
||||
) {
|
||||
return messages;
|
||||
}
|
||||
|
||||
let content = "";
|
||||
if (originalMessages?.[0]?.role === "system") {
|
||||
content = renderChatMessage(originalMessages[0]);
|
||||
}
|
||||
if (systemMessage && systemMessage.trim() !== "") {
|
||||
const shouldAddNewLines = content !== "";
|
||||
if (shouldAddNewLines) {
|
||||
content += "\n\n";
|
||||
}
|
||||
content += systemMessage;
|
||||
}
|
||||
|
||||
const systemChatMsg: ChatMessage = {
|
||||
role: "system",
|
||||
content,
|
||||
};
|
||||
// Insert as second to last
|
||||
messages.splice(-1, 0, systemChatMsg);
|
||||
return messages;
|
||||
}
|
||||
|
||||
function getMessageStringContent(message?: UserChatMessage): string {
|
||||
if (!message) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message.content;
|
||||
}
|
||||
|
||||
// Handle MessagePart array
|
||||
return message.content
|
||||
.map((part) => {
|
||||
if (part.type === "text") {
|
||||
return part.text;
|
||||
}
|
||||
|
||||
return "";
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
const getSystemMessage = ({
|
||||
userMessage,
|
||||
rules,
|
||||
currentModel,
|
||||
}: {
|
||||
userMessage?: UserChatMessage;
|
||||
rules: Rule[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const messageStringContent = getMessageStringContent(userMessage);
|
||||
const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent);
|
||||
|
||||
return rules
|
||||
.filter((rule) => {
|
||||
return isRuleActive({
|
||||
rule,
|
||||
activePaths: filePathsFromMessage,
|
||||
currentModel,
|
||||
});
|
||||
})
|
||||
.map((rule) => {
|
||||
if (typeof rule === "string") {
|
||||
return rule;
|
||||
}
|
||||
return rule.rule;
|
||||
})
|
||||
.join("\n");
|
||||
};
|
||||
|
||||
function getLastUserMessage(
|
||||
messages: ChatMessage[],
|
||||
): UserChatMessage | undefined {
|
||||
// Iterate backwards through messages to find the last user message
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].role === "user") {
|
||||
return messages[i] as UserChatMessage;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function compileChatMessages({
|
||||
modelName,
|
||||
msgs,
|
||||
contextLength,
|
||||
maxTokens,
|
||||
supportsImages,
|
||||
prompt,
|
||||
functions,
|
||||
systemMessage,
|
||||
rules,
|
||||
}: {
|
||||
modelName: string;
|
||||
msgs: ChatMessage[] | undefined;
|
||||
contextLength: number;
|
||||
maxTokens: number;
|
||||
supportsImages: boolean;
|
||||
prompt: string | undefined;
|
||||
functions: any[] | undefined;
|
||||
systemMessage: string | undefined;
|
||||
rules: Rule[];
|
||||
}): ChatMessage[] {
|
||||
let msgsCopy = msgs
|
||||
? msgs
|
||||
.map((msg) => ({ ...msg }))
|
||||
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
|
||||
.map((msg) => ({ ...msg }))
|
||||
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
|
||||
: [];
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
|
@ -398,29 +544,19 @@ function compileChatMessages(
|
|||
msgsCopy.push(promptMsg);
|
||||
}
|
||||
|
||||
if (
|
||||
(systemMessage && systemMessage.trim() !== "") ||
|
||||
msgs?.[0]?.role === "system"
|
||||
) {
|
||||
let content = "";
|
||||
if (msgs?.[0]?.role === "system") {
|
||||
content = renderChatMessage(msgs?.[0]);
|
||||
}
|
||||
if (systemMessage && systemMessage.trim() !== "") {
|
||||
const shouldAddNewLines = content !== "";
|
||||
if (shouldAddNewLines) {
|
||||
content += "\n\n";
|
||||
}
|
||||
content += systemMessage;
|
||||
}
|
||||
const systemChatMsg: ChatMessage = {
|
||||
role: "system",
|
||||
content,
|
||||
};
|
||||
// Insert as second to last
|
||||
// Later moved to top, but want second-priority to last user message
|
||||
msgsCopy.splice(-1, 0, systemChatMsg);
|
||||
}
|
||||
const lastUserMessage = getLastUserMessage(msgsCopy);
|
||||
|
||||
msgsCopy = addSystemMessage({
|
||||
messages: msgsCopy,
|
||||
systemMessage:
|
||||
systemMessage ??
|
||||
getSystemMessage({
|
||||
userMessage: lastUserMessage,
|
||||
rules,
|
||||
currentModel: modelName,
|
||||
}),
|
||||
originalMessages: msgs,
|
||||
});
|
||||
|
||||
let functionTokens = 0;
|
||||
if (functions) {
|
||||
|
|
@ -470,6 +606,5 @@ export {
|
|||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
pruneStringFromBottom,
|
||||
pruneStringFromTop
|
||||
pruneStringFromTop,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ChatMessage, LLMOptions } from "..";
|
||||
|
||||
import { BaseLLM } from ".";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
class DummyLLM extends BaseLLM {
|
||||
static providerName = "openai";
|
||||
|
|
@ -30,7 +31,7 @@ describe("BaseLLM", () => {
|
|||
const templatMessagesFunction = (messages: ChatMessage[]) => {
|
||||
return messages[0]?.content.toString() ?? "";
|
||||
};
|
||||
const writeLogFunction = async () => {};
|
||||
const llmLogger = new LLMLogger();
|
||||
const options: LLMOptions = {
|
||||
model: "gpt-3.5-turbo",
|
||||
uniqueId: "testId",
|
||||
|
|
@ -43,7 +44,7 @@ describe("BaseLLM", () => {
|
|||
requestOptions: {},
|
||||
promptTemplates: {},
|
||||
templateMessages: templatMessagesFunction,
|
||||
writeLog: writeLogFunction,
|
||||
logger: llmLogger,
|
||||
llmRequestHook: () => {},
|
||||
apiKey: "testApiKey",
|
||||
aiGatewaySlug: "testSlug",
|
||||
|
|
@ -67,7 +68,7 @@ describe("BaseLLM", () => {
|
|||
expect(instance.requestOptions).toEqual({});
|
||||
expect(instance.promptTemplates).toEqual({});
|
||||
expect(instance.templateMessages).toEqual(templatMessagesFunction);
|
||||
expect(instance.writeLog).toBe(writeLogFunction);
|
||||
expect(instance.logger).toBe(llmLogger);
|
||||
expect(instance.apiKey).toBe("testApiKey");
|
||||
expect(instance.aiGatewaySlug).toBe("testSlug");
|
||||
expect(instance.apiBase).toBe("https://api.example.com/");
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ModelRole } from "@continuedev/config-yaml";
|
||||
import { ModelRole, Rule } from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import { findLlmInfo } from "@continuedev/llm-info";
|
||||
import {
|
||||
|
|
@ -16,6 +16,8 @@ import {
|
|||
Chunk,
|
||||
CompletionOptions,
|
||||
ILLM,
|
||||
ILLMInteractionLog,
|
||||
ILLMLogger,
|
||||
LLMFullCompletionOptions,
|
||||
LLMOptions,
|
||||
ModelCapability,
|
||||
|
|
@ -72,6 +74,8 @@ export function isModelInstaller(provider: any): provider is ModelInstaller {
|
|||
return provider && typeof provider.installModel === "function";
|
||||
}
|
||||
|
||||
type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
|
||||
|
||||
export abstract class BaseLLM implements ILLM {
|
||||
static providerName: string;
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
|
||||
|
|
@ -129,7 +133,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
template?: TemplateType;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
apiKey?: string;
|
||||
|
||||
|
|
@ -143,6 +147,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
cacheBehavior?: CacheBehavior;
|
||||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
rules?: Rule[];
|
||||
|
||||
deployment?: string;
|
||||
apiVersion?: string;
|
||||
|
|
@ -177,7 +182,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
this.model = options.model;
|
||||
// Use @continuedev/llm-info package to autodetect certain parameters
|
||||
const llmInfo = findLlmInfo(this.model);
|
||||
const modelSearchString =
|
||||
this.providerName === "continue-proxy"
|
||||
? this.model?.split("/").pop() || this.model
|
||||
: this.model;
|
||||
const llmInfo = findLlmInfo(modelSearchString);
|
||||
|
||||
const templateType =
|
||||
options.template ?? autodetectTemplateType(options.model);
|
||||
|
|
@ -195,11 +204,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
options.completionOptions?.maxTokens ??
|
||||
(llmInfo?.maxCompletionTokens
|
||||
? Math.min(
|
||||
llmInfo.maxCompletionTokens,
|
||||
// Even if the model has a large maxTokens, we don't want to use that every time,
|
||||
// because it takes away from the context length
|
||||
this.contextLength / 4,
|
||||
)
|
||||
llmInfo.maxCompletionTokens,
|
||||
// Even if the model has a large maxTokens, we don't want to use that every time,
|
||||
// because it takes away from the context length
|
||||
this.contextLength / 4,
|
||||
)
|
||||
: DEFAULT_MAX_TOKENS),
|
||||
};
|
||||
this.requestOptions = options.requestOptions;
|
||||
|
|
@ -215,7 +224,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
options.template,
|
||||
) ??
|
||||
undefined;
|
||||
this.writeLog = options.writeLog;
|
||||
this.logger = options.logger;
|
||||
this.llmRequestHook = options.llmRequestHook;
|
||||
this.apiKey = options.apiKey;
|
||||
|
||||
|
|
@ -238,6 +247,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.accountId = options.accountId;
|
||||
this.capabilities = options.capabilities;
|
||||
this.roles = options.roles;
|
||||
this.rules = options.rules;
|
||||
|
||||
this.deployment = options.deployment;
|
||||
this.apiVersion = options.apiVersion;
|
||||
|
|
@ -282,21 +292,17 @@ export abstract class BaseLLM implements ILLM {
|
|||
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
|
||||
}
|
||||
|
||||
return compileChatMessages(
|
||||
options.model,
|
||||
messages,
|
||||
return compileChatMessages({
|
||||
modelName: options.model,
|
||||
msgs: messages,
|
||||
contextLength,
|
||||
options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
this.supportsImages(),
|
||||
undefined,
|
||||
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
prompt: undefined,
|
||||
functions,
|
||||
this.systemMessage,
|
||||
);
|
||||
}
|
||||
|
||||
private _getSystemMessage(): string | undefined {
|
||||
// TODO: Merge with config system message
|
||||
return this.systemMessage;
|
||||
systemMessage: this.systemMessage,
|
||||
rules: this.rules ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
private _templatePromptLikeMessages(prompt: string): string {
|
||||
|
|
@ -306,7 +312,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
|
||||
|
||||
const systemMessage = this._getSystemMessage();
|
||||
const systemMessage = this.systemMessage;
|
||||
if (systemMessage) {
|
||||
msgs.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
|
@ -343,13 +349,17 @@ export abstract class BaseLLM implements ILLM {
|
|||
);
|
||||
}
|
||||
|
||||
private _logTokensGenerated(
|
||||
private _logEnd(
|
||||
model: string,
|
||||
prompt: string,
|
||||
completion: string,
|
||||
) {
|
||||
thinking: string | undefined,
|
||||
interaction: ILLMInteractionLog | undefined,
|
||||
error?: any,
|
||||
): InteractionStatus {
|
||||
let promptTokens = this.countTokens(prompt);
|
||||
let generatedTokens = this.countTokens(completion);
|
||||
let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
|
||||
|
||||
void Telemetry.capture(
|
||||
"tokens_generated",
|
||||
|
|
@ -378,6 +388,37 @@ export abstract class BaseLLM implements ILLM {
|
|||
generatedTokens: generatedTokens,
|
||||
},
|
||||
});
|
||||
|
||||
if (error !== undefined) {
|
||||
if (error === "cancel" || error.name === "AbortError") {
|
||||
interaction?.logItem({
|
||||
kind: "cancel",
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
});
|
||||
return "cancelled";
|
||||
} else {
|
||||
console.log(error);
|
||||
interaction?.logItem({
|
||||
kind: "error",
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
});
|
||||
return "error";
|
||||
}
|
||||
} else {
|
||||
interaction?.logItem({
|
||||
kind: "success",
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
});
|
||||
return "success";
|
||||
}
|
||||
}
|
||||
|
||||
fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
|
|
@ -458,11 +499,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
//if e instance of LLMError, rethrow
|
||||
if (e instanceof LLMError) {
|
||||
throw e;
|
||||
}
|
||||
throw new Error(e.message);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
return withExponentialBackoff<Response>(
|
||||
|
|
@ -537,52 +574,89 @@ export abstract class BaseLLM implements ILLM {
|
|||
): AsyncGenerator<string> {
|
||||
const { completionOptions, logEnabled } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
? this.logger?.createInteractionLog()
|
||||
: undefined;
|
||||
let status: InteractionStatus = "in_progress";
|
||||
|
||||
const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
|
||||
if (logEnabled) {
|
||||
if (this.writeLog) {
|
||||
await this.writeLog(
|
||||
this._compilePromptForLog(fimLog, completionOptions),
|
||||
);
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "startFim",
|
||||
prefix,
|
||||
suffix,
|
||||
options: completionOptions,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, fimLog);
|
||||
}
|
||||
}
|
||||
|
||||
let completion = "";
|
||||
|
||||
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
|
||||
const stream = this.openaiAdapter.fimStream(
|
||||
toFimBody(prefix, suffix, completionOptions),
|
||||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
const content = renderChatMessage(result);
|
||||
completion += content;
|
||||
yield content;
|
||||
try {
|
||||
if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) {
|
||||
const stream = this.openaiAdapter.fimStream(
|
||||
toFimBody(prefix, suffix, completionOptions),
|
||||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
const content = renderChatMessage(result);
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: content,
|
||||
});
|
||||
completion += content;
|
||||
yield content;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for await (const chunk of this._streamFim(
|
||||
prefix,
|
||||
suffix,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk,
|
||||
});
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for await (const chunk of this._streamFim(
|
||||
prefix,
|
||||
suffix,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
fimLog,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
fimLog,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status === "in_progress") {
|
||||
this._logEnd(
|
||||
completionOptions.model,
|
||||
fimLog,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this._logTokensGenerated(completionOptions.model, fimLog, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
}
|
||||
|
||||
return {
|
||||
prompt: fimLog,
|
||||
completion,
|
||||
|
|
@ -597,6 +671,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
) {
|
||||
const { completionOptions, logEnabled, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
? this.logger?.createInteractionLog()
|
||||
: undefined;
|
||||
let status: InteractionStatus = "in_progress";
|
||||
|
||||
let prompt = pruneRawPromptFromTop(
|
||||
completionOptions.model,
|
||||
|
|
@ -610,11 +688,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
|
||||
if (logEnabled) {
|
||||
if (this.writeLog) {
|
||||
await this.writeLog(
|
||||
this._compilePromptForLog(prompt, completionOptions),
|
||||
);
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "startComplete",
|
||||
prompt,
|
||||
options: completionOptions,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
}
|
||||
|
|
@ -642,6 +720,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
)) {
|
||||
const content = chunk.choices[0]?.text ?? "";
|
||||
completion += content;
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: content,
|
||||
});
|
||||
yield content;
|
||||
}
|
||||
}
|
||||
|
|
@ -652,14 +734,40 @@ export abstract class BaseLLM implements ILLM {
|
|||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk,
|
||||
});
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
} finally {
|
||||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
if (status === "in_progress") {
|
||||
this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -678,6 +786,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
) {
|
||||
const { completionOptions, logEnabled, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
? this.logger?.createInteractionLog()
|
||||
: undefined;
|
||||
let status: InteractionStatus = "in_progress";
|
||||
|
||||
let prompt = pruneRawPromptFromTop(
|
||||
completionOptions.model,
|
||||
|
|
@ -691,34 +803,65 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
|
||||
if (logEnabled) {
|
||||
if (this.writeLog) {
|
||||
await this.writeLog(
|
||||
this._compilePromptForLog(prompt, completionOptions),
|
||||
);
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "startComplete",
|
||||
prompt: prompt,
|
||||
options: completionOptions,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
}
|
||||
}
|
||||
|
||||
let completion: string;
|
||||
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
|
||||
const result = await this.openaiAdapter.completionNonStream(
|
||||
{
|
||||
...toCompleteBody(prompt, completionOptions),
|
||||
stream: false,
|
||||
},
|
||||
signal,
|
||||
let completion: string = "";
|
||||
|
||||
try {
|
||||
if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) {
|
||||
const result = await this.openaiAdapter.completionNonStream(
|
||||
{
|
||||
...toCompleteBody(prompt, completionOptions),
|
||||
stream: false,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
completion = result.choices[0].text;
|
||||
} else {
|
||||
completion = await this._complete(prompt, signal, completionOptions);
|
||||
}
|
||||
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: completion,
|
||||
});
|
||||
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
);
|
||||
completion = result.choices[0].text;
|
||||
} else {
|
||||
completion = await this._complete(prompt, signal, completionOptions);
|
||||
}
|
||||
|
||||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status === "in_progress") {
|
||||
this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return completion;
|
||||
|
|
@ -763,6 +906,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
): AsyncGenerator<ChatMessage, PromptLog> {
|
||||
let { completionOptions, logEnabled } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
? this.logger?.createInteractionLog()
|
||||
: undefined;
|
||||
let status: InteractionStatus = "in_progress";
|
||||
|
||||
completionOptions = this._modifyCompletionOptions(completionOptions);
|
||||
|
||||
|
|
@ -772,11 +919,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
? this.templateMessages(messages)
|
||||
: this._formatChatMessages(messages);
|
||||
if (logEnabled) {
|
||||
if (this.writeLog) {
|
||||
await this.writeLog(
|
||||
this._compilePromptForLog(prompt, completionOptions),
|
||||
);
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "startChat",
|
||||
messages,
|
||||
options: completionOptions,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
}
|
||||
|
|
@ -784,7 +931,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
let citations: null | string[] = null;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -794,6 +940,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: chunk,
|
||||
});
|
||||
yield { role: "assistant", content: chunk };
|
||||
}
|
||||
} else {
|
||||
|
|
@ -823,15 +973,12 @@ export abstract class BaseLLM implements ILLM {
|
|||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
completion += result.content;
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: result,
|
||||
});
|
||||
yield result;
|
||||
}
|
||||
if (
|
||||
!citations &&
|
||||
(chunk as any).citations &&
|
||||
Array.isArray((chunk as any).citations)
|
||||
) {
|
||||
citations = (chunk as any).citations;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
@ -840,47 +987,58 @@ export abstract class BaseLLM implements ILLM {
|
|||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
|
||||
if (chunk.role === "assistant") {
|
||||
completion += chunk.content;
|
||||
yield chunk;
|
||||
} else if (chunk.role === "thinking") {
|
||||
thinking += chunk.content;
|
||||
}
|
||||
|
||||
if (chunk.role === "thinking") {
|
||||
thinking += chunk.content;
|
||||
yield chunk;
|
||||
}
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: chunk,
|
||||
});
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
if (thinking) {
|
||||
await this.writeLog(`Thinking:\n${thinking}\n\n`);
|
||||
}
|
||||
/*
|
||||
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
|
||||
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
|
||||
and you must include the complete unmodified block back to the API. This is critical
|
||||
for maintaining the model's reasoning flow and conversation integrity.
|
||||
|
||||
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
|
||||
requests when not using tools, so it's the simplest option to always add to history.
|
||||
*/
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
|
||||
if (citations) {
|
||||
await this.writeLog(
|
||||
`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`,
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status === "in_progress") {
|
||||
this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
}
|
||||
/*
|
||||
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
|
||||
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
|
||||
and you must include the complete unmodified block back to the API. This is critical
|
||||
for maintaining the model's reasoning flow and conversation integrity.
|
||||
|
||||
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
|
||||
requests when not using tools, so it's the simplest option to always add to history.
|
||||
*/
|
||||
|
||||
return {
|
||||
modelTitle: this.title ?? completionOptions.model,
|
||||
|
|
@ -948,7 +1106,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
);
|
||||
}
|
||||
|
||||
protected async * _streamComplete(
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
|
|
@ -956,7 +1114,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
throw new Error("Not implemented");
|
||||
}
|
||||
|
||||
protected async * _streamChat(
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
|
|
|
|||
|
|
@ -140,7 +140,9 @@ function testLLM(
|
|||
},
|
||||
},
|
||||
type: "function",
|
||||
wouldLikeTo: "Say hello",
|
||||
wouldLikeTo: "say hello",
|
||||
isCurrently: "saying hello",
|
||||
hasAlready: "said hello",
|
||||
readonly: true,
|
||||
group: "Hello",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -2,8 +2,9 @@ import {
|
|||
BedrockRuntimeClient,
|
||||
ContentBlock,
|
||||
ConverseStreamCommand,
|
||||
ConverseStreamCommandOutput,
|
||||
InvokeModelCommand,
|
||||
Message
|
||||
Message,
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
|
|
@ -11,7 +12,7 @@ import {
|
|||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
|
@ -31,6 +32,14 @@ interface ToolUseState {
|
|||
input: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for prompt caching metrics
|
||||
*/
|
||||
interface PromptCachingMetrics {
|
||||
cacheReadInputTokens: number;
|
||||
cacheWriteInputTokens: number;
|
||||
}
|
||||
|
||||
class Bedrock extends BaseLLM {
|
||||
static providerName = "bedrock";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
|
|
@ -41,8 +50,16 @@ class Bedrock extends BaseLLM {
|
|||
};
|
||||
|
||||
private _currentToolResponse: Partial<ToolUseState> | null = null;
|
||||
private _promptCachingMetrics: PromptCachingMetrics = {
|
||||
cacheReadInputTokens: 0,
|
||||
cacheWriteInputTokens: 0,
|
||||
};
|
||||
|
||||
public requestOptions: { region?: string; credentials?: any; headers?: Record<string, string> };
|
||||
public requestOptions: {
|
||||
region?: string;
|
||||
credentials?: any;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
|
@ -108,12 +125,17 @@ class Bedrock extends BaseLLM {
|
|||
},
|
||||
);
|
||||
|
||||
const input = this._generateConverseInput(messages, { ...options, stream: true });
|
||||
const input = this._generateConverseInput(messages, {
|
||||
...options,
|
||||
stream: true,
|
||||
});
|
||||
const command = new ConverseStreamCommand(input);
|
||||
|
||||
let response;
|
||||
let response: ConverseStreamCommandOutput;
|
||||
try {
|
||||
response = await client.send(command, { abortSignal: signal });
|
||||
response = (await client.send(command, {
|
||||
abortSignal: signal,
|
||||
})) as ConverseStreamCommandOutput;
|
||||
} catch (error: unknown) {
|
||||
console.error(error);
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
|
|
@ -124,51 +146,82 @@ class Bedrock extends BaseLLM {
|
|||
throw new Error("No stream received from Bedrock API");
|
||||
}
|
||||
|
||||
// Reset cache metrics for new request
|
||||
this._promptCachingMetrics = {
|
||||
cacheReadInputTokens: 0,
|
||||
cacheWriteInputTokens: 0,
|
||||
};
|
||||
|
||||
try {
|
||||
for await (const chunk of response.stream) {
|
||||
if (chunk.metadata?.usage) {
|
||||
console.log(`${JSON.stringify(chunk.metadata.usage)}`);
|
||||
}
|
||||
|
||||
if (chunk.contentBlockDelta?.delta) {
|
||||
|
||||
const delta: any = chunk.contentBlockDelta.delta
|
||||
const delta: any = chunk.contentBlockDelta.delta;
|
||||
|
||||
// Handle text content
|
||||
if (chunk.contentBlockDelta.delta.text) {
|
||||
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: chunk.contentBlockDelta.delta.text,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle text content
|
||||
if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) {
|
||||
yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent.text };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: (chunk.contentBlockDelta.delta as any).reasoningContent
|
||||
.text,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle signature for thinking
|
||||
if (delta.reasoningContent?.signature) {
|
||||
yield { role: "thinking", content: "", signature: delta.reasoningContent.signature };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
signature: delta.reasoningContent.signature,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle redacted thinking
|
||||
if (delta.redactedReasoning?.data) {
|
||||
yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: delta.redactedReasoning.data,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
|
||||
if (
|
||||
chunk.contentBlockDelta.delta.toolUse?.input &&
|
||||
this._currentToolResponse
|
||||
) {
|
||||
// Append the new input to the existing string
|
||||
if (this._currentToolResponse.input === undefined) {
|
||||
this._currentToolResponse.input = "";
|
||||
}
|
||||
this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input;
|
||||
this._currentToolResponse.input +=
|
||||
chunk.contentBlockDelta.delta.toolUse.input;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.contentBlockStart?.start) {
|
||||
const start: any = chunk.contentBlockStart.start
|
||||
const start: any = chunk.contentBlockStart.start;
|
||||
if (start.redactedReasoning) {
|
||||
yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: start.redactedReasoning.data,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -177,7 +230,7 @@ class Bedrock extends BaseLLM {
|
|||
this._currentToolResponse = {
|
||||
toolUseId: toolUse.toolUseId,
|
||||
name: toolUse.name,
|
||||
input: ""
|
||||
input: "",
|
||||
};
|
||||
}
|
||||
continue;
|
||||
|
|
@ -188,14 +241,16 @@ class Bedrock extends BaseLLM {
|
|||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: this._currentToolResponse.toolUseId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: this._currentToolResponse.name,
|
||||
arguments: this._currentToolResponse.input
|
||||
}
|
||||
}],
|
||||
toolCalls: [
|
||||
{
|
||||
id: this._currentToolResponse.toolUseId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: this._currentToolResponse.name,
|
||||
arguments: this._currentToolResponse.input,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
this._currentToolResponse = null;
|
||||
}
|
||||
|
|
@ -207,13 +262,16 @@ class Bedrock extends BaseLLM {
|
|||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`);
|
||||
throw new Error(
|
||||
`AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Error processing Bedrock stream: ${error.message}`);
|
||||
}
|
||||
throw new Error("Error processing Bedrock stream: Unknown error occurred");
|
||||
throw new Error(
|
||||
"Error processing Bedrock stream: Unknown error occurred",
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -228,22 +286,43 @@ class Bedrock extends BaseLLM {
|
|||
): any {
|
||||
const convertedMessages = this._convertMessages(messages);
|
||||
|
||||
const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
|
||||
const shouldCacheSystemMessage =
|
||||
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const enablePromptCaching =
|
||||
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
|
||||
|
||||
// Add header for prompt caching
|
||||
if (enablePromptCaching) {
|
||||
this.requestOptions.headers = {
|
||||
...this.requestOptions.headers,
|
||||
"x-amzn-bedrock-enablepromptcaching": "true",
|
||||
};
|
||||
}
|
||||
|
||||
const supportsTools =
|
||||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
|
||||
return {
|
||||
modelId: options.model,
|
||||
messages: convertedMessages,
|
||||
system: this.systemMessage ? [{ text: this.systemMessage }] : undefined,
|
||||
toolConfig: supportsTools && options.tools ? {
|
||||
tools: options.tools.map(tool => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters
|
||||
system: this.systemMessage
|
||||
? shouldCacheSystemMessage
|
||||
? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }]
|
||||
: [{ text: this.systemMessage }]
|
||||
: undefined,
|
||||
toolConfig:
|
||||
supportsTools && options.tools
|
||||
? {
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
}
|
||||
}
|
||||
}))
|
||||
} : undefined,
|
||||
: undefined,
|
||||
inferenceConfig: {
|
||||
maxTokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
|
|
@ -261,20 +340,29 @@ class Bedrock extends BaseLLM {
|
|||
.slice(0, 4),
|
||||
},
|
||||
additionalModelRequestFields: {
|
||||
"thinking": options.reasoning ? {
|
||||
"type": "enabled",
|
||||
"budget_tokens": options.reasoningBudgetTokens
|
||||
} : undefined,
|
||||
}
|
||||
thinking: options.reasoning
|
||||
? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private _convertMessage(message: ChatMessage): Message | null {
|
||||
private _convertMessage(
|
||||
message: ChatMessage,
|
||||
addCaching: boolean = false,
|
||||
): Message | null {
|
||||
// Handle system messages explicitly
|
||||
if (message.role === "system") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cachePoint = addCaching
|
||||
? { cachePoint: { type: "default" } }
|
||||
: undefined;
|
||||
|
||||
// Tool response handling
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
|
|
@ -285,12 +373,12 @@ class Bedrock extends BaseLLM {
|
|||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: message.content || ""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
text: message.content || "",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -303,8 +391,8 @@ class Bedrock extends BaseLLM {
|
|||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
}
|
||||
}))
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -312,84 +400,111 @@ class Bedrock extends BaseLLM {
|
|||
if (message.redactedThinking) {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
redactedContent: new Uint8Array(Buffer.from(message.redactedThinking))
|
||||
}
|
||||
redactedContent: new Uint8Array(
|
||||
Buffer.from(message.redactedThinking),
|
||||
),
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content]
|
||||
content: [content],
|
||||
};
|
||||
} else {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: (message.content as string) || "",
|
||||
signature: message.signature
|
||||
}
|
||||
|
||||
}
|
||||
signature: message.signature,
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content]
|
||||
content: [content],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Standard text message
|
||||
if (typeof message.content === "string") {
|
||||
const content: any[] = [{ text: message.content }];
|
||||
if (addCaching) {
|
||||
content.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
return {
|
||||
role: message.role,
|
||||
content: [{ text: message.content }]
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
// Improved multimodal content handling
|
||||
if (Array.isArray(message.content)) {
|
||||
const content: any[] = [];
|
||||
|
||||
// Process all parts first
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "text") {
|
||||
content.push({ text: part.text });
|
||||
} else if (part.type === "imageUrl" && part.imageUrl) {
|
||||
try {
|
||||
const [mimeType, base64Data] = part.imageUrl.url.split(",");
|
||||
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
|
||||
content.push({
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Buffer.from(base64Data, "base64"),
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process image: ${error}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Add cache point as a separate block at the end if needed
|
||||
if (addCaching && content.length > 0) {
|
||||
content.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
|
||||
return {
|
||||
role: message.role,
|
||||
content: message.content.map(part => {
|
||||
if (part.type === "text") {
|
||||
return { text: part.text };
|
||||
}
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
try {
|
||||
const [mimeType, base64Data] = part.imageUrl.url.split(",");
|
||||
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
|
||||
return {
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Buffer.from(base64Data, "base64")
|
||||
}
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process image: ${error}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}).filter(Boolean)
|
||||
content,
|
||||
} as Message;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private _convertMessages(messages: ChatMessage[]): any[] {
|
||||
const filteredmessages = messages.filter(
|
||||
(m) => m.role !== "system" && !!m.content,
|
||||
);
|
||||
const lastTwoUserMsgIndices = filteredmessages
|
||||
.map((msg, index) => (msg.role === "user" ? index : -1))
|
||||
.filter((index) => index !== -1)
|
||||
.slice(-2);
|
||||
|
||||
const converted = filteredmessages
|
||||
.map((message, filteredMsgIdx) => {
|
||||
// Add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
|
||||
const addCaching =
|
||||
this.cacheBehavior?.cacheConversation &&
|
||||
lastTwoUserMsgIndices.includes(filteredMsgIdx);
|
||||
|
||||
const converted = messages
|
||||
.map((message) => {
|
||||
try {
|
||||
return this._convertMessage(message);
|
||||
return this._convertMessage(message, addCaching);
|
||||
} catch (error) {
|
||||
console.error(`Failed to convert message: ${error}`);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
return converted;
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
|
|
@ -453,7 +568,6 @@ class Bedrock extends BaseLLM {
|
|||
return modelConfig.extractEmbeddings(responseBody);
|
||||
}
|
||||
|
||||
|
||||
private _getModelConfig() {
|
||||
const modelConfigs: { [key: string]: ModelConfig } = {
|
||||
cohere: {
|
||||
|
|
@ -491,7 +605,11 @@ class Bedrock extends BaseLLM {
|
|||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
credentials,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
|
||||
// Base payload for both models
|
||||
|
|
@ -530,11 +648,15 @@ class Bedrock extends BaseLLM {
|
|||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`);
|
||||
throw new Error(
|
||||
`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
|
||||
}
|
||||
throw new Error("Error in BedrockReranker.rerank: Unknown error occurred");
|
||||
throw new Error(
|
||||
"Error in BedrockReranker.rerank: Unknown error occurred",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
197
core/llm/llms/Docker.ts
Normal file
197
core/llm/llms/Docker.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
import { spawn } from "child_process";
|
||||
import { LLMOptions, ModelInstaller } from "../../index.js";
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
/**
|
||||
* Docker Model Runner provider
|
||||
*
|
||||
* Integrates with Docker Desktop's Model Runner feature (currently in beta)
|
||||
* that allows running local AI models through Docker.
|
||||
*
|
||||
* Docker Model Runner provides an OpenAI-compatible API endpoint, making it
|
||||
* easy to integrate with existing OpenAI-compatible code.
|
||||
*
|
||||
* More information at: https://docs.docker.com/desktop/features/model-runner/
|
||||
*/
|
||||
class Docker extends OpenAI implements ModelInstaller {
|
||||
static providerName = "docker";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:12434/engines/v1",
|
||||
model: "gemma3-4B-F4", // Default model
|
||||
};
|
||||
|
||||
private modelMap: Record<string, string> = {
|
||||
// Map of "continue model name" to Docker model name
|
||||
// Models can be pulled using: docker model pull <model_name>
|
||||
"llama3.3-70b": "ai/llama3.3:70B-Q4_K_M",
|
||||
"smollm2-360M-F4": "ai/smollm2:360M-Q4_K_M",
|
||||
"smollm2-360M-F16": "ai/ai/smollm2:360M-F16",
|
||||
"qwen2.5-7B-F16": "ai/qwen2.5:7B-F16",
|
||||
"qwen2.5-7B-F4": "ai/qwen2.5:7B-Q4_K_M",
|
||||
"phi4-14B-F16": "ai/phi4:14B-F16",
|
||||
"phi4-14B-F4": "ai/phi4:14B-Q4_K_M",
|
||||
"mistral-7B-F16": "ai/mistral:7B-F16",
|
||||
"mistral-7B-F4": "ai/mistral:7B-Q4_K_M",
|
||||
"mistral-nemo-12B": "ai/mistral-nemo:12B-Q4_K_M",
|
||||
"gemma3-4B-F16": "ai/gemma3:4B-F16",
|
||||
"gemma3-4B-F4": "ai/gemma3:4B-Q4_K_M",
|
||||
"llama3.2-3B-F16": "ai/llama3.2:3B-F16",
|
||||
"llama3.2-3B-F4": "ai/llama3.2:3B-Q4_K_M",
|
||||
"llama3.2-1B-F16": "ai/llama3.2:1B-F16",
|
||||
"llama3.2-1B-F8": "ai/llama3.2:1B-Q8_0",
|
||||
"qwq-32B-F16": "ai/qwq:32B-F16",
|
||||
"qwq-32B-F4": "ai/qwq:32B-Q4_K_M",
|
||||
"deepseek-r1-distill-llama-70B-F4":
|
||||
"ai/deepseek-r1-distill-llama:70B-Q4_K_M",
|
||||
"deepseek-r1-distill-llama-8B-F16": "ai/deepseek-r1-distill-llama:8B-F16",
|
||||
"deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M",
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
||||
// Handle model name mapping
|
||||
if (this.model && this.modelMap[this.model]) {
|
||||
this.model = this.modelMap[this.model];
|
||||
}
|
||||
|
||||
// Check if Docker Model Runner is active and enable it if needed
|
||||
this.ensureModelRunnerEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if Docker Model Runner is running at the expected port
|
||||
* and enables it if not running
|
||||
*/
|
||||
private async ensureModelRunnerEnabled(): Promise<void> {
|
||||
try {
|
||||
// Check if the Model Runner service is running on the expected port
|
||||
const isRunning = await this.isPortBound(12434);
|
||||
|
||||
if (!isRunning) {
|
||||
console.log(
|
||||
"Docker Model Runner not detected. Attempting to enable it...",
|
||||
);
|
||||
await this.executeDockerCommand([
|
||||
"desktop",
|
||||
"enable",
|
||||
"model-runner",
|
||||
"--tcp",
|
||||
"12434",
|
||||
]);
|
||||
console.log("Docker Model Runner has been enabled on port 12434");
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed to enable Docker Model Runner:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a port is currently bound/in use
|
||||
*/
|
||||
private async isPortBound(port: number): Promise<boolean> {
|
||||
try {
|
||||
await this.fetch(`http://localhost:${port}`, {
|
||||
method: "HEAD",
|
||||
signal: AbortSignal.timeout(1000),
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async executeDockerCommand(
|
||||
args: string[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn("docker", args, { shell: true });
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
proc.stdout.on("data", (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr.on("data", (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ stdout, stderr });
|
||||
} else {
|
||||
reject(
|
||||
new Error(`Docker command failed with code ${code}: ${stderr}`),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (signal) {
|
||||
signal.addEventListener("abort", () => {
|
||||
proc.kill();
|
||||
reject(new Error("Docker command was aborted"));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async listModels(): Promise<string[]> {
|
||||
try {
|
||||
// Execute docker model ls and parse the output
|
||||
const { stdout } = await this.executeDockerCommand([
|
||||
"model",
|
||||
"ls",
|
||||
"--format",
|
||||
"{{.Repository}}/{{.Tag}}",
|
||||
]);
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
} catch (error) {
|
||||
console.error("Failed to list Docker models:", error);
|
||||
return Object.values(this.modelMap);
|
||||
}
|
||||
}
|
||||
|
||||
async installModel(
|
||||
modelName: string,
|
||||
signal: AbortSignal,
|
||||
progressReporter?: (task: string, increment: number, total: number) => void,
|
||||
): Promise<any> {
|
||||
const targetModel = this.modelMap[modelName] || modelName;
|
||||
|
||||
try {
|
||||
// Report starting the installation
|
||||
progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100);
|
||||
|
||||
// Pull the model
|
||||
const { stdout, stderr } = await this.executeDockerCommand(
|
||||
["model", "pull", targetModel],
|
||||
signal,
|
||||
);
|
||||
|
||||
// Report completion
|
||||
progressReporter?.(
|
||||
`Docker model ${targetModel} installed successfully`,
|
||||
100,
|
||||
100,
|
||||
);
|
||||
|
||||
return { success: true, stdout, stderr };
|
||||
} catch (error) {
|
||||
console.error(`Failed to install Docker model ${targetModel}:`, error);
|
||||
// Fix: Type check the error before accessing message property
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
throw new Error(
|
||||
`Failed to install Docker model ${targetModel}: ${errorMessage}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Docker;
|
||||
|
|
@ -4,6 +4,7 @@ import {
|
|||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessagePart,
|
||||
TextMessagePart,
|
||||
ToolCallDelta,
|
||||
} from "../../index.js";
|
||||
import { findLast } from "../../util/findLast.js";
|
||||
|
|
@ -69,20 +70,84 @@ class Gemini extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the system message and merges it with the next user message if present.
|
||||
* @param messages Array of chat messages
|
||||
* @returns Modified array with system message merged into user message if applicable
|
||||
*/
|
||||
public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] {
|
||||
// should be public for use within VertexAI
|
||||
const msgs = [...messages];
|
||||
// If no messages or first message isn't system, return copy of original messages
|
||||
if (messages.length === 0 || messages[0]?.role !== "system") {
|
||||
return [...messages];
|
||||
}
|
||||
|
||||
if (msgs[0]?.role === "system") {
|
||||
const sysMsg = msgs.shift()?.content;
|
||||
// @ts-ignore
|
||||
if (msgs[0]?.role === "user") {
|
||||
// @ts-ignore
|
||||
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
|
||||
// Extract system message
|
||||
const systemMessage: ChatMessage = messages[0];
|
||||
|
||||
// Extract system content based on its type
|
||||
let systemContent = "";
|
||||
|
||||
if (typeof systemMessage.content === "string") {
|
||||
systemContent = systemMessage.content;
|
||||
} else if (Array.isArray(systemMessage.content)) {
|
||||
const contentArray: Array<MessagePart> =
|
||||
systemMessage.content as Array<MessagePart>;
|
||||
|
||||
const concatenatedText = contentArray
|
||||
.filter((part): part is TextMessagePart => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join(" ");
|
||||
|
||||
systemContent = concatenatedText ? concatenatedText : "";
|
||||
} else if (
|
||||
systemMessage.content &&
|
||||
typeof systemMessage.content === "object"
|
||||
) {
|
||||
const typedContent = systemMessage.content as TextMessagePart;
|
||||
systemContent = typedContent?.text || "";
|
||||
}
|
||||
|
||||
// Create new array without the system message
|
||||
const remainingMessages: ChatMessage[] = messages.slice(1);
|
||||
|
||||
// Check if there's a user message to merge with
|
||||
if (remainingMessages.length > 0 && remainingMessages[0].role === "user") {
|
||||
const userMessage: ChatMessage = remainingMessages[0];
|
||||
const prefix = `System message - follow these instructions in every response: ${systemContent}\n\n---\n\n`;
|
||||
|
||||
// Merge based on user content type
|
||||
if (typeof userMessage.content === "string") {
|
||||
userMessage.content = prefix + userMessage.content;
|
||||
} else if (Array.isArray(userMessage.content)) {
|
||||
const contentArray: Array<MessagePart> =
|
||||
userMessage.content as Array<MessagePart>;
|
||||
const textPart = contentArray.find((part) => part.type === "text") as
|
||||
| TextMessagePart
|
||||
| undefined;
|
||||
|
||||
if (textPart) {
|
||||
textPart.text = prefix + textPart.text;
|
||||
} else {
|
||||
userMessage.content.push({
|
||||
type: "text",
|
||||
text: prefix,
|
||||
} as TextMessagePart);
|
||||
}
|
||||
} else if (
|
||||
userMessage.content &&
|
||||
typeof userMessage.content === "object"
|
||||
) {
|
||||
const typedContent = userMessage.content as TextMessagePart;
|
||||
userMessage.content = [
|
||||
{
|
||||
type: "text",
|
||||
text: prefix + (typedContent.text || ""),
|
||||
} as TextMessagePart,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return msgs;
|
||||
return remainingMessages;
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
|
|
|
|||
70
core/llm/llms/Inception.ts
Normal file
70
core/llm/llms/Inception.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
/**
|
||||
* Inception Labs provider
|
||||
*
|
||||
* Integrates with Inception Labs' OpenAI-compatible API endpoints.
|
||||
* Provides access to Mercury models for autocomplete and other tasks.
|
||||
*
|
||||
* Different models use different API endpoints:
|
||||
* - mercury-editor-mini-experimental: zaragoza.api.inceptionlabs.ai
|
||||
* - mercury-editor-small-experimental: copenhagen.api.inceptionlabs.ai
|
||||
*
|
||||
* More information at: https://docs.inceptionlabs.ai/
|
||||
*/
|
||||
class Inception extends OpenAI {
|
||||
static providerName = "inception";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://copenhagen.api.inceptionlabs.ai/v1/",
|
||||
model: "mercury-editor-small-experimental",
|
||||
completionOptions: {
|
||||
temperature: 0.0,
|
||||
maxTokens: 150,
|
||||
presencePenalty: 1.5,
|
||||
stop: ["\n\n", "\n \n", "<|endoftext|>"],
|
||||
model: "mercury-editor-small-experimental", // Added model to fix TypeScript error
|
||||
},
|
||||
};
|
||||
|
||||
supportsFim(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
async *_streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const endpoint = new URL("completions", this.apiBase);
|
||||
const resp = await this.fetch(endpoint, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: options.model,
|
||||
prompt: prefix,
|
||||
suffix,
|
||||
max_tokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
top_p: options.topP,
|
||||
frequency_penalty: options.frequencyPenalty,
|
||||
presence_penalty: options.presencePenalty,
|
||||
stop: options.stop,
|
||||
stream: true,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
for await (const chunk of streamSse(resp)) {
|
||||
yield chunk.choices[0].text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Inception;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
|
|
@ -52,6 +52,41 @@ class SiliconFlow extends OpenAI {
|
|||
yield chunk.choices[0].text;
|
||||
}
|
||||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || query.trim() === "") {
|
||||
console.warn("[SiliconFlow] rerank: query is empty");
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!chunks || chunks.length === 0) {
|
||||
console.warn("[SiliconFlow] rerank: chunks is empty");
|
||||
return [];
|
||||
}
|
||||
|
||||
const endpoint = new URL("rerank", this.apiBase);
|
||||
const resp = await this.fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: this.model,
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
const results = data.results.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
||||
export default SiliconFlow;
|
||||
|
|
|
|||
|
|
@ -43,14 +43,16 @@ export class TransformersJsEmbeddingsProvider extends BaseLLM {
|
|||
static maxGroupSize: number = 1;
|
||||
static model: string = "all-MiniLM-L6-v2";
|
||||
static mockVector: number[] = Array.from({ length: 384 }).fill(2) as number[];
|
||||
static title: string = "Transformers.js (Built-In)";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
model: TransformersJsEmbeddingsProvider.model,
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super({ model: TransformersJsEmbeddingsProvider.model });
|
||||
super({
|
||||
model: TransformersJsEmbeddingsProvider.model,
|
||||
title: "Transformers.js (Built-In)",
|
||||
});
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ class WatsonX extends BaseLLM {
|
|||
if (this.apiBase?.includes("cloud.ibm.com")) {
|
||||
// watsonx SaaS
|
||||
const wxToken = await (
|
||||
await fetch(
|
||||
await this.fetch(
|
||||
`https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
|
||||
{
|
||||
method: "POST",
|
||||
|
|
@ -48,7 +48,7 @@ class WatsonX extends BaseLLM {
|
|||
// Using username/password auth
|
||||
const userPass = this.apiKey?.split(":");
|
||||
const wxToken = await (
|
||||
await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
|
||||
await this.fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
|
@ -61,7 +61,7 @@ class WatsonX extends BaseLLM {
|
|||
})
|
||||
).json();
|
||||
const wxTokenExpiry = await (
|
||||
await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
|
||||
await this.fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import {
|
|||
BaseCompletionOptions,
|
||||
IdeSettings,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
LLMOptions,
|
||||
ModelDescription,
|
||||
} from "../..";
|
||||
|
|
@ -18,6 +19,7 @@ import Cloudflare from "./Cloudflare";
|
|||
import Cohere from "./Cohere";
|
||||
import DeepInfra from "./DeepInfra";
|
||||
import Deepseek from "./Deepseek";
|
||||
import Docker from "./Docker";
|
||||
import Fireworks from "./Fireworks";
|
||||
import Flowise from "./Flowise";
|
||||
import FreeTrial from "./FreeTrial";
|
||||
|
|
@ -26,6 +28,7 @@ import Gemini from "./Gemini";
|
|||
import Groq from "./Groq";
|
||||
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
|
||||
import HuggingFaceTGI from "./HuggingFaceTGI";
|
||||
import Inception from "./Inception";
|
||||
import Kindo from "./Kindo";
|
||||
import LlamaCpp from "./LlamaCpp";
|
||||
import Llamafile from "./Llamafile";
|
||||
|
|
@ -87,6 +90,7 @@ export const LLMClasses = [
|
|||
ContinueProxy,
|
||||
Cloudflare,
|
||||
Deepseek,
|
||||
Docker,
|
||||
Msty,
|
||||
Azure,
|
||||
WatsonX,
|
||||
|
|
@ -104,6 +108,7 @@ export const LLMClasses = [
|
|||
SiliconFlow,
|
||||
Scaleway,
|
||||
Relace,
|
||||
Inception,
|
||||
];
|
||||
|
||||
export async function llmFromDescription(
|
||||
|
|
@ -111,7 +116,7 @@ export async function llmFromDescription(
|
|||
readFile: (filepath: string) => Promise<string>,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
llmLogger: ILLMLogger,
|
||||
completionOptions?: BaseCompletionOptions,
|
||||
systemMessage?: string,
|
||||
): Promise<BaseLLM | undefined> {
|
||||
|
|
@ -141,7 +146,7 @@ export async function llmFromDescription(
|
|||
cls.defaultOptions?.completionOptions?.maxTokens,
|
||||
},
|
||||
systemMessage,
|
||||
writeLog,
|
||||
logger: llmLogger,
|
||||
uniqueId,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ class ContinueProxy extends OpenAI {
|
|||
this.apiKey = value.workOsAccessToken;
|
||||
if (!this.onPremProxyUrl) {
|
||||
this.apiBase = new URL(
|
||||
"openai/v1/",
|
||||
"model-proxy/v1/",
|
||||
value.controlPlaneProxyUrl,
|
||||
).toString();
|
||||
}
|
||||
|
|
@ -29,7 +29,7 @@ class ContinueProxy extends OpenAI {
|
|||
this.orgScopeId = options.orgScopeId;
|
||||
this.onPremProxyUrl = options.onPremProxyUrl;
|
||||
if (this.onPremProxyUrl) {
|
||||
this.apiBase = new URL("openai/v1/", this.onPremProxyUrl).toString();
|
||||
this.apiBase = new URL("model-proxy/v1/", this.onPremProxyUrl).toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
315
core/llm/logFormatter.test.ts
Normal file
315
core/llm/logFormatter.test.ts
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
import { Buffer } from "buffer";
|
||||
import { Writable } from "stream";
|
||||
import { LLMLogFormatter } from "./logFormatter";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
class MemoryWritable extends Writable {
|
||||
data: Buffer[] = [];
|
||||
constructor() {
|
||||
super();
|
||||
this.data = [];
|
||||
}
|
||||
|
||||
_write(
|
||||
chunk: Buffer,
|
||||
encoding: BufferEncoding,
|
||||
callback: (error?: Error | null) => void,
|
||||
): void {
|
||||
this.data.push(chunk);
|
||||
callback();
|
||||
}
|
||||
|
||||
getText() {
|
||||
const decoder = new TextDecoder();
|
||||
return decoder.decode(Buffer.concat(this.data as any));
|
||||
}
|
||||
}
|
||||
|
||||
describe("LLMLogFormatter", () => {
|
||||
it("should format log items correctly", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output);
|
||||
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765432100,
|
||||
kind: "startChat",
|
||||
options: {
|
||||
model: "granite3.2-dense:8b",
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content: "You are a helpful assistant",
|
||||
},
|
||||
],
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello, ",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433200,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "world!",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433300,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "\nHow can I help you?",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765434100,
|
||||
kind: "success",
|
||||
promptTokens: 10,
|
||||
generatedTokens: 20,
|
||||
thinkingTokens: 0,
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:12.1 [Chat]",
|
||||
" Options: {",
|
||||
' "model": "granite3.2-dense:8b"',
|
||||
" }",
|
||||
" Role: system",
|
||||
" | You are a helpful assistant",
|
||||
" +1.0 Role: assistant",
|
||||
" | Hello, world!",
|
||||
" +1.2 | How can I help you?",
|
||||
" +2.0 Success",
|
||||
" Prompt Tokens: 10",
|
||||
" Generated Tokens: 20",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should format completion interactions correctly", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output);
|
||||
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765432100,
|
||||
kind: "startComplete",
|
||||
options: {
|
||||
model: "granite3.2-dense:8b",
|
||||
},
|
||||
prompt: "A horse is a horse",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "chunk",
|
||||
chunk: ", of course, of course",
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:12.1 [Complete]",
|
||||
" Options: {",
|
||||
' "model": "granite3.2-dense:8b"',
|
||||
" }",
|
||||
" Prompt:",
|
||||
" | A horse is a horse",
|
||||
" +1.0 Result:",
|
||||
" | , of course, of course",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should format FIM interactions correctly", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output);
|
||||
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765432100,
|
||||
kind: "startFim",
|
||||
options: {
|
||||
model: "granite3.2-dense:8b",
|
||||
},
|
||||
prefix: "A\nB",
|
||||
suffix: "D\nE",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "chunk",
|
||||
chunk: "C",
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:12.1 [Fim]",
|
||||
" Options: {",
|
||||
' "model": "granite3.2-dense:8b"',
|
||||
" }",
|
||||
" Prefix:",
|
||||
" | A",
|
||||
" | B",
|
||||
" Suffix:",
|
||||
" | D",
|
||||
" | E",
|
||||
" +1.0 Result:",
|
||||
" | C",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should interleave log items correctly", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output);
|
||||
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello, ",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "2",
|
||||
timestamp: 1698765433200,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello, ",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433300,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "World!",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "2",
|
||||
timestamp: 1698765433400,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "World!",
|
||||
},
|
||||
});
|
||||
// Check if we end interaction 2 and start another interaction,
|
||||
// it gets a different prefix marker.
|
||||
logger._logItem({
|
||||
interactionId: "2",
|
||||
timestamp: 1698765434000,
|
||||
kind: "success",
|
||||
promptTokens: 10,
|
||||
generatedTokens: 20,
|
||||
thinkingTokens: 0,
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "3",
|
||||
timestamp: 1698765434100,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Hello, World!",
|
||||
},
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:13.1 Role: assistant",
|
||||
" | Hello, ",
|
||||
"|15:17:13.2 Role: assistant",
|
||||
"| | Hello, ",
|
||||
" +0.2 | World!",
|
||||
"| +0.2 | World!",
|
||||
"| +0.8 Success",
|
||||
"| Prompt Tokens: 10",
|
||||
"| Generated Tokens: 20",
|
||||
"&15:17:14.1 Role: assistant",
|
||||
"& | Hello, World!",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should wrap long lines", () => {
|
||||
const logger = new LLMLogger();
|
||||
const output = new MemoryWritable();
|
||||
const formatter = new LLMLogFormatter(logger, output, 40);
|
||||
|
||||
// Test a single message long enough to wrap; the input is
|
||||
// "<xx...xx>", not "xxxx" to make sure we are writing the correct
|
||||
// substrings.
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433100,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "<" + "x".repeat(58) + ">",
|
||||
},
|
||||
});
|
||||
// Test when a first message doesn't wrap, but another message
|
||||
// that continues the same line causes a wrap
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433200,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "\n<" + "y".repeat(29),
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433300,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "y".repeat(29) + ">",
|
||||
},
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
timestamp: 1698765433400,
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "\n" + "Artichokes and Beans ".repeat(3),
|
||||
},
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
[
|
||||
" 15:17:13.1 Role: assistant",
|
||||
" | <" + "x".repeat(39),
|
||||
" . " + "x".repeat(19) + ">",
|
||||
" +0.1 | <" + "y".repeat(39),
|
||||
" +0.2 . " + "y".repeat(19) + ">",
|
||||
" +0.3 | Artichokes and Beans Artichokes and",
|
||||
" . Beans Artichokes and Beans ",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
});
|
||||
426
core/llm/logFormatter.ts
Normal file
426
core/llm/logFormatter.ts
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
import { Writable } from "stream";
|
||||
import {
|
||||
AssistantChatMessage,
|
||||
ChatMessage,
|
||||
LLMInteractionCancel,
|
||||
LLMInteractionError,
|
||||
LLMInteractionItem,
|
||||
LLMInteractionStartChat,
|
||||
LLMInteractionStartComplete,
|
||||
LLMInteractionStartFim,
|
||||
LLMInteractionSuccess,
|
||||
ThinkingChatMessage,
|
||||
ToolCallDelta,
|
||||
UserChatMessage,
|
||||
} from "..";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
// Markers for different overlapping interactions.
|
||||
const LOG_PREFIXES = [" ", "|", "&", "%", "#"];
|
||||
// Wrap wide to avoid messing up code
|
||||
const DEFAULT_WRAP_WIDTH = 100;
|
||||
|
||||
interface InteractionData {
|
||||
prefix: string;
|
||||
startItem: LLMInteractionItem;
|
||||
lastItem: LLMInteractionItem | null;
|
||||
}
|
||||
|
||||
function formatTimestamp(timestamp: number) {
|
||||
const date = new Date(timestamp);
|
||||
|
||||
const hours = date.getUTCHours().toString().padStart(2, "0");
|
||||
const minutes = date.getUTCMinutes().toString().padStart(2, "0");
|
||||
const seconds = date.getUTCSeconds();
|
||||
const milliseconds = date.getUTCMilliseconds();
|
||||
|
||||
// Format seconds with one decimal place
|
||||
const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`;
|
||||
|
||||
return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A class that formats LLM log output as a human-readable stream.
|
||||
* The general appearance of the output is something like:
|
||||
*
|
||||
* 01:23:45.6 [Chat]
|
||||
* Options: {
|
||||
* "maxTokens": 1000,
|
||||
* }
|
||||
* Role: system
|
||||
* | You are a helpful assistant.
|
||||
* Role: user
|
||||
* | Who are you?
|
||||
* +0.2 Role: assistant
|
||||
* | How can I help you today?
|
||||
* +0.3 | I can tell you about the weather or the stock mark
|
||||
* +0.4 . et. [THIS LINE IS WRAPPED]
|
||||
* |01:23:46.1 [Complete]
|
||||
* | Options: {
|
||||
* | "maxTokens": 1000,
|
||||
* | }
|
||||
* | Prefix:
|
||||
* | | COMPLETE THIS
|
||||
* +0.6 Success
|
||||
* PromptTokens: 50
|
||||
* GeneratedTokens: 30
|
||||
* | +0.2 Result:
|
||||
* | | COMPLETION
|
||||
*
|
||||
* The lines with | are a second interaction that starts while the
|
||||
* first one is still in progress; every interaction starts with
|
||||
* an absolute timestamp, and relative timestamps are included for
|
||||
* separately received results in the same interaction.
|
||||
*/
|
||||
export class LLMLogFormatter {
|
||||
// Current active interactions
|
||||
private interactions: Record<string, InteractionData> = {};
|
||||
private lastItem: LLMInteractionItem | null = null;
|
||||
// Item that started the current line; we use this to determine
|
||||
// if the next line needs a timestamp.
|
||||
private lastLineStartItem: LLMInteractionItem | null = null;
|
||||
private openLine: boolean = false;
|
||||
private openLineChars: number = 0;
|
||||
private lastFreedPrefix: string | null = null;
|
||||
|
||||
/**
|
||||
* Creates a new LLMLogWriter.
|
||||
* @param logger - The LLMLogger instance to listen to for log items
|
||||
* @param output - Stream to write formatted output to
|
||||
* @param wrapWidth - Maximum width of a line before wrapping
|
||||
*/
|
||||
constructor(
|
||||
private logger: LLMLogger,
|
||||
private output: Writable,
|
||||
private wrapWidth: number = DEFAULT_WRAP_WIDTH,
|
||||
) {
|
||||
this.logger.onLogItem((item) => {
|
||||
this.logItem(item);
|
||||
});
|
||||
}
|
||||
|
||||
private getInteractionData(item: LLMInteractionItem) {
|
||||
let interaction = this.interactions[item.interactionId];
|
||||
if (interaction !== undefined) {
|
||||
return interaction;
|
||||
}
|
||||
|
||||
let usedPrefixes = Object.values(this.interactions).map(
|
||||
(interaction) => interaction.prefix,
|
||||
);
|
||||
|
||||
// Select a prefix that is not currently in use, and is
|
||||
// also not the last retired prefix - but with the
|
||||
// exception that we can reuse the empty prefix " "
|
||||
// immediately - this isn't confusing.
|
||||
let i = 0;
|
||||
let prefix;
|
||||
while (true) {
|
||||
const candidate = i < LOG_PREFIXES.length ? LOG_PREFIXES[i] : `X`;
|
||||
if (
|
||||
!usedPrefixes.includes(candidate) &&
|
||||
(candidate === " " || candidate !== this.lastFreedPrefix)
|
||||
) {
|
||||
prefix = candidate;
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
this.interactions[item.interactionId] = {
|
||||
prefix,
|
||||
startItem: item,
|
||||
lastItem: null,
|
||||
};
|
||||
|
||||
return this.interactions[item.interactionId];
|
||||
}
|
||||
|
||||
private formatTimestamp(
|
||||
interaction: InteractionData,
|
||||
item: LLMInteractionItem,
|
||||
) {
|
||||
if (item !== this.lastLineStartItem) {
|
||||
if (item === interaction.startItem) {
|
||||
return formatTimestamp(item.timestamp);
|
||||
} else {
|
||||
const delta = (item.timestamp - interaction.startItem.timestamp) / 1000;
|
||||
return ("+" + delta.toFixed(1)).padStart(10, " ");
|
||||
}
|
||||
} else {
|
||||
return " ";
|
||||
}
|
||||
}
|
||||
|
||||
// the implementation behind logLines and logMessageText
|
||||
private logFragment(
|
||||
item: LLMInteractionItem,
|
||||
fragment: string,
|
||||
startAt: number,
|
||||
marker: string = "",
|
||||
joinBefore: boolean = false,
|
||||
joinAfter: boolean = false,
|
||||
wrap: boolean = false,
|
||||
) {
|
||||
const interaction = this.getInteractionData(item);
|
||||
|
||||
if (
|
||||
this.openLine &&
|
||||
(!joinBefore || item.interactionId !== this.lastItem?.interactionId)
|
||||
) {
|
||||
this.openLine = false;
|
||||
this.openLineChars = 0;
|
||||
this.output.write("\n");
|
||||
}
|
||||
|
||||
let continueAt = null;
|
||||
if (
|
||||
wrap &&
|
||||
fragment.length - startAt > this.wrapWidth - this.openLineChars
|
||||
) {
|
||||
continueAt = startAt + this.wrapWidth - this.openLineChars;
|
||||
|
||||
// Look for a better line-breaking point at whitespace
|
||||
const searchBackwardLimit = Math.max(startAt, continueAt - 20); // Don't look back too far
|
||||
for (let i = continueAt; i > searchBackwardLimit; i--) {
|
||||
if (/\s/.test(fragment.charAt(i))) {
|
||||
continueAt = i + 1; // Break after the whitespace
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// When there's whitespace immediately after the wrap width,
|
||||
// the above will result in breaking *after* that, so we exceed
|
||||
// the wrap width. The trimEnd() avoids that.
|
||||
fragment = fragment.substring(startAt, continueAt).trimEnd();
|
||||
joinAfter = false;
|
||||
} else if (startAt > 0) {
|
||||
fragment = fragment.substring(startAt);
|
||||
}
|
||||
|
||||
if (!this.openLine || !this.openLine) {
|
||||
let timestamp = this.formatTimestamp(interaction, item);
|
||||
this.output.write(`${interaction.prefix}${timestamp} ${marker}`);
|
||||
this.lastLineStartItem = item;
|
||||
}
|
||||
|
||||
this.output.write(fragment);
|
||||
this.openLine = joinAfter;
|
||||
this.lastItem = item;
|
||||
if (!this.openLine) {
|
||||
this.output.write("\n");
|
||||
this.openLineChars = 0;
|
||||
} else {
|
||||
this.openLineChars += fragment.length;
|
||||
}
|
||||
|
||||
return continueAt;
|
||||
}
|
||||
|
||||
// Use for everything but text content; a newline is
|
||||
// implicitly added at the end of content
|
||||
private logLines(
|
||||
item: LLMInteractionItem,
|
||||
content: string,
|
||||
marker: string = "",
|
||||
) {
|
||||
for (const line of content.split("\n")) {
|
||||
this.logFragment(item, line, 0, marker);
|
||||
}
|
||||
}
|
||||
|
||||
// This logs text context - as compared to logLines:
|
||||
// - No newline is appended to the end of content
|
||||
// - consecutive calls to logMessageText for the same interaction
|
||||
// will join onto a single line
|
||||
// - It will wrap text at the wrap width
|
||||
private logMessageText(item: LLMInteractionItem, content: string) {
|
||||
const lines = content.split("\n");
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
let startAt: number | null = 0;
|
||||
let marker = "| ";
|
||||
while (startAt !== null) {
|
||||
// When wrapping, the next start position is turned;
|
||||
// null means we've written everything
|
||||
startAt = this.logFragment(
|
||||
item,
|
||||
lines[i],
|
||||
startAt,
|
||||
marker,
|
||||
true,
|
||||
i === lines.length - 1,
|
||||
true,
|
||||
);
|
||||
marker = ". ";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private logToolcalls(item: LLMInteractionItem, toolsCalls: ToolCallDelta[]) {
|
||||
for (const toolCall of toolsCalls) {
|
||||
this.logLines(
|
||||
item,
|
||||
`Tool call: ${JSON.stringify(toolCall, undefined, 2)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private logMessageContent(
|
||||
item: LLMInteractionItem,
|
||||
message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage,
|
||||
) {
|
||||
if (typeof message.content === "string") {
|
||||
this.logMessageText(item, message.content);
|
||||
} else {
|
||||
for (const part of message.content) {
|
||||
if (part.type === "text") {
|
||||
this.logMessageText(item, part.text);
|
||||
} else {
|
||||
this.logLines(item, `Image: ${part.imageUrl.url}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private logMessage(
|
||||
item: LLMInteractionItem,
|
||||
message: ChatMessage,
|
||||
forceRole: boolean = false,
|
||||
) {
|
||||
let showRole = true;
|
||||
if (
|
||||
!forceRole &&
|
||||
(message.role === "assistant" || message.role === "thinking")
|
||||
) {
|
||||
const interaction = this.getInteractionData(item);
|
||||
const lastMessage =
|
||||
interaction.lastItem?.kind === "message"
|
||||
? interaction.lastItem.message
|
||||
: null;
|
||||
if (message.role === lastMessage?.role) {
|
||||
showRole = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (showRole) {
|
||||
this.logLines(item, "Role: " + message.role);
|
||||
}
|
||||
|
||||
switch (message.role) {
|
||||
case "assistant":
|
||||
if (message.toolCalls) {
|
||||
this.logToolcalls(item, message.toolCalls);
|
||||
}
|
||||
this.logMessageContent(item, message);
|
||||
break;
|
||||
case "thinking":
|
||||
if (message.toolCalls) {
|
||||
this.logToolcalls(item, message.toolCalls);
|
||||
}
|
||||
this.logMessageContent(item, message);
|
||||
if (message.redactedThinking) {
|
||||
this.logLines(item, `Redacted Thinking: ${message.redactedThinking}`);
|
||||
}
|
||||
if (message.signature) {
|
||||
this.logLines(item, `Signature: ${message.signature}`);
|
||||
}
|
||||
break;
|
||||
case "user":
|
||||
this.logMessageContent(item, message);
|
||||
break;
|
||||
case "system":
|
||||
this.logMessageText(item, message.content);
|
||||
break;
|
||||
case "tool":
|
||||
this.logLines(item, `Tool Call ID: ${message.toolCallId}`);
|
||||
this.logMessageText(item, message.content);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private logTokens(
|
||||
item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel,
|
||||
) {
|
||||
this.logLines(item, `Prompt Tokens: ${item.promptTokens}`);
|
||||
this.logLines(item, `Generated Tokens: ${item.generatedTokens}`);
|
||||
if (item.thinkingTokens > 0) {
|
||||
this.logLines(item, `Thinking Tokens: ${item.thinkingTokens}`);
|
||||
}
|
||||
}
|
||||
|
||||
private logOptions(
|
||||
item:
|
||||
| LLMInteractionStartChat
|
||||
| LLMInteractionStartComplete
|
||||
| LLMInteractionStartFim,
|
||||
) {
|
||||
this.logLines(
|
||||
item,
|
||||
"Options: " + JSON.stringify(item.options, undefined, 2),
|
||||
);
|
||||
}
|
||||
|
||||
private logItem(item: LLMInteractionItem) {
|
||||
const interaction = this.getInteractionData(item);
|
||||
|
||||
switch (item.kind) {
|
||||
case "startChat":
|
||||
this.logLines(item, "[Chat]");
|
||||
this.logOptions(item);
|
||||
let lastMessage = null;
|
||||
for (let message of item.messages) {
|
||||
this.logMessage(item, message, true);
|
||||
}
|
||||
break;
|
||||
case "startComplete":
|
||||
this.logLines(item, "[Complete]");
|
||||
this.logOptions(item);
|
||||
this.logLines(item, "Prompt:");
|
||||
this.logLines(item, item.prompt, "| ");
|
||||
break;
|
||||
case "startFim":
|
||||
this.logLines(item, "[Fim]");
|
||||
this.logOptions(item);
|
||||
this.logLines(item, "Prefix:");
|
||||
this.logLines(item, item.prefix, "| ");
|
||||
this.logLines(item, "Suffix:");
|
||||
this.logLines(item, item.suffix, "| ");
|
||||
break;
|
||||
case "chunk":
|
||||
if (interaction.lastItem?.kind !== "chunk") {
|
||||
this.logLines(item, "Result:");
|
||||
}
|
||||
this.logMessageText(item, item.chunk);
|
||||
break;
|
||||
case "message":
|
||||
this.logMessage(item, item.message);
|
||||
break;
|
||||
case "cancel":
|
||||
this.logLines(item, "Cancelled");
|
||||
this.logTokens(item);
|
||||
break;
|
||||
case "error":
|
||||
this.logLines(item, "Error");
|
||||
this.logTokens(item);
|
||||
break;
|
||||
case "success":
|
||||
this.logLines(item, "Success");
|
||||
this.logTokens(item);
|
||||
break;
|
||||
}
|
||||
|
||||
if (
|
||||
item.kind === "cancel" ||
|
||||
item.kind === "error" ||
|
||||
item.kind === "success"
|
||||
) {
|
||||
if (interaction.prefix !== " ") {
|
||||
this.lastFreedPrefix = interaction.prefix;
|
||||
}
|
||||
delete this.interactions[item.interactionId];
|
||||
} else {
|
||||
interaction.lastItem = item;
|
||||
}
|
||||
}
|
||||
}
|
||||
43
core/llm/logger.ts
Normal file
43
core/llm/logger.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import {
|
||||
ILLMLogger,
|
||||
ILLMInteractionLog,
|
||||
LLMInteractionItem,
|
||||
LLMInteractionItemDetails,
|
||||
} from "..";
|
||||
|
||||
type LLMLogItemFunction = (item: LLMInteractionItem) => void;
|
||||
|
||||
export class LLMLogger implements ILLMLogger {
|
||||
private nextId = 0;
|
||||
|
||||
public createInteractionLog(): LLMInteractionLog {
|
||||
return new LLMInteractionLog(this, (this.nextId++).toString());
|
||||
}
|
||||
|
||||
private logItemListeners: LLMLogItemFunction[] = [];
|
||||
|
||||
onLogItem(listener: LLMLogItemFunction) {
|
||||
this.logItemListeners.push(listener);
|
||||
}
|
||||
|
||||
public _logItem(item: LLMInteractionItem) {
|
||||
for (const listener of this.logItemListeners) {
|
||||
listener(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class LLMInteractionLog implements ILLMInteractionLog {
|
||||
constructor(
|
||||
private logger: LLMLogger,
|
||||
public interactionId: string,
|
||||
) {}
|
||||
|
||||
logItem(item: LLMInteractionItemDetails) {
|
||||
this.logger._logItem({
|
||||
...item,
|
||||
interactionId: this.interactionId,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
59
core/llm/rules/isRuleActive.test.ts
Normal file
59
core/llm/rules/isRuleActive.test.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { isRuleActive } from "./isRuleActive";
|
||||
|
||||
describe("isRuleActive", () => {
|
||||
const rule = {
|
||||
name: "My Rule",
|
||||
rule: "Do no harm",
|
||||
if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}',
|
||||
};
|
||||
|
||||
it("should return false when activePaths is empty", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: [],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when no matching paths exist", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["test.py", "main.js"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return true when both conditions are met", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.tsx", "main.js"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when only glob matches but model doesn't", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.tsx"],
|
||||
currentModel: "gpt-4",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when model matches but glob doesn't", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.ts"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
68
core/llm/rules/isRuleActive.ts
Normal file
68
core/llm/rules/isRuleActive.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { Rule } from "@continuedev/config-yaml";
|
||||
import { compileExpression } from "filtrex";
|
||||
import { minimatch } from "minimatch";
|
||||
|
||||
const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/;
|
||||
|
||||
const createGlobFunction = (activePaths: string[]) => {
|
||||
return (pattern: string) => {
|
||||
const result = activePaths.some((path) => minimatch(path, pattern));
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
const contains = (str: string, searchStr: string): boolean => {
|
||||
return str.includes(searchStr);
|
||||
};
|
||||
|
||||
const evaluateIf = ({
|
||||
condition,
|
||||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
condition: string;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim();
|
||||
if (!expression) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const evaluate = compileExpression(expression, {
|
||||
extraFunctions: {
|
||||
glob: createGlobFunction(activePaths),
|
||||
contains,
|
||||
},
|
||||
constants: {
|
||||
"current.model.model": currentModel,
|
||||
},
|
||||
});
|
||||
|
||||
return evaluate({});
|
||||
} catch (error) {
|
||||
console.error("Error evaluating rule condition:", error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const isRuleActive = ({
|
||||
rule,
|
||||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
rule: Rule;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}): boolean => {
|
||||
if (typeof rule === "string") {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (rule.if) {
|
||||
return evaluateIf({ condition: rule.if, activePaths, currentModel });
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
22
core/llm/utils/extractPathsFromCodeBlocks.ts
Normal file
22
core/llm/utils/extractPathsFromCodeBlocks.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
/**
|
||||
* Extracts file paths from markdown code blocks
|
||||
*/
|
||||
export function extractPathsFromCodeBlocks(content: string): string[] {
|
||||
// Match:
|
||||
// 1. Starting ```
|
||||
// 2. Optional language identifier
|
||||
// 3. Required whitespace
|
||||
// 4. File path (captured) that must contain a dot and extension
|
||||
const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g;
|
||||
const paths: string[] = [];
|
||||
let match;
|
||||
|
||||
while ((match = codeBlockRegex.exec(content)) !== null) {
|
||||
const path = match[1];
|
||||
if (path && !path.startsWith("```")) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
1126
core/package-lock.json
generated
1126
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -39,16 +39,17 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"ts-jest": "^29.1.1"
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
|
||||
"@aws-sdk/credential-providers": "^3.758.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.63",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
"@modelcontextprotocol/sdk": "^1.5.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
|
|
@ -65,6 +66,7 @@
|
|||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
|
|||
|
|
@ -2,10 +2,11 @@ import { ContinueSDK, SlashCommand } from "../..";
|
|||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
|
||||
import { renderPromptFileV2 } from "../v2/renderPromptFile";
|
||||
|
||||
import { getContextProviderHelpers } from "./getContextProviderHelpers";
|
||||
import { renderTemplatedString } from "./renderTemplatedString";
|
||||
import { updateChatHistory } from "./updateChatHistory";
|
||||
import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
|
|
@ -67,8 +68,18 @@ export function slashCommandFromPromptFileV1(
|
|||
context.llm.systemMessage = systemMessage;
|
||||
|
||||
const userInput = extractUserInput(context.input, name);
|
||||
const renderedPrompt = await renderPromptV1(prompt, context, userInput);
|
||||
const messages = updateChatHistory(
|
||||
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
|
||||
config: context.config,
|
||||
fullInput: userInput,
|
||||
embeddingsProvider: context.config.modelsByRole.embed[0],
|
||||
reranker: context.config.modelsByRole.rerank[0],
|
||||
llm: context.llm,
|
||||
ide: context.ide,
|
||||
selectedCode: context.selectedCode,
|
||||
fetch: context.fetch,
|
||||
});
|
||||
|
||||
const messages = replaceSlashCommandWithPromptInChatHistory(
|
||||
context.history,
|
||||
name,
|
||||
renderedPrompt,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
export function updateChatHistory(
|
||||
export function replaceSlashCommandWithPromptInChatHistory(
|
||||
history: any[],
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ export async function renderPromptFileV2(
|
|||
rawContent: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<[ContextItem[], string]> {
|
||||
const [preamble, body] = getPreambleAndBody(rawContent);
|
||||
const [_, body] = getPreambleAndBody(rawContent);
|
||||
|
||||
const contextItemsPromises: Promise<ContextItem[]>[] = [];
|
||||
const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
|
||||
|
|
@ -75,6 +75,10 @@ export async function renderPromptFileV2(
|
|||
});
|
||||
|
||||
const contextItems = (await Promise.all(contextItemsPromises)).flat();
|
||||
const renderedPrompt =
|
||||
contextItems.map((item) => item.content).join("\n\n") +
|
||||
"\n\n" +
|
||||
renderedBody;
|
||||
|
||||
return [contextItems, renderedBody];
|
||||
return [contextItems, renderedPrompt];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,8 +5,6 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
|
||||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
import { OrganizationDescription } from "../config/ProfileLifecycleManager";
|
||||
import { SharedConfigSchema } from "../config/sharedConfig";
|
||||
import { GlobalContextModelSelections } from "../util/GlobalContext";
|
||||
|
||||
|
|
@ -15,7 +13,6 @@ import type {
|
|||
ChatMessage,
|
||||
ContextItem,
|
||||
ContextItemWithId,
|
||||
ContextProviderWithParams,
|
||||
ContextSubmenuItem,
|
||||
DiffLine,
|
||||
DocsIndexingDetails,
|
||||
|
|
@ -33,6 +30,7 @@ import type {
|
|||
SlashCommandDescription,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
|
||||
|
||||
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
|
||||
|
||||
|
|
@ -67,15 +65,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
{
|
||||
result: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
profileId: string | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedOrgId: string;
|
||||
usingContinueForTeams: boolean;
|
||||
},
|
||||
];
|
||||
"config/deleteModel": [{ title: string }, void];
|
||||
"config/addContextProvider": [ContextProviderWithParams, void];
|
||||
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
|
||||
"config/listProfiles": [
|
||||
undefined,
|
||||
{ profiles: ProfileDescription[] | null; selectedProfileId: string | null },
|
||||
];
|
||||
"config/refreshProfiles": [undefined, void];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
|
||||
|
|
@ -200,5 +196,4 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
|
||||
"controlPlane/listOrganizations": [undefined, OrganizationDescription[]];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,19 +1,8 @@
|
|||
import { ProfileDescription } from "../config/ConfigHandler.js";
|
||||
|
||||
import { ToCoreFromIdeOrWebviewProtocol } from "./core.js";
|
||||
import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
|
||||
|
||||
export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & {
|
||||
didChangeSelectedProfile: [{ id: string | null }, void];
|
||||
didChangeSelectedOrg: [
|
||||
{ id: string | null; profileId?: string | null },
|
||||
void,
|
||||
];
|
||||
};
|
||||
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
didChangeAvailableProfiles: [
|
||||
{ profiles: ProfileDescription[]; selectedProfileId: string | null },
|
||||
void,
|
||||
];
|
||||
didSelectOrganization: [{ orgId: string | null }, void];
|
||||
didChangeSelectedProfile: [{ id: string }, void];
|
||||
didChangeSelectedOrg: [{ id: string; profileId?: string }, void];
|
||||
};
|
||||
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol;
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
openUrl: [string, void];
|
||||
runCommand: [{ command: string; options?: TerminalOptions }, void];
|
||||
getSearchResults: [{ query: string }, string];
|
||||
getFileResults: [{ pattern: string }, string[]];
|
||||
subprocess: [{ command: string; cwd?: string }, [string, string]];
|
||||
saveFile: [{ filepath: string }, void];
|
||||
fileExists: [{ filepath: string }, boolean];
|
||||
|
|
@ -106,5 +107,4 @@ export type ToWebviewOrCoreFromIdeProtocol = {
|
|||
{ sessionInfo: ControlPlaneSessionInfo | undefined },
|
||||
void,
|
||||
];
|
||||
didChangeIdeSettings: [{ settings: IdeSettings }, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
|
|||
import type {
|
||||
ApplyState,
|
||||
CodeToEdit,
|
||||
ContextSubmenuItem,
|
||||
EditStatus,
|
||||
MessageContent,
|
||||
RangeInFileWithContents,
|
||||
|
|
@ -20,6 +19,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
streamId: string;
|
||||
curSelectedModelTitle: string;
|
||||
filepath?: string;
|
||||
toolCallId?: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -187,6 +187,10 @@ export class MessageIde implements IDE {
|
|||
return this.request("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getFileResults(pattern: string): Promise<string[]> {
|
||||
return this.request("getFileResults", { pattern });
|
||||
}
|
||||
|
||||
getProblems(fileUri: string): Promise<Problem[]> {
|
||||
return this.request("getProblems", { filepath: fileUri });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -166,6 +166,10 @@ export class ReverseMessageIde {
|
|||
return this.ide.getSearchResults(data.query);
|
||||
});
|
||||
|
||||
this.on("getFileResults", (data) => {
|
||||
return this.ide.getFileResults(data.pattern);
|
||||
});
|
||||
|
||||
this.on("getProblems", (data) => {
|
||||
return this.ide.getProblems(data.filepath);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -16,12 +16,10 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"history/save",
|
||||
"devdata/log",
|
||||
"config/addModel",
|
||||
"config/addContextProvider",
|
||||
"config/newPromptFile",
|
||||
"config/ideSettingsUpdate",
|
||||
"config/getSerializedProfileInfo",
|
||||
"config/deleteModel",
|
||||
"config/listProfiles",
|
||||
"config/refreshProfiles",
|
||||
"config/openProfile",
|
||||
"config/updateSharedConfig",
|
||||
|
|
@ -61,7 +59,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"controlPlane/openUrl",
|
||||
"controlPlane/listOrganizations",
|
||||
];
|
||||
|
||||
// Message types to pass through from core to webview
|
||||
|
|
@ -76,10 +73,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
|||
"addContextItem",
|
||||
"refreshSubmenuItems",
|
||||
"isContinueInputFocused",
|
||||
"didChangeAvailableProfiles",
|
||||
"setTTSActive",
|
||||
"getWebviewHistoryLength",
|
||||
"getCurrentSessionId",
|
||||
"didCloseFiles",
|
||||
"didSelectOrganization",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContextItemWithId,
|
||||
ContextProviderName,
|
||||
IndexingProgressUpdate,
|
||||
IndexingStatus,
|
||||
PackageDocsResult,
|
||||
} from "../index.js";
|
||||
|
||||
export type ToWebviewFromIdeOrCoreProtocol = {
|
||||
|
|
@ -13,6 +13,9 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
{
|
||||
result: ConfigResult<BrowserSerializedContinueConfig>;
|
||||
profileId: string | null;
|
||||
organizations: SerializedOrgWithProfiles[];
|
||||
selectedOrgId: string | null;
|
||||
usingContinueForTeams: boolean;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler";
|
||||
import { ControlPlaneClient } from "../control-plane/client";
|
||||
import Mock from "../llm/llms/Mock";
|
||||
import { LLMLogger } from "../llm/logger";
|
||||
import FileSystemIde from "../util/filesystem";
|
||||
|
||||
import { TEST_DIR } from "./testDir";
|
||||
|
|
@ -17,7 +18,7 @@ export const testControlPlaneClient = new ControlPlaneClient(
|
|||
export const testConfigHandler = new ConfigHandler(
|
||||
testIde,
|
||||
ideSettingsPromise,
|
||||
async (text) => {},
|
||||
new LLMLogger(),
|
||||
Promise.resolve(undefined),
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,18 @@
|
|||
export enum BuiltInToolNames {
|
||||
ReadFile = "builtin_read_file",
|
||||
EditExistingFile = "builtin_edit_existing_file",
|
||||
ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
|
||||
CreateNewFile = "builtin_create_new_file",
|
||||
RunTerminalCommand = "builtin_run_terminal_command",
|
||||
ViewSubdirectory = "builtin_view_subdirectory",
|
||||
ViewRepoMap = "builtin_view_repo_map",
|
||||
ExactSearch = "builtin_exact_search",
|
||||
GrepSearch = "builtin_grep_search",
|
||||
FileGlobSearch = "builtin_file_glob_search",
|
||||
SearchWeb = "builtin_search_web",
|
||||
ViewDiff = "builtin_view_diff",
|
||||
LSTool = "builtin_ls",
|
||||
|
||||
// excluded from allTools for now
|
||||
ViewRepoMap = "builtin_view_repo_map",
|
||||
ViewSubdirectory = "builtin_view_subdirectory",
|
||||
}
|
||||
|
||||
export const BUILT_IN_GROUP_NAME = "Built-In";
|
||||
|
|
|
|||
|
|
@ -4,14 +4,14 @@ import { canParseUrl } from "../util/url";
|
|||
import { BuiltInToolNames } from "./builtIn";
|
||||
|
||||
import { createNewFileImpl } from "./implementations/createNewFile";
|
||||
import { exactSearchImpl } from "./implementations/exactSearch";
|
||||
import { fileGlobSearchImpl } from "./implementations/globSearch";
|
||||
import { grepSearchImpl } from "./implementations/grepSearch";
|
||||
import { lsToolImpl } from "./implementations/lsTool";
|
||||
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
|
||||
import { readFileImpl } from "./implementations/readFile";
|
||||
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
|
||||
import { searchWebImpl } from "./implementations/searchWeb";
|
||||
import { viewDiffImpl } from "./implementations/viewDiff";
|
||||
import { viewRepoMapImpl } from "./implementations/viewRepoMap";
|
||||
import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory";
|
||||
|
||||
async function callHttpTool(
|
||||
url: string,
|
||||
|
|
@ -139,22 +139,27 @@ export async function callTool(
|
|||
switch (uri) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
// Note: Custom GUI handling for edit
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.ExactSearch:
|
||||
return await exactSearchImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
return await grepSearchImpl(args, extras);
|
||||
case BuiltInToolNames.FileGlobSearch:
|
||||
return await fileGlobSearchImpl(args, extras);
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
return await runTerminalCommandImpl(args, extras);
|
||||
case BuiltInToolNames.SearchWeb:
|
||||
return await searchWebImpl(args, extras);
|
||||
case BuiltInToolNames.ViewDiff:
|
||||
return await viewDiffImpl(args, extras);
|
||||
case BuiltInToolNames.ViewRepoMap:
|
||||
return await viewRepoMapImpl(args, extras);
|
||||
case BuiltInToolNames.ViewSubdirectory:
|
||||
return await viewSubdirectoryImpl(args, extras);
|
||||
case BuiltInToolNames.LSTool:
|
||||
return await lsToolImpl(args, extras);
|
||||
case BuiltInToolNames.ReadCurrentlyOpenFile:
|
||||
return await readCurrentlyOpenFileImpl(args, extras);
|
||||
// case BuiltInToolNames.ViewRepoMap:
|
||||
// return await viewRepoMapImpl(args, extras);
|
||||
// case BuiltInToolNames.ViewSubdirectory:
|
||||
// return await viewSubdirectoryImpl(args, extras);
|
||||
default:
|
||||
return await callToolFromUri(uri, args, extras);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
|||
export const createNewFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Create New File",
|
||||
wouldLikeTo: "create a new file",
|
||||
wouldLikeTo: "create a new file at {{{ filepath }}}",
|
||||
isCurrently: "creating a new file at {{{ filepath }}}",
|
||||
hasAlready: "created a new file at {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
function: {
|
||||
|
|
|
|||
37
core/tools/definitions/editFile.ts
Normal file
37
core/tools/definitions/editFile.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface EditToolArgs {
|
||||
filepath: string;
|
||||
new_contents: string;
|
||||
}
|
||||
|
||||
export const editFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.EditExistingFile,
|
||||
description:
|
||||
"Use this tool to edit an existing file. If you don't know the contents of the file, read it first.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "new_contents"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to edit, relative to the root of the workspace.",
|
||||
},
|
||||
new_contents: {
|
||||
type: "string",
|
||||
description: "The new file contents",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
26
core/tools/definitions/globSearch.ts
Normal file
26
core/tools/definitions/globSearch.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const globSearchTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Glob File Search",
|
||||
wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
|
||||
isCurrently: 'finding file matches for "{{{ pattern }}}"',
|
||||
hasAlready: 'retreived file matches for "{{{ pattern }}}"',
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.FileGlobSearch,
|
||||
description: "Search for files in the project",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["pattern"],
|
||||
properties: {
|
||||
pattern: {
|
||||
type: "string",
|
||||
description: "Glob pattern for file path matching",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -1,15 +1,17 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const exactSearchTool: Tool = {
|
||||
export const grepSearchTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Exact Search",
|
||||
displayTitle: "Grep Search",
|
||||
wouldLikeTo: 'search for "{{{ query }}}" in the repository',
|
||||
isCurrently: 'getting search results for "{{{ query }}}"',
|
||||
hasAlready: 'retrieved search results for "{{{ query }}}"',
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.ExactSearch,
|
||||
description: "Perform an exact search over the repository using ripgrep.",
|
||||
name: BuiltInToolNames.GrepSearch,
|
||||
description: "Perform a search over the repository using ripgrep.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["query"],
|
||||
33
core/tools/definitions/lsTool.ts
Normal file
33
core/tools/definitions/lsTool.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const lsTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "LS Tool",
|
||||
wouldLikeTo: "list files and folders in {{{ dirPath }}}",
|
||||
isCurrently: "listing files and folders in {{{ dirPath }}}",
|
||||
hasAlready: "listed files and folders in {{{ dirPath }}}",
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.LSTool,
|
||||
description: "List files and folders in a given directory",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["dirPath", "recursive"],
|
||||
properties: {
|
||||
dirPath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'",
|
||||
},
|
||||
recursive: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"If true, lists files and folders recursively. To prevent unexpected large results, use this sparingly",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -5,6 +5,8 @@ export const readCurrentlyOpenFileTool: Tool = {
|
|||
type: "function",
|
||||
displayTitle: "Read Currently Open File",
|
||||
wouldLikeTo: "read the current file",
|
||||
isCurrently: "reading the current file",
|
||||
hasAlready: "viewed the current file",
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ export const readFileTool: Tool = {
|
|||
type: "function",
|
||||
displayTitle: "Read File",
|
||||
wouldLikeTo: "read {{{ filepath }}}",
|
||||
isCurrently: "reading {{{ filepath }}}",
|
||||
hasAlready: "viewed {{{ filepath }}}",
|
||||
readonly: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
|||
export const runTerminalCommandTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Run Terminal Command",
|
||||
wouldLikeTo: "run a terminal command",
|
||||
wouldLikeTo: "run the following terminal command:",
|
||||
isCurrently: "running the following terminal command:",
|
||||
hasAlready: "ran the following terminal command:",
|
||||
readonly: false,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue