diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5b248d5d8..2b9f266d5 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -9,7 +9,7 @@ ## Screenshots -[ For visual changes, include screenshots. ] +[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ] ## Testing instructions diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml new file mode 100644 index 000000000..5985624de --- /dev/null +++ b/.github/workflows/auto-release.yml @@ -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 diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index bf2fa74a6..a968dcc19 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -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 }} diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 7408cf76f..80eaa4931 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -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" diff --git a/.github/workflows/release-config-yaml.yml b/.github/workflows/release-config-yaml.yml new file mode 100644 index 000000000..0847f5c0c --- /dev/null +++ b/.github/workflows/release-config-yaml.yml @@ -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 diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml new file mode 100644 index 000000000..39dc5b7f1 --- /dev/null +++ b/.github/workflows/vscode-version-bump.yml @@ -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 diff --git a/.node-version b/.node-version new file mode 100644 index 000000000..18c284172 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +20.11.0 \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4f7e1634f..4b42593d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 diff --git a/README.md b/README.md index fc07289d7..dffa26b4f 100644 --- a/README.md +++ b/README.md @@ -44,11 +44,11 @@ ![edit](docs/static/img/edit.gif) -## 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 -![actions](docs/static/img/actions.gif) +![agent](docs/static/img/agent.gif) diff --git a/binary/build.js b/binary/build.js index adc461396..99a5d0e12 100644 --- a/binary/build.js +++ b/binary/build.js @@ -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 diff --git a/binary/package-lock.json b/binary/package-lock.json index 5ce095e37..51ea6b1f1 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -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", diff --git a/binary/src/index.ts b/binary/src/index.ts index 32bede332..dce9a25ab 100644 --- a/binary/src/index.ts +++ b/binary/src/index.ts @@ -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) { diff --git a/core/.eslintrc.json b/core/.eslintrc.json index e541d57c1..633895fb7 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -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 }] diff --git a/core/autocomplete/context/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts index 5528d223c..e2288138a 100644 --- a/core/autocomplete/context/ImportDefinitionsService.ts +++ b/core/autocomplete/context/ImportDefinitionsService.ts @@ -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; diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 79b598f1e..7a29f8a8f 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -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 = diff --git a/core/autocomplete/util/AutocompleteLruCache.ts b/core/autocomplete/util/AutocompleteLruCache.ts index a93b23c5a..adac906ff 100644 --- a/core/autocomplete/util/AutocompleteLruCache.ts +++ b/core/autocomplete/util/AutocompleteLruCache.ts @@ -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(), ); diff --git a/core/commands/index.ts b/core/commands/index.ts index 486eaccf2..3037d7ef7 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -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, diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index eadaa137f..bf71952e9 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -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 () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 7db61161a..2d4a471d5 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -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) => 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; + private organizations: OrgWithProfiles[] = []; + currentProfile: ProfileLifecycleManager | null; + currentOrg: OrgWithProfiles; constructor( private readonly ide: IDE, private ideSettingsPromise: Promise, - private readonly writeLog: (text: string) => Promise, + private llmLogger: ILLMLogger, sessionInfoPromise: Promise, - 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 { + 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 { + 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 { + 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 { + 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 { - const workspaceId = await this.getWorkspaceId(); - const lastSelectedIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - return lastSelectedIds[workspaceId] ?? null; - } - - async getSelectedOrgId(): Promise { - 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 { - 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) { - // 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 > { @@ -465,10 +444,6 @@ export class ConfigHandler { ); } - listProfiles(): ProfileDescription[] | null { - return this.profiles?.map((p) => p.profileDescription) ?? null; - } - async loadConfig(): Promise> { 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 { 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); + } } diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index 9d4bd2842..d93ab9236 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -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 | undefined; private savedBrowserConfigResult?: ConfigResult; diff --git a/core/config/default.ts b/core/config/default.ts index 8c349a13b..81c133455 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -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, }; diff --git a/core/config/load.ts b/core/config/load.ts index 4c98e7728..b85359641 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -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, + 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, + llmLogger: ILLMLogger, workOsAccessToken: string | undefined, overrideConfigJson: SerializedContinueConfig | undefined, ): Promise> { @@ -947,7 +936,7 @@ async function loadContinueConfigFromJson( ideSettings, ideInfo, uniqueId, - writeLog, + llmLogger, workOsAccessToken, ); return { diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts index 189bb21ed..cf689b45d 100644 --- a/core/config/migrateSharedConfig.ts +++ b/core/config/migrateSharedConfig.ts @@ -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}`); diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts index 8babfffde..729653674 100644 --- a/core/config/onboarding.ts +++ b/core/config/onboarding.ts @@ -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; } diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 09a1846a4..21ea27e14 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -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, - private writeLog: (message: string) => Promise, + 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, ); } diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 46245a7f0..f49c8bb7a 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -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, private controlPlaneClient: ControlPlaneClient, - private writeLog: (message: string) => Promise, + 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; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 1eddedb6a..cf9efb399 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -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, - private writeLog: (message: string) => Promise, - 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, - writeLog: (message: string) => Promise, - onReload: () => void, + llmLogger: ILLMLogger, rawYaml: string, + orgScopeId: string | null, ): Promise { 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 { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 28371a220..626546b74 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -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, controlPlaneClient: ControlPlaneClient, - writeLog: (message: string) => Promise, + llmLogger: ILLMLogger, overrideConfigJson: SerializedContinueConfig | undefined, overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, overrideConfigYamlByPath: string | undefined, + orgScopeId: string | null, ): Promise> { 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); } diff --git a/core/config/types.ts b/core/config/types.ts index 2a68c4c35..3cf978540 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -90,7 +90,7 @@ declare global { requestOptions?: RequestOptions; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + 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 extends unknown + ? Omit + : 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; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; aiGatewaySlug?: string; diff --git a/core/config/util.ts b/core/config/util.ts index 8bfe6a84f..ee827c2f9 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -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( diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts index 072dc79de..dbc567005 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -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 { diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 1ca54337b..1edb48604 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -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> { 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, + 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, + llmLogger: ILLMLogger, workOsAccessToken: string | undefined, overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, controlPlaneClient: ControlPlaneClient, configYamlPath: string | undefined, + orgScopeId: string | null, ): Promise> { 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, ); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 57caf324a..fa9c92cac 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -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, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +async function modelConfigToBaseLLM({ + model, + uniqueId, + ideSettings, + llmLogger, + platformConfigMetadata, + config, +}: { + model: ModelConfig; + uniqueId: string; + ideSettings: IdeSettings; + llmLogger: ILLMLogger; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { 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, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +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 { 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, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { - 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 { + 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]; diff --git a/core/context/allRerankers.ts b/core/context/allRerankers.ts index 944a77dbc..e87cd06e3 100644 --- a/core/context/allRerankers.ts +++ b/core/context/allRerankers.ts @@ -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, }; diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 3b9fa0cf4..360e68670 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -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(); + // 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); } } diff --git a/core/context/providers/FolderContextProvider.ts b/core/context/providers/FolderContextProvider.ts index 42df6ab34..b4d2e0e09 100644 --- a/core/context/providers/FolderContextProvider.ts +++ b/core/context/providers/FolderContextProvider.ts @@ -35,7 +35,7 @@ class FolderContextProvider extends BaseContextProvider { const folders = await walkDirs( args.ide, { - onlyDirs: true, + include: "dirs", source: "load submenu items - folder", }, workspaceDirs, diff --git a/core/context/providers/GitCommitContextProvider.ts b/core/context/providers/GitCommitContextProvider.ts index 24d2eab7b..e387b2f66 100644 --- a/core/context/providers/GitCommitContextProvider.ts +++ b/core/context/providers/GitCommitContextProvider.ts @@ -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 => { + 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 { + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { 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 { 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 []; } diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts index 0cb8e2c66..be9e50cd5 100644 --- a/core/context/providers/MCPContextProvider.ts +++ b/core/context/providers/MCPContextProvider.ts @@ -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 }); diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 6a2db46fa..575e7af4b 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -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, diff --git a/core/context/providers/SearchContextProvider.ts b/core/context/providers/SearchContextProvider.ts index bc44964ac..ec75994c3 100644 --- a/core/context/providers/SearchContextProvider.ts +++ b/core/context/providers/SearchContextProvider.ts @@ -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 { 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", }, ]; diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 345d21e37..d8eb90ef9 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -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 { 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"); diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index dee4d7ef4..77a3dc108 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -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", { diff --git a/core/core.ts b/core/core.ts index 5fa42c5b6..d59900cec 100644 --- a/core/core.ts +++ b/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, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = 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[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 } - diff --git a/core/index.d.ts b/core/index.d.ts index d86d73489..345829ecf 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -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; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + 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 extends unknown + ? Omit + : 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; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; + rules?: Rule[]; apiKey?: string; // continueProperties @@ -711,6 +799,8 @@ export interface IDE { getSearchResults(query: string): Promise; + getFileResults(pattern: string): Promise; + subprocess(command: string, cwd?: string): Promise<[string, string]>; getProblems(fileUri?: string | undefined): Promise; @@ -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; selectedModelByRole: Record; data?: DataDestination[]; @@ -1336,7 +1429,7 @@ export interface BrowserSerializedContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; modelsByRole: Record; diff --git a/core/indexing/docs/DocsCache.test.ts b/core/indexing/docs/DocsCache.test.ts new file mode 100644 index 000000000..341cd0229 --- /dev/null +++ b/core/indexing/docs/DocsCache.test.ts @@ -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}`, + ); + }); +}); diff --git a/core/indexing/docs/DocsCache.ts b/core/indexing/docs/DocsCache.ts new file mode 100644 index 000000000..f250b797c --- /dev/null +++ b/core/indexing/docs/DocsCache.ts @@ -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 { + const filepath = DocsCache.getFilepathForEmbeddingIdAndUrl( + embeddingId, + url, + ); + + return new Promise((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)); + }); + } +} diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 682b76a23..9677abfef 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -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); +// }); +// }); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 75f92b145..99dc1d539 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -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; 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 { + 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 { + 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 { + // 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, + ) || [], + }), + ); } } diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts index ef9b528ce..03fc44212 100644 --- a/core/indexing/docs/crawlers/ChromiumCrawler.ts +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -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 { diff --git a/core/indexing/docs/migrations.ts b/core/indexing/docs/migrations.ts index 64e313175..b9d5fbcf8 100644 --- a/core/indexing/docs/migrations.ts +++ b/core/indexing/docs/migrations.ts @@ -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> >(`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); diff --git a/core/indexing/docs/preIndexed.ts b/core/indexing/docs/preIndexed.ts deleted file mode 100644 index b66d21e70..000000000 --- a/core/indexing/docs/preIndexed.ts +++ /dev/null @@ -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 { - return new Promise((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; -} diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts deleted file mode 100644 index 5342396fd..000000000 --- a/core/indexing/docs/preIndexedDocs.ts +++ /dev/null @@ -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; diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index ef21149b1..f76c6a7f6 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -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 - }>(); + 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); } diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 399a24875..50acba4ed 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -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", }, ); diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 2c70006a8..04e45a3ca 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -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( diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 7e8b8e9f5..333c79e70 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -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 = { diff --git a/core/llm/countTokens.test.ts b/core/llm/countTokens.test.ts index 6895e9269..92f9d92c5 100644 --- a/core/llm/countTokens.test.ts +++ b/core/llm/countTokens.test.ts @@ -1,3 +1,4 @@ +// @ts-nocheck // Generated by continue import { ChatMessage, MessagePart } from "../index.js"; import { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index a05889c52..2fc01f9b8 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -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 { } + async close(): Promise {} async encode(text: string): Promise { 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, }; - diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 404902e91..7f535d1fd 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -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/"); diff --git a/core/llm/index.ts b/core/llm/index.ts index dda2e7a87..7544b5292 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -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 | undefined = undefined; @@ -129,7 +133,7 @@ export abstract class BaseLLM implements ILLM { template?: TemplateType; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + 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 { @@ -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( @@ -537,52 +574,89 @@ export abstract class BaseLLM implements ILLM { ): AsyncGenerator { 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 { 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, diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index efd98ae00..2ce2d93b2 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -140,7 +140,9 @@ function testLLM( }, }, type: "function", - wouldLikeTo: "Say hello", + wouldLikeTo: "say hello", + isCurrently: "saying hello", + hasAlready: "said hello", readonly: true, group: "Hello", }, diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index c6abbeb97..7fefbd329 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -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 = { @@ -41,8 +50,16 @@ class Bedrock extends BaseLLM { }; private _currentToolResponse: Partial | null = null; + private _promptCachingMetrics: PromptCachingMetrics = { + cacheReadInputTokens: 0, + cacheWriteInputTokens: 0, + }; - public requestOptions: { region?: string; credentials?: any; headers?: Record }; + public requestOptions: { + region?: string; + credentials?: any; + headers?: Record; + }; 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", + ); } } } diff --git a/core/llm/llms/Docker.ts b/core/llm/llms/Docker.ts new file mode 100644 index 000000000..d9c3d5c58 --- /dev/null +++ b/core/llm/llms/Docker.ts @@ -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 = { + apiBase: "http://localhost:12434/engines/v1", + model: "gemma3-4B-F4", // Default model + }; + + private modelMap: Record = { + // Map of "continue model name" to Docker model name + // Models can be pulled using: docker model pull + "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 { + 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 { + 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 { + 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 { + 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; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index e6b1c5c70..1c5d24aee 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -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 = + systemMessage.content as Array; + + 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 = + userMessage.content as Array; + 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( diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts new file mode 100644 index 000000000..ef204fec1 --- /dev/null +++ b/core/llm/llms/Inception.ts @@ -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 = { + 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 { + 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; diff --git a/core/llm/llms/SiliconFlow.ts b/core/llm/llms/SiliconFlow.ts index 6f522f920..cddb22b0d 100644 --- a/core/llm/llms/SiliconFlow.ts +++ b/core/llm/llms/SiliconFlow.ts @@ -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 { + 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; diff --git a/core/llm/llms/TransformersJsEmbeddingsProvider.ts b/core/llm/llms/TransformersJsEmbeddingsProvider.ts index d17c9e0f1..7bd7b78ec 100644 --- a/core/llm/llms/TransformersJsEmbeddingsProvider.ts +++ b/core/llm/llms/TransformersJsEmbeddingsProvider.ts @@ -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 | undefined = { model: TransformersJsEmbeddingsProvider.model, }; constructor() { - super({ model: TransformersJsEmbeddingsProvider.model }); + super({ + model: TransformersJsEmbeddingsProvider.model, + title: "Transformers.js (Built-In)", + }); } async embed(chunks: string[]) { diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 561f4f2d9..7f1fe2e0c 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -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", diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index e6a33a9a8..cef09098c 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -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, uniqueId: string, ideSettings: IdeSettings, - writeLog: (log: string) => Promise, + llmLogger: ILLMLogger, completionOptions?: BaseCompletionOptions, systemMessage?: string, ): Promise { @@ -141,7 +146,7 @@ export async function llmFromDescription( cls.defaultOptions?.completionOptions?.maxTokens, }, systemMessage, - writeLog, + logger: llmLogger, uniqueId, }; diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 01f62cd00..181db2abd 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -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(); } } diff --git a/core/llm/logFormatter.test.ts b/core/llm/logFormatter.test.ts new file mode 100644 index 000000000..80aa92068 --- /dev/null +++ b/core/llm/logFormatter.test.ts @@ -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 + // "", 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"), + ); + }); +}); diff --git a/core/llm/logFormatter.ts b/core/llm/logFormatter.ts new file mode 100644 index 000000000..cae469f77 --- /dev/null +++ b/core/llm/logFormatter.ts @@ -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 = {}; + 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; + } + } +} diff --git a/core/llm/logger.ts b/core/llm/logger.ts new file mode 100644 index 000000000..ae4699a45 --- /dev/null +++ b/core/llm/logger.ts @@ -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(), + }); + } +} diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts new file mode 100644 index 000000000..f50b9972a --- /dev/null +++ b/core/llm/rules/isRuleActive.test.ts @@ -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); + }); +}); diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts new file mode 100644 index 000000000..47125c644 --- /dev/null +++ b/core/llm/rules/isRuleActive.ts @@ -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; +}; diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts new file mode 100644 index 000000000..7573a1f6f --- /dev/null +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -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; +} diff --git a/core/package-lock.json b/core/package-lock.json index 765c3541e..24aeb4f18 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -9,13 +9,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", @@ -32,6 +32,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", @@ -100,7 +101,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" @@ -288,51 +290,51 @@ } }, "node_modules/@aws-sdk/client-bedrock-runtime": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.758.0.tgz", - "integrity": "sha512-T7s+fULUxN3AcJP+lgoUKLawzVEtyCTi+5Ga+wrHnqEPwAsM/wg7VctsZfow1fCgARLT/lzmP2LTCi8ycRnQWg==", + "version": "3.779.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.779.0.tgz", + "integrity": "sha512-MyzZks8XxWwdsA4VlyPW4IekUjpgDI91VwMvEtOITHD8w+9nTGJtD32HcCKNQQCHWYfSoOj7yIoHRisVatR8yw==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-node": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/eventstream-serde-browser": "^4.0.1", - "@smithy/eventstream-serde-config-resolver": "^4.0.1", - "@smithy/eventstream-serde-node": "^4.0.1", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-node": "3.777.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/eventstream-serde-browser": "^4.0.2", + "@smithy/eventstream-serde-config-resolver": "^4.1.0", + "@smithy/eventstream-serde-node": "^4.0.2", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", - "@smithy/util-stream": "^4.1.2", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", + "@smithy/util-stream": "^4.2.0", "@smithy/util-utf8": "^4.0.0", "@types/uuid": "^9.0.1", "tslib": "^2.6.2", @@ -343,47 +345,47 @@ } }, "node_modules/@aws-sdk/client-cognito-identity": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.758.0.tgz", - "integrity": "sha512-8bOXVYtf/0OUN0jXTIHLv3V0TAS6kvvCRAy7nmiL/fDde0O+ChW1WZU7CVPAOtFEpFCdKskDcxFspM7m1k6qyg==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.777.0.tgz", + "integrity": "sha512-VGtFI3SH+jKfPln+9CM16F9zKieIqSxUSZNzQ6WZahPDVC79VmlG6QkXCqgm9Y4qZf4ebcdMhO23+FkR4s9vhA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-node": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-node": "3.777.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -392,51 +394,51 @@ } }, "node_modules/@aws-sdk/client-sagemaker-runtime": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sagemaker-runtime/-/client-sagemaker-runtime-3.758.0.tgz", - "integrity": "sha512-6pZdZT+Xol56UKcpUDzOlRwLgmVIgv4I2bvCsvq4YI0TnSNhO6/Ob2I8l0GzUTU2qoO2XBkrhO1t+zLuc681ig==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sagemaker-runtime/-/client-sagemaker-runtime-3.777.0.tgz", + "integrity": "sha512-b5IE89QOt7pvaImtDiOmUlKVGK7pcb3rW7nIKEqY65pJboIT/RNkehfA/XrlfgDjgGhVebojpUm/paqG+2xlDg==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-node": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/eventstream-serde-browser": "^4.0.1", - "@smithy/eventstream-serde-config-resolver": "^4.0.1", - "@smithy/eventstream-serde-node": "^4.0.1", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-node": "3.777.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/eventstream-serde-browser": "^4.0.2", + "@smithy/eventstream-serde-config-resolver": "^4.1.0", + "@smithy/eventstream-serde-node": "^4.0.2", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", - "@smithy/util-stream": "^4.1.2", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", + "@smithy/util-stream": "^4.2.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -445,46 +447,46 @@ } }, "node_modules/@aws-sdk/client-sso": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.758.0.tgz", - "integrity": "sha512-BoGO6IIWrLyLxQG6txJw6RT2urmbtlwfggapNCrNPyYjlXpzTSJhBYjndg7TpDATFd0SXL0zm8y/tXsUXNkdYQ==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.777.0.tgz", + "integrity": "sha512-0+z6CiAYIQa7s6FJ+dpBYPi9zr9yY5jBg/4/FGcwYbmqWPXwL9Thdtr0FearYRZgKl7bhL3m3dILCCfWqr3teQ==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -493,19 +495,19 @@ } }, "node_modules/@aws-sdk/core": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.758.0.tgz", - "integrity": "sha512-0RswbdR9jt/XKemaLNuxi2gGr4xGlHyGxkTdhSQzCyUe9A9OPCoLl3rIESRguQEech+oJnbHk/wuiwHqTuP9sg==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.775.0.tgz", + "integrity": "sha512-8vpW4WihVfz0DX+7WnnLGm3GuQER++b0IwQG35JlQMlgqnc44M//KbJPsIHA0aJUJVwJAEShgfr5dUbY8WUzaA==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/core": "^3.1.5", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/signature-v4": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/util-middleware": "^4.0.1", + "@aws-sdk/types": "3.775.0", + "@smithy/core": "^3.2.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/signature-v4": "^5.0.2", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/util-middleware": "^4.0.2", "fast-xml-parser": "4.4.1", "tslib": "^2.6.2" }, @@ -514,14 +516,14 @@ } }, "node_modules/@aws-sdk/credential-provider-cognito-identity": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.758.0.tgz", - "integrity": "sha512-y/rHZqyChlEkNRr59gn4hv0gjhJwGmdCdW0JI1K9p3P9p7EurWGjr2M6+goTn3ilOlcAwrl5oFKR5jLt27TkOA==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.777.0.tgz", + "integrity": "sha512-lNvz3v94TvEcBvQqVUyg+c/aL3Max+8wUMXvehWoQPv9y9cJAHciZqvA/G+yFo/JB+1Y4IBpMu09W2lfpT6Euw==", "dependencies": { - "@aws-sdk/client-cognito-identity": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/client-cognito-identity": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -529,14 +531,14 @@ } }, "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.758.0.tgz", - "integrity": "sha512-N27eFoRrO6MeUNumtNHDW9WOiwfd59LPXPqDrIa3kWL/s+fOKFHb9xIcF++bAwtcZnAxKkgpDCUP+INNZskE+w==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.775.0.tgz", + "integrity": "sha512-6ESVxwCbGm7WZ17kY1fjmxQud43vzJFoLd4bmlR+idQSWdqlzGDYdcfzpjDKTcivdtNrVYmFvcH1JBUwCRAZhw==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -544,19 +546,19 @@ } }, "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.758.0.tgz", - "integrity": "sha512-Xt9/U8qUCiw1hihztWkNeIR+arg6P+yda10OuCHX6kFVx3auTlU7+hCqs3UxqniGU4dguHuftf3mRpi5/GJ33Q==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.775.0.tgz", + "integrity": "sha512-PjDQeDH/J1S0yWV32wCj2k5liRo0ssXMseCBEkCsD3SqsU8o5cU82b0hMX4sAib/RkglCSZqGO0xMiN0/7ndww==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/property-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/util-stream": "^4.1.2", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/property-provider": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/util-stream": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -564,22 +566,22 @@ } }, "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.758.0.tgz", - "integrity": "sha512-cymSKMcP5d+OsgetoIZ5QCe1wnp2Q/tq+uIxVdh9MbfdBBEnl9Ecq6dH6VlYS89sp4QKuxHxkWXVnbXU3Q19Aw==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.777.0.tgz", + "integrity": "sha512-1X9mCuM9JSQPmQ+D2TODt4THy6aJWCNiURkmKmTIPRdno7EIKgAqrr/LLN++K5mBf54DZVKpqcJutXU2jwo01A==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-env": "3.758.0", - "@aws-sdk/credential-provider-http": "3.758.0", - "@aws-sdk/credential-provider-process": "3.758.0", - "@aws-sdk/credential-provider-sso": "3.758.0", - "@aws-sdk/credential-provider-web-identity": "3.758.0", - "@aws-sdk/nested-clients": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-env": "3.775.0", + "@aws-sdk/credential-provider-http": "3.775.0", + "@aws-sdk/credential-provider-process": "3.775.0", + "@aws-sdk/credential-provider-sso": "3.777.0", + "@aws-sdk/credential-provider-web-identity": "3.777.0", + "@aws-sdk/nested-clients": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/credential-provider-imds": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -587,21 +589,21 @@ } }, "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.758.0.tgz", - "integrity": "sha512-+DaMv63wiq7pJrhIQzZYMn4hSarKiizDoJRvyR7WGhnn0oQ/getX9Z0VNCV3i7lIFoLNTb7WMmQ9k7+z/uD5EQ==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.777.0.tgz", + "integrity": "sha512-ZD66ywx1Q0KyUSuBXZIQzBe3Q7MzX8lNwsrCU43H3Fww+Y+HB3Ncws9grhSdNhKQNeGmZ+MgKybuZYaaeLwJEQ==", "dependencies": { - "@aws-sdk/credential-provider-env": "3.758.0", - "@aws-sdk/credential-provider-http": "3.758.0", - "@aws-sdk/credential-provider-ini": "3.758.0", - "@aws-sdk/credential-provider-process": "3.758.0", - "@aws-sdk/credential-provider-sso": "3.758.0", - "@aws-sdk/credential-provider-web-identity": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/credential-provider-env": "3.775.0", + "@aws-sdk/credential-provider-http": "3.775.0", + "@aws-sdk/credential-provider-ini": "3.777.0", + "@aws-sdk/credential-provider-process": "3.775.0", + "@aws-sdk/credential-provider-sso": "3.777.0", + "@aws-sdk/credential-provider-web-identity": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/credential-provider-imds": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -609,15 +611,15 @@ } }, "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.758.0.tgz", - "integrity": "sha512-AzcY74QTPqcbXWVgjpPZ3HOmxQZYPROIBz2YINF0OQk0MhezDWV/O7Xec+K1+MPGQO3qS6EDrUUlnPLjsqieHA==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.775.0.tgz", + "integrity": "sha512-A6k68H9rQp+2+7P7SGO90Csw6nrUEm0Qfjpn9Etc4EboZhhCLs9b66umUsTsSBHus4FDIe5JQxfCUyt1wgNogg==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -625,17 +627,17 @@ } }, "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.758.0.tgz", - "integrity": "sha512-x0FYJqcOLUCv8GLLFDYMXRAQKGjoM+L0BG4BiHYZRDf24yQWFCAZsCQAYKo6XZYh2qznbsW6f//qpyJ5b0QVKQ==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.777.0.tgz", + "integrity": "sha512-9mPz7vk9uE4PBVprfINv4tlTkyq1OonNevx2DiXC1LY4mCUCNN3RdBwAY0BTLzj0uyc3k5KxFFNbn3/8ZDQP7w==", "dependencies": { - "@aws-sdk/client-sso": "3.758.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/token-providers": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/client-sso": "3.777.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/token-providers": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -643,15 +645,15 @@ } }, "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.758.0.tgz", - "integrity": "sha512-XGguXhBqiCXMXRxcfCAVPlMbm3VyJTou79r/3mxWddHWF0XbhaQiBIbUz6vobVTD25YQRbWSmSch7VA8kI5Lrw==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.777.0.tgz", + "integrity": "sha512-uGCqr47fnthkqwq5luNl2dksgcpHHjSXz2jUra7TXtFOpqvnhOW8qXjoa1ivlkq8qhqlaZwCzPdbcN0lXpmLzQ==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/nested-clients": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/nested-clients": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -659,26 +661,28 @@ } }, "node_modules/@aws-sdk/credential-providers": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-providers/-/credential-providers-3.758.0.tgz", - "integrity": "sha512-BaGVBdm9ynsErIc/mLuUwJ1OQcL/pkhCuAm24jpsif3evZ5wgyZnEAZB2yRin+mQnQaQT3L+KvTbdKGfjL8+fQ==", + "version": "3.778.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-providers/-/credential-providers-3.778.0.tgz", + "integrity": "sha512-Yy1RSBvoDp/iqGDpmgy5/YnSP2ac9NxTv3wdAjKlqVVStlKWU9nG8MPHZRfy01oPNJ5YWZL9stxHjNKC9hg9eg==", "dependencies": { - "@aws-sdk/client-cognito-identity": "3.758.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/credential-provider-cognito-identity": "3.758.0", - "@aws-sdk/credential-provider-env": "3.758.0", - "@aws-sdk/credential-provider-http": "3.758.0", - "@aws-sdk/credential-provider-ini": "3.758.0", - "@aws-sdk/credential-provider-node": "3.758.0", - "@aws-sdk/credential-provider-process": "3.758.0", - "@aws-sdk/credential-provider-sso": "3.758.0", - "@aws-sdk/credential-provider-web-identity": "3.758.0", - "@aws-sdk/nested-clients": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/core": "^3.1.5", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/client-cognito-identity": "3.777.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/credential-provider-cognito-identity": "3.777.0", + "@aws-sdk/credential-provider-env": "3.775.0", + "@aws-sdk/credential-provider-http": "3.775.0", + "@aws-sdk/credential-provider-ini": "3.777.0", + "@aws-sdk/credential-provider-node": "3.777.0", + "@aws-sdk/credential-provider-process": "3.775.0", + "@aws-sdk/credential-provider-sso": "3.777.0", + "@aws-sdk/credential-provider-web-identity": "3.777.0", + "@aws-sdk/nested-clients": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/credential-provider-imds": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -686,13 +690,13 @@ } }, "node_modules/@aws-sdk/middleware-host-header": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.734.0.tgz", - "integrity": "sha512-LW7RRgSOHHBzWZnigNsDIzu3AiwtjeI2X66v+Wn1P1u+eXssy1+up4ZY/h+t2sU4LU36UvEf+jrZti9c6vRnFw==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.775.0.tgz", + "integrity": "sha512-tkSegM0Z6WMXpLB8oPys/d+umYIocvO298mGvcMCncpRl77L9XkvSLJIFzaHes+o7djAgIduYw8wKIMStFss2w==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -700,12 +704,12 @@ } }, "node_modules/@aws-sdk/middleware-logger": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.734.0.tgz", - "integrity": "sha512-mUMFITpJUW3LcKvFok176eI5zXAUomVtahb9IQBwLzkqFYOrMJvWAvoV4yuxrJ8TlQBG8gyEnkb9SnhZvjg67w==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.775.0.tgz", + "integrity": "sha512-FaxO1xom4MAoUJsldmR92nT1G6uZxTdNYOFYtdHfd6N2wcNaTuxgjIvqzg5y7QIH9kn58XX/dzf1iTjgqUStZw==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -713,13 +717,13 @@ } }, "node_modules/@aws-sdk/middleware-recursion-detection": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.734.0.tgz", - "integrity": "sha512-CUat2d9ITsFc2XsmeiRQO96iWpxSKYFjxvj27Hc7vo87YUHRnfMfnc8jw1EpxEwMcvBD7LsRa6vDNky6AjcrFA==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.775.0.tgz", + "integrity": "sha512-GLCzC8D0A0YDG5u3F5U03Vb9j5tcOEFhr8oc6PDk0k0vm5VwtZOE6LvK7hcCSoAB4HXyOUM0sQuXrbaAh9OwXA==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -727,16 +731,16 @@ } }, "node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.758.0.tgz", - "integrity": "sha512-iNyehQXtQlj69JCgfaOssgZD4HeYGOwxcaKeG6F+40cwBjTAi0+Ph1yfDwqk2qiBPIRWJ/9l2LodZbxiBqgrwg==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.775.0.tgz", + "integrity": "sha512-7Lffpr1ptOEDE1ZYH1T78pheEY1YmeXWBfFt/amZ6AGsKSLG+JPXvof3ltporTGR2bhH/eJPo7UHCglIuXfzYg==", "dependencies": { - "@aws-sdk/core": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@smithy/core": "^3.1.5", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@smithy/core": "^3.2.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -744,46 +748,46 @@ } }, "node_modules/@aws-sdk/nested-clients": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.758.0.tgz", - "integrity": "sha512-YZ5s7PSvyF3Mt2h1EQulCG93uybprNGbBkPmVuy/HMMfbFTt4iL3SbKjxqvOZelm86epFfj7pvK7FliI2WOEcg==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.777.0.tgz", + "integrity": "sha512-bmmVRsCjuYlStYPt06hr+f8iEyWg7+AklKCA8ZLDEJujXhXIowgUIqXmqpTkXwkVvDQ9tzU7hxaONjyaQCGybA==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.758.0", - "@aws-sdk/middleware-host-header": "3.734.0", - "@aws-sdk/middleware-logger": "3.734.0", - "@aws-sdk/middleware-recursion-detection": "3.734.0", - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/region-config-resolver": "3.734.0", - "@aws-sdk/types": "3.734.0", - "@aws-sdk/util-endpoints": "3.743.0", - "@aws-sdk/util-user-agent-browser": "3.734.0", - "@aws-sdk/util-user-agent-node": "3.758.0", - "@smithy/config-resolver": "^4.0.1", - "@smithy/core": "^3.1.5", - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/hash-node": "^4.0.1", - "@smithy/invalid-dependency": "^4.0.1", - "@smithy/middleware-content-length": "^4.0.1", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-retry": "^4.0.7", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/protocol-http": "^5.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@aws-sdk/core": "3.775.0", + "@aws-sdk/middleware-host-header": "3.775.0", + "@aws-sdk/middleware-logger": "3.775.0", + "@aws-sdk/middleware-recursion-detection": "3.775.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/region-config-resolver": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@aws-sdk/util-endpoints": "3.775.0", + "@aws-sdk/util-user-agent-browser": "3.775.0", + "@aws-sdk/util-user-agent-node": "3.775.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/core": "^3.2.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/hash-node": "^4.0.2", + "@smithy/invalid-dependency": "^4.0.2", + "@smithy/middleware-content-length": "^4.0.2", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-retry": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/protocol-http": "^5.1.0", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.7", - "@smithy/util-defaults-mode-node": "^4.0.7", - "@smithy/util-endpoints": "^3.0.1", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/util-defaults-mode-browser": "^4.0.8", + "@smithy/util-defaults-mode-node": "^4.0.8", + "@smithy/util-endpoints": "^3.0.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -792,15 +796,15 @@ } }, "node_modules/@aws-sdk/region-config-resolver": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.734.0.tgz", - "integrity": "sha512-Lvj1kPRC5IuJBr9DyJ9T9/plkh+EfKLy+12s/mykOy1JaKHDpvj+XGy2YO6YgYVOb8JFtaqloid+5COtje4JTQ==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.775.0.tgz", + "integrity": "sha512-40iH3LJjrQS3LKUJAl7Wj0bln7RFPEvUYKFxtP8a+oKFDO0F65F52xZxIJbPn6sHkxWDAnZlGgdjZXM3p2g5wQ==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -808,15 +812,15 @@ } }, "node_modules/@aws-sdk/token-providers": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.758.0.tgz", - "integrity": "sha512-ckptN1tNrIfQUaGWm/ayW1ddG+imbKN7HHhjFdS4VfItsP0QQOB0+Ov+tpgb4MoNR4JaUghMIVStjIeHN2ks1w==", + "version": "3.777.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.777.0.tgz", + "integrity": "sha512-Yc2cDONsHOa4dTSGOev6Ng2QgTKQUEjaUnsyKd13pc/nLLz/WLqHiQ/o7PcnKERJxXGs1g1C6l3sNXiX+kbnFQ==", "dependencies": { - "@aws-sdk/nested-clients": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/nested-clients": "3.777.0", + "@aws-sdk/types": "3.775.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -824,11 +828,11 @@ } }, "node_modules/@aws-sdk/types": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.734.0.tgz", - "integrity": "sha512-o11tSPTT70nAkGV1fN9wm/hAIiLPyWX6SuGf+9JyTp7S/rC2cFWhR26MvA69nplcjNaXVzB0f+QFrLXXjOqCrg==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.775.0.tgz", + "integrity": "sha512-ZoGKwa4C9fC9Av6bdfqcW6Ix5ot05F/S4VxWR2nHuMv7hzfmAjTOcUiWT7UR4hM/U0whf84VhDtXN/DWAk52KA==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -836,13 +840,13 @@ } }, "node_modules/@aws-sdk/util-endpoints": { - "version": "3.743.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.743.0.tgz", - "integrity": "sha512-sN1l559zrixeh5x+pttrnd0A3+r34r0tmPkJ/eaaMaAzXqsmKU/xYre9K3FNnsSS1J1k4PEfk/nHDTVUgFYjnw==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.775.0.tgz", + "integrity": "sha512-yjWmUgZC9tUxAo8Uaplqmq0eUh0zrbZJdwxGRKdYxfm4RG6fMw1tj52+KkatH7o+mNZvg1GDcVp/INktxonJLw==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", - "@smithy/util-endpoints": "^3.0.1", + "@aws-sdk/types": "3.775.0", + "@smithy/types": "^4.2.0", + "@smithy/util-endpoints": "^3.0.2", "tslib": "^2.6.2" }, "engines": { @@ -861,25 +865,25 @@ } }, "node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.734.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.734.0.tgz", - "integrity": "sha512-xQTCus6Q9LwUuALW+S76OL0jcWtMOVu14q+GoLnWPUM7QeUw963oQcLhF7oq0CtaLLKyl4GOUfcwc773Zmwwng==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.775.0.tgz", + "integrity": "sha512-txw2wkiJmZKVdDbscK7VBK+u+TJnRtlUjRTLei+elZg2ADhpQxfVAQl436FUeIv6AhB/oRHW6/K/EAGXUSWi0A==", "dependencies": { - "@aws-sdk/types": "3.734.0", - "@smithy/types": "^4.1.0", + "@aws-sdk/types": "3.775.0", + "@smithy/types": "^4.2.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.758.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.758.0.tgz", - "integrity": "sha512-A5EZw85V6WhoKMV2hbuFRvb9NPlxEErb4HPO6/SPXYY4QrjprIzScHxikqcWv1w4J3apB1wto9LPU3IMsYtfrw==", + "version": "3.775.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.775.0.tgz", + "integrity": "sha512-N9yhTevbizTOMo3drH7Eoy6OkJ3iVPxhV7dwb6CMAObbLneS36CSfA6xQXupmHWcRvZPTz8rd1JGG3HzFOau+g==", "dependencies": { - "@aws-sdk/middleware-user-agent": "3.758.0", - "@aws-sdk/types": "3.734.0", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@aws-sdk/middleware-user-agent": "3.775.0", + "@aws-sdk/types": "3.775.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -2973,9 +2977,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.63", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.63.tgz", - "integrity": "sha512-KBfyOUU/mWOXeNf6v+4IfMkbvfEEe/YP6n/g/reJBhrpApchG2A/P11JviH87N2To1SrhZxnW//0g5FIGupDFw==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", + "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -2995,9 +2999,9 @@ } }, "node_modules/@continuedev/llm-info": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.7.tgz", - "integrity": "sha512-MyYmP4tbTzOnlT6hItC9tFkVZpYkaAg45AUXqdXzEfZhz8ZWpaiN8jZ789KLVmq+NKqhMUbKAHIZUUY1d39eRw==" + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.8.tgz", + "integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw==" }, "node_modules/@continuedev/openai-adapters": { "version": "1.0.18", @@ -4532,11 +4536,11 @@ } }, "node_modules/@smithy/abort-controller": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.0.1.tgz", - "integrity": "sha512-fiUIYgIgRjMWznk6iLJz35K2YxSLHzLBA/RC6lBrKfQ8fHbPfvk7Pk9UvpKoHgJjI18MnbPuEju53zcVy6KF1g==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.0.2.tgz", + "integrity": "sha512-Sl/78VDtgqKxN2+1qduaVE140XF+Xg+TafkncspwM4jFP/LHr76ZHmIY/y3V1M0mMLNk+Je6IGbzxy23RSToMw==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4544,14 +4548,14 @@ } }, "node_modules/@smithy/config-resolver": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.0.1.tgz", - "integrity": "sha512-Igfg8lKu3dRVkTSEm98QpZUvKEOa71jDX4vKRcvJVyRc3UgN3j7vFMf0s7xLQhYmKa8kyJGQgUJDOV5V3neVlQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.1.0.tgz", + "integrity": "sha512-8smPlwhga22pwl23fM5ew4T9vfLUCeFXlcqNOCD5M5h8VmNPNUE9j6bQSuRXpDSV11L/E/SwEBQuW8hr6+nS1A==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -4559,16 +4563,16 @@ } }, "node_modules/@smithy/core": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.1.5.tgz", - "integrity": "sha512-HLclGWPkCsekQgsyzxLhCQLa8THWXtB5PxyYN+2O6nkyLt550KQKTlbV2D1/j5dNIQapAZM1+qFnpBFxZQkgCA==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.2.0.tgz", + "integrity": "sha512-k17bgQhVZ7YmUvA8at4af1TDpl0NDMBuBKJl8Yg0nrefwmValU+CnA5l/AriVdQNthU/33H3nK71HrLgqOPr1Q==", "dependencies": { - "@smithy/middleware-serde": "^4.0.2", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-stream": "^4.1.2", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-stream": "^4.2.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -4577,14 +4581,14 @@ } }, "node_modules/@smithy/credential-provider-imds": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.0.1.tgz", - "integrity": "sha512-l/qdInaDq1Zpznpmev/+52QomsJNZ3JkTl5yrTl02V6NBgJOQ4LY0SFw/8zsMwj3tLe8vqiIuwF6nxaEwgf6mg==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.0.2.tgz", + "integrity": "sha512-32lVig6jCaWBHnY+OEQ6e6Vnt5vDHaLiydGrwYMW9tPqO688hPGTYRamYJ1EptxEC2rAwJrHWmPoKRBl4iTa8w==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -4592,12 +4596,12 @@ } }, "node_modules/@smithy/eventstream-codec": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-4.0.1.tgz", - "integrity": "sha512-Q2bCAAR6zXNVtJgifsU16ZjKGqdw/DyecKNgIgi7dlqw04fqDu0mnq+JmGphqheypVc64CYq3azSuCpAdFk2+A==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-4.0.2.tgz", + "integrity": "sha512-p+f2kLSK7ZrXVfskU/f5dzksKTewZk8pJLPvER3aFHPt76C2MxD9vNatSfLzzQSQB4FNO96RK4PSXfhD1TTeMQ==", "dependencies": { "@aws-crypto/crc32": "5.2.0", - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-hex-encoding": "^4.0.0", "tslib": "^2.6.2" }, @@ -4606,12 +4610,12 @@ } }, "node_modules/@smithy/eventstream-serde-browser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.0.1.tgz", - "integrity": "sha512-HbIybmz5rhNg+zxKiyVAnvdM3vkzjE6ccrJ620iPL8IXcJEntd3hnBl+ktMwIy12Te/kyrSbUb8UCdnUT4QEdA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.0.2.tgz", + "integrity": "sha512-CepZCDs2xgVUtH7ZZ7oDdZFH8e6Y2zOv8iiX6RhndH69nlojCALSKK+OXwZUgOtUZEUaZ5e1hULVCHYbCn7pug==", "dependencies": { - "@smithy/eventstream-serde-universal": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/eventstream-serde-universal": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4619,11 +4623,11 @@ } }, "node_modules/@smithy/eventstream-serde-config-resolver": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.0.1.tgz", - "integrity": "sha512-lSipaiq3rmHguHa3QFF4YcCM3VJOrY9oq2sow3qlhFY+nBSTF/nrO82MUQRPrxHQXA58J5G1UnU2WuJfi465BA==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.1.0.tgz", + "integrity": "sha512-1PI+WPZ5TWXrfj3CIoKyUycYynYJgZjuQo8U+sphneOtjsgrttYybdqESFReQrdWJ+LKt6NEdbYzmmfDBmjX2A==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4631,12 +4635,12 @@ } }, "node_modules/@smithy/eventstream-serde-node": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.0.1.tgz", - "integrity": "sha512-o4CoOI6oYGYJ4zXo34U8X9szDe3oGjmHgsMGiZM0j4vtNoT+h80TLnkUcrLZR3+E6HIxqW+G+9WHAVfl0GXK0Q==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.0.2.tgz", + "integrity": "sha512-C5bJ/C6x9ENPMx2cFOirspnF9ZsBVnBMtP6BdPl/qYSuUawdGQ34Lq0dMcf42QTjUZgWGbUIZnz6+zLxJlb9aw==", "dependencies": { - "@smithy/eventstream-serde-universal": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/eventstream-serde-universal": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4644,12 +4648,12 @@ } }, "node_modules/@smithy/eventstream-serde-universal": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-4.0.1.tgz", - "integrity": "sha512-Z94uZp0tGJuxds3iEAZBqGU2QiaBHP4YytLUjwZWx+oUeohCsLyUm33yp4MMBmhkuPqSbQCXq5hDet6JGUgHWA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-4.0.2.tgz", + "integrity": "sha512-St8h9JqzvnbB52FtckiHPN4U/cnXcarMniXRXTKn0r4b4XesZOGiAyUdj1aXbqqn1icSqBlzzUsCl6nPB018ng==", "dependencies": { - "@smithy/eventstream-codec": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/eventstream-codec": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4657,13 +4661,13 @@ } }, "node_modules/@smithy/fetch-http-handler": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.0.1.tgz", - "integrity": "sha512-3aS+fP28urrMW2KTjb6z9iFow6jO8n3MFfineGbndvzGZit3taZhKWtTorf+Gp5RpFDDafeHlhfsGlDCXvUnJA==", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.0.2.tgz", + "integrity": "sha512-+9Dz8sakS9pe7f2cBocpJXdeVjMopUDLgZs1yWeu7h++WqSbjUYv/JAJwKwXw1HV6gq1jyWjxuyn24E2GhoEcQ==", "dependencies": { - "@smithy/protocol-http": "^5.0.1", - "@smithy/querystring-builder": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/querystring-builder": "^4.0.2", + "@smithy/types": "^4.2.0", "@smithy/util-base64": "^4.0.0", "tslib": "^2.6.2" }, @@ -4672,11 +4676,11 @@ } }, "node_modules/@smithy/hash-node": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.0.1.tgz", - "integrity": "sha512-TJ6oZS+3r2Xu4emVse1YPB3Dq3d8RkZDKcPr71Nj/lJsdAP1c7oFzYqEn1IBc915TsgLl2xIJNuxCz+gLbLE0w==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.0.2.tgz", + "integrity": "sha512-VnTpYPnRUE7yVhWozFdlxcYknv9UN7CeOqSrMH+V877v4oqtVYuoqhIhtSjmGPvYrYnAkaM61sLMKHvxL138yg==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-buffer-from": "^4.0.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" @@ -4686,11 +4690,11 @@ } }, "node_modules/@smithy/invalid-dependency": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.0.1.tgz", - "integrity": "sha512-gdudFPf4QRQ5pzj7HEnu6FhKRi61BfH/Gk5Yf6O0KiSbr1LlVhgjThcvjdu658VE6Nve8vaIWB8/fodmS1rBPQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.0.2.tgz", + "integrity": "sha512-GatB4+2DTpgWPday+mnUkoumP54u/MDM/5u44KF9hIu8jF0uafZtQLcdfIKkIcUNuF/fBojpLEHZS/56JqPeXQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4709,12 +4713,12 @@ } }, "node_modules/@smithy/middleware-content-length": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.0.1.tgz", - "integrity": "sha512-OGXo7w5EkB5pPiac7KNzVtfCW2vKBTZNuCctn++TTSOMpe6RZO/n6WEC1AxJINn3+vWLKW49uad3lo/u0WJ9oQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.0.2.tgz", + "integrity": "sha512-hAfEXm1zU+ELvucxqQ7I8SszwQ4znWMbNv6PLMndN83JJN41EPuS93AIyh2N+gJ6x8QFhzSO6b7q2e6oClDI8A==", "dependencies": { - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4722,17 +4726,17 @@ } }, "node_modules/@smithy/middleware-endpoint": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.0.6.tgz", - "integrity": "sha512-ftpmkTHIFqgaFugcjzLZv3kzPEFsBFSnq1JsIkr2mwFzCraZVhQk2gqN51OOeRxqhbPTkRFj39Qd2V91E/mQxg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.1.0.tgz", + "integrity": "sha512-xhLimgNCbCzsUppRTGXWkZywksuTThxaIB0HwbpsVLY5sceac4e1TZ/WKYqufQLaUy+gUSJGNdwD2jo3cXL0iA==", "dependencies": { - "@smithy/core": "^3.1.5", - "@smithy/middleware-serde": "^4.0.2", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", - "@smithy/url-parser": "^4.0.1", - "@smithy/util-middleware": "^4.0.1", + "@smithy/core": "^3.2.0", + "@smithy/middleware-serde": "^4.0.3", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", + "@smithy/url-parser": "^4.0.2", + "@smithy/util-middleware": "^4.0.2", "tslib": "^2.6.2" }, "engines": { @@ -4740,17 +4744,17 @@ } }, "node_modules/@smithy/middleware-retry": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.0.7.tgz", - "integrity": "sha512-58j9XbUPLkqAcV1kHzVX/kAR16GT+j7DUZJqwzsxh1jtz7G82caZiGyyFgUvogVfNTg3TeAOIJepGc8TXF4AVQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.1.0.tgz", + "integrity": "sha512-2zAagd1s6hAaI/ap6SXi5T3dDwBOczOMCSkkYzktqN1+tzbk1GAsHNAdo/1uzxz3Ky02jvZQwbi/vmDA6z4Oyg==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/service-error-classification": "^4.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", - "@smithy/util-middleware": "^4.0.1", - "@smithy/util-retry": "^4.0.1", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/service-error-classification": "^4.0.2", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", + "@smithy/util-middleware": "^4.0.2", + "@smithy/util-retry": "^4.0.2", "tslib": "^2.6.2", "uuid": "^9.0.1" }, @@ -4759,11 +4763,11 @@ } }, "node_modules/@smithy/middleware-serde": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.0.2.tgz", - "integrity": "sha512-Sdr5lOagCn5tt+zKsaW+U2/iwr6bI9p08wOkCp6/eL6iMbgdtc2R5Ety66rf87PeohR0ExI84Txz9GYv5ou3iQ==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.0.3.tgz", + "integrity": "sha512-rfgDVrgLEVMmMn0BI8O+8OVr6vXzjV7HZj57l0QxslhzbvVfikZbVfBVthjLHqib4BW44QhcIgJpvebHlRaC9A==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4771,11 +4775,11 @@ } }, "node_modules/@smithy/middleware-stack": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.0.1.tgz", - "integrity": "sha512-dHwDmrtR/ln8UTHpaIavRSzeIk5+YZTBtLnKwDW3G2t6nAupCiQUvNzNoHBpik63fwUaJPtlnMzXbQrNFWssIA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.0.2.tgz", + "integrity": "sha512-eSPVcuJJGVYrFYu2hEq8g8WWdJav3sdrI4o2c6z/rjnYDd3xH9j9E7deZQCzFn4QvGPouLngH3dQ+QVTxv5bOQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4783,13 +4787,13 @@ } }, "node_modules/@smithy/node-config-provider": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.0.1.tgz", - "integrity": "sha512-8mRTjvCtVET8+rxvmzRNRR0hH2JjV0DFOmwXPrISmTIJEfnCBugpYYGAsCj8t41qd+RB5gbheSQ/6aKZCQvFLQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.0.2.tgz", + "integrity": "sha512-WgCkILRZfJwJ4Da92a6t3ozN/zcvYyJGUTmfGbgS/FkCcoCjl7G4FJaCDN1ySdvLvemnQeo25FdkyMSTSwulsw==", "dependencies": { - "@smithy/property-provider": "^4.0.1", - "@smithy/shared-ini-file-loader": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/shared-ini-file-loader": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4797,14 +4801,14 @@ } }, "node_modules/@smithy/node-http-handler": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.0.3.tgz", - "integrity": "sha512-dYCLeINNbYdvmMLtW0VdhW1biXt+PPCGazzT5ZjKw46mOtdgToQEwjqZSS9/EN8+tNs/RO0cEWG044+YZs97aA==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.0.4.tgz", + "integrity": "sha512-/mdqabuAT3o/ihBGjL94PUbTSPSRJ0eeVTdgADzow0wRJ0rN4A27EOrtlK56MYiO1fDvlO3jVTCxQtQmK9dZ1g==", "dependencies": { - "@smithy/abort-controller": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/querystring-builder": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/abort-controller": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/querystring-builder": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4812,11 +4816,11 @@ } }, "node_modules/@smithy/property-provider": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.0.1.tgz", - "integrity": "sha512-o+VRiwC2cgmk/WFV0jaETGOtX16VNPp2bSQEzu0whbReqE1BMqsP2ami2Vi3cbGVdKu1kq9gQkDAGKbt0WOHAQ==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.0.2.tgz", + "integrity": "sha512-wNRoQC1uISOuNc2s4hkOYwYllmiyrvVXWMtq+TysNRVQaHm4yoafYQyjN/goYZS+QbYlPIbb/QRjaUZMuzwQ7A==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4824,11 +4828,11 @@ } }, "node_modules/@smithy/protocol-http": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.0.1.tgz", - "integrity": "sha512-TE4cpj49jJNB/oHyh/cRVEgNZaoPaxd4vteJNB0yGidOCVR0jCw/hjPVsT8Q8FRmj8Bd3bFZt8Dh7xGCT+xMBQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.1.0.tgz", + "integrity": "sha512-KxAOL1nUNw2JTYrtviRRjEnykIDhxc84qMBzxvu1MUfQfHTuBlCG7PA6EdVwqpJjH7glw7FqQoFxUJSyBQgu7g==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4836,11 +4840,11 @@ } }, "node_modules/@smithy/querystring-builder": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.0.1.tgz", - "integrity": "sha512-wU87iWZoCbcqrwszsOewEIuq+SU2mSoBE2CcsLwE0I19m0B2gOJr1MVjxWcDQYOzHbR1xCk7AcOBbGFUYOKvdg==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.0.2.tgz", + "integrity": "sha512-NTOs0FwHw1vimmQM4ebh+wFQvOwkEf/kQL6bSM1Lock+Bv4I89B3hGYoUEPkmvYPkDKyp5UdXJYu+PoTQ3T31Q==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-uri-escape": "^4.0.0", "tslib": "^2.6.2" }, @@ -4849,11 +4853,11 @@ } }, "node_modules/@smithy/querystring-parser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.0.1.tgz", - "integrity": "sha512-Ma2XC7VS9aV77+clSFylVUnPZRindhB7BbmYiNOdr+CHt/kZNJoPP0cd3QxCnCFyPXC4eybmyE98phEHkqZ5Jw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.0.2.tgz", + "integrity": "sha512-v6w8wnmZcVXjfVLjxw8qF7OwESD9wnpjp0Dqry/Pod0/5vcEA3qxCr+BhbOHlxS8O+29eLpT3aagxXGwIoEk7Q==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4861,22 +4865,22 @@ } }, "node_modules/@smithy/service-error-classification": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.0.1.tgz", - "integrity": "sha512-3JNjBfOWpj/mYfjXJHB4Txc/7E4LVq32bwzE7m28GN79+M1f76XHflUaSUkhOriprPDzev9cX/M+dEB80DNDKA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.0.2.tgz", + "integrity": "sha512-LA86xeFpTKn270Hbkixqs5n73S+LVM0/VZco8dqd+JT75Dyx3Lcw/MraL7ybjmz786+160K8rPOmhsq0SocoJQ==", "dependencies": { - "@smithy/types": "^4.1.0" + "@smithy/types": "^4.2.0" }, "engines": { "node": ">=18.0.0" } }, "node_modules/@smithy/shared-ini-file-loader": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.0.1.tgz", - "integrity": "sha512-hC8F6qTBbuHRI/uqDgqqi6J0R4GtEZcgrZPhFQnMhfJs3MnUTGSnR1NSJCJs5VWlMydu0kJz15M640fJlRsIOw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.0.2.tgz", + "integrity": "sha512-J9/gTWBGVuFZ01oVA6vdb4DAjf1XbDhK6sLsu3OS9qmLrS6KB5ygpeHiM3miIbj1qgSJ96GYszXFWv6ErJ8QEw==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4884,15 +4888,15 @@ } }, "node_modules/@smithy/signature-v4": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.0.1.tgz", - "integrity": "sha512-nCe6fQ+ppm1bQuw5iKoeJ0MJfz2os7Ic3GBjOkLOPtavbD1ONoyE3ygjBfz2ythFWm4YnRm6OxW+8p/m9uCoIA==", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.0.2.tgz", + "integrity": "sha512-Mz+mc7okA73Lyz8zQKJNyr7lIcHLiPYp0+oiqiMNc/t7/Kf2BENs5d63pEj7oPqdjaum6g0Fc8wC78dY1TgtXw==", "dependencies": { "@smithy/is-array-buffer": "^4.0.0", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", "@smithy/util-hex-encoding": "^4.0.0", - "@smithy/util-middleware": "^4.0.1", + "@smithy/util-middleware": "^4.0.2", "@smithy/util-uri-escape": "^4.0.0", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" @@ -4902,16 +4906,16 @@ } }, "node_modules/@smithy/smithy-client": { - "version": "4.1.6", - "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.1.6.tgz", - "integrity": "sha512-UYDolNg6h2O0L+cJjtgSyKKvEKCOa/8FHYJnBobyeoeWDmNpXjwOAtw16ezyeu1ETuuLEOZbrynK0ZY1Lx9Jbw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.2.0.tgz", + "integrity": "sha512-Qs65/w30pWV7LSFAez9DKy0Koaoh3iHhpcpCCJ4waj/iqwsuSzJna2+vYwq46yBaqO5ZbP9TjUsATUNxrKeBdw==", "dependencies": { - "@smithy/core": "^3.1.5", - "@smithy/middleware-endpoint": "^4.0.6", - "@smithy/middleware-stack": "^4.0.1", - "@smithy/protocol-http": "^5.0.1", - "@smithy/types": "^4.1.0", - "@smithy/util-stream": "^4.1.2", + "@smithy/core": "^3.2.0", + "@smithy/middleware-endpoint": "^4.1.0", + "@smithy/middleware-stack": "^4.0.2", + "@smithy/protocol-http": "^5.1.0", + "@smithy/types": "^4.2.0", + "@smithy/util-stream": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -4919,9 +4923,9 @@ } }, "node_modules/@smithy/types": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.1.0.tgz", - "integrity": "sha512-enhjdwp4D7CXmwLtD6zbcDMbo6/T6WtuuKCY49Xxc6OMOmUWlBEBDREsxxgV2LIdeQPW756+f97GzcgAwp3iLw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.2.0.tgz", + "integrity": "sha512-7eMk09zQKCO+E/ivsjQv+fDlOupcFUCSC/L2YUPgwhvowVGWbPQHjEFcmjt7QQ4ra5lyowS92SV53Zc6XD4+fg==", "dependencies": { "tslib": "^2.6.2" }, @@ -4930,12 +4934,12 @@ } }, "node_modules/@smithy/url-parser": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.0.1.tgz", - "integrity": "sha512-gPXcIEUtw7VlK8f/QcruNXm7q+T5hhvGu9tl63LsJPZ27exB6dtNwvh2HIi0v7JcXJ5emBxB+CJxwaLEdJfA+g==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.0.2.tgz", + "integrity": "sha512-Bm8n3j2ScqnT+kJaClSVCMeiSenK6jVAzZCNewsYWuZtnBehEz4r2qP0riZySZVfzB+03XZHJeqfmJDkeeSLiQ==", "dependencies": { - "@smithy/querystring-parser": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/querystring-parser": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5001,13 +5005,13 @@ } }, "node_modules/@smithy/util-defaults-mode-browser": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.0.7.tgz", - "integrity": "sha512-CZgDDrYHLv0RUElOsmZtAnp1pIjwDVCSuZWOPhIOBvG36RDfX1Q9+6lS61xBf+qqvHoqRjHxgINeQz47cYFC2Q==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.0.8.tgz", + "integrity": "sha512-ZTypzBra+lI/LfTYZeop9UjoJhhGRTg3pxrNpfSTQLd3AJ37r2z4AXTKpq1rFXiiUIJsYyFgNJdjWRGP/cbBaQ==", "dependencies": { - "@smithy/property-provider": "^4.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", + "@smithy/property-provider": "^4.0.2", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", "bowser": "^2.11.0", "tslib": "^2.6.2" }, @@ -5016,16 +5020,16 @@ } }, "node_modules/@smithy/util-defaults-mode-node": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.0.7.tgz", - "integrity": "sha512-79fQW3hnfCdrfIi1soPbK3zmooRFnLpSx3Vxi6nUlqaaQeC5dm8plt4OTNDNqEEEDkvKghZSaoti684dQFVrGQ==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.0.8.tgz", + "integrity": "sha512-Rgk0Jc/UDfRTzVthye/k2dDsz5Xxs9LZaKCNPgJTRyoyBoeiNCnHsYGOyu1PKN+sDyPnJzMOz22JbwxzBp9NNA==", "dependencies": { - "@smithy/config-resolver": "^4.0.1", - "@smithy/credential-provider-imds": "^4.0.1", - "@smithy/node-config-provider": "^4.0.1", - "@smithy/property-provider": "^4.0.1", - "@smithy/smithy-client": "^4.1.6", - "@smithy/types": "^4.1.0", + "@smithy/config-resolver": "^4.1.0", + "@smithy/credential-provider-imds": "^4.0.2", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/property-provider": "^4.0.2", + "@smithy/smithy-client": "^4.2.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5033,12 +5037,12 @@ } }, "node_modules/@smithy/util-endpoints": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.0.1.tgz", - "integrity": "sha512-zVdUENQpdtn9jbpD9SCFK4+aSiavRb9BxEtw9ZGUR1TYo6bBHbIoi7VkrFQ0/RwZlzx0wRBaRmPclj8iAoJCLA==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.0.2.tgz", + "integrity": "sha512-6QSutU5ZyrpNbnd51zRTL7goojlcnuOB55+F9VBD+j8JpRY50IGamsjlycrmpn8PQkmJucFW8A0LSfXj7jjtLQ==", "dependencies": { - "@smithy/node-config-provider": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/node-config-provider": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5057,11 +5061,11 @@ } }, "node_modules/@smithy/util-middleware": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.0.1.tgz", - "integrity": "sha512-HiLAvlcqhbzhuiOa0Lyct5IIlyIz0PQO5dnMlmQ/ubYM46dPInB+3yQGkfxsk6Q24Y0n3/JmcA1v5iEhmOF5mA==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.0.2.tgz", + "integrity": "sha512-6GDamTGLuBQVAEuQ4yDQ+ti/YINf/MEmIegrEeg7DdB/sld8BX1lqt9RRuIcABOhAGTA50bRbPzErez7SlDtDQ==", "dependencies": { - "@smithy/types": "^4.1.0", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5069,12 +5073,12 @@ } }, "node_modules/@smithy/util-retry": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.0.1.tgz", - "integrity": "sha512-WmRHqNVwn3kI3rKk1LsKcVgPBG6iLTBGC1iYOV3GQegwJ3E8yjzHytPt26VNzOWr1qu0xE03nK0Ug8S7T7oufw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.0.2.tgz", + "integrity": "sha512-Qryc+QG+7BCpvjloFLQrmlSd0RsVRHejRXd78jNO3+oREueCjwG1CCEH1vduw/ZkM1U9TztwIKVIi3+8MJScGg==", "dependencies": { - "@smithy/service-error-classification": "^4.0.1", - "@smithy/types": "^4.1.0", + "@smithy/service-error-classification": "^4.0.2", + "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "engines": { @@ -5082,13 +5086,13 @@ } }, "node_modules/@smithy/util-stream": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.1.2.tgz", - "integrity": "sha512-44PKEqQ303d3rlQuiDpcCcu//hV8sn+u2JBo84dWCE0rvgeiVl0IlLMagbU++o0jCWhYCsHaAt9wZuZqNe05Hw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.2.0.tgz", + "integrity": "sha512-Vj1TtwWnuWqdgQI6YTUF5hQ/0jmFiOYsc51CSMgj7QfyO+RF4EnT2HNjoviNlOOmgzgvf3f5yno+EiC4vrnaWQ==", "dependencies": { - "@smithy/fetch-http-handler": "^5.0.1", - "@smithy/node-http-handler": "^4.0.3", - "@smithy/types": "^4.1.0", + "@smithy/fetch-http-handler": "^5.0.2", + "@smithy/node-http-handler": "^4.0.4", + "@smithy/types": "^4.2.0", "@smithy/util-base64": "^4.0.0", "@smithy/util-buffer-from": "^4.0.0", "@smithy/util-hex-encoding": "^4.0.0", @@ -8584,6 +8588,11 @@ "node": ">=8" } }, + "node_modules/filtrex": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/filtrex/-/filtrex-3.1.0.tgz", + "integrity": "sha512-mHzZ2wUISETF1OaEcNRiGz1ljuIV8c/C9td9qyAZ+wTwigkAk5RO9YrCxQKk5H9v7joDRFIBik9U5RTK9eXZ/A==" + }, "node_modules/find-replace": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", @@ -15449,7 +15458,6 @@ "version": "5.7.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz", "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/core/package.json b/core/package.json index a60eda4ad..a405bad55 100644 --- a/core/package.json +++ b/core/package.json @@ -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", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index b9d4e88c8..fd0b48b2c 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -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, diff --git a/core/promptFiles/v1/updateChatHistory.ts b/core/promptFiles/v1/updateChatHistory.ts index 8ebc6f038..04cbcd91b 100644 --- a/core/promptFiles/v1/updateChatHistory.ts +++ b/core/promptFiles/v1/updateChatHistory.ts @@ -1,4 +1,4 @@ -export function updateChatHistory( +export function replaceSlashCommandWithPromptInChatHistory( history: any[], commandName: string, renderedPrompt: string, diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index 1f08011a8..4d52c7ba1 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -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[] = []; 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]; } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index d0d12e2ec..0213cd0e5 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -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; profileId: string | null; + organizations: SerializedOrgWithProfiles[]; + selectedOrgId: string; + usingContinueForTeams: boolean; }, ]; "config/deleteModel": [{ title: string }, void]; - "config/addContextProvider": [ContextProviderWithParams, void]; "config/reload": [undefined, ConfigResult]; - "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[]]; }; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 4dcf74ee5..2e1bd3ff1 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -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; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 5b2a7ab1f..1646d848e 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -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]; }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index a7cd16e5b..6aae337f0 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -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, ]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 4bb78e0ed..5d541225b 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -187,6 +187,10 @@ export class MessageIde implements IDE { return this.request("getSearchResults", { query }); } + getFileResults(pattern: string): Promise { + return this.request("getFileResults", { pattern }); + } + getProblems(fileUri: string): Promise { return this.request("getProblems", { filepath: fileUri }); } diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index 620055a75..8cd1cfbd6 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -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); }); diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 9fcbeda83..272a6d148 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -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", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 329f71bdc..6b59fa338 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -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; profileId: string | null; + organizations: SerializedOrgWithProfiles[]; + selectedOrgId: string | null; + usingContinueForTeams: boolean; }, void, ]; diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index ae54b03db..a394273e9 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -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), ); diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 268cbb9a8..7cff1c70e 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -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"; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 8d4b1f1b3..28a8f8c30 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -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); } diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index f932ae87b..46db25cb9 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -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: { diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts new file mode 100644 index 000000000..6ee5cee6b --- /dev/null +++ b/core/tools/definitions/editFile.ts @@ -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", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts new file mode 100644 index 000000000..bff2d454c --- /dev/null +++ b/core/tools/definitions/globSearch.ts @@ -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", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/grepSearch.ts similarity index 63% rename from core/tools/definitions/exactSearch.ts rename to core/tools/definitions/grepSearch.ts index 400adbd9e..42ea92e64 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -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"], diff --git a/core/tools/definitions/lsTool.ts b/core/tools/definitions/lsTool.ts new file mode 100644 index 000000000..6b6e96498 --- /dev/null +++ b/core/tools/definitions/lsTool.ts @@ -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", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 75a0e8169..eacaab70d 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -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: { diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 53d381e62..ff5d58a31 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -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: { diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index 2b7882167..e7f48ea32 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -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: { diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index 7e2724a7c..0f98f382c 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -6,6 +6,8 @@ export const searchWebTool: Tool = { type: "function", displayTitle: "Search Web", wouldLikeTo: 'search the web for "{{{ query }}}"', + isCurrently: 'searching the web for "{{{ query }}}"', + hasAlready: 'searched the web fore "{{{ query }}}"', readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index 3da0c71a9..e7ce716a8 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -5,7 +5,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const viewDiffTool: Tool = { type: "function", displayTitle: "View Diff", - wouldLikeTo: "view a diff", + wouldLikeTo: "view the git diff", + isCurrently: "getting the git diff", + hasAlready: "viewed the git diff", readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index 60d671177..21c8050a6 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -6,6 +6,8 @@ export const viewRepoMapTool: Tool = { type: "function", displayTitle: "View Repo Map", wouldLikeTo: "view the repository map", + isCurrently: "getting the repository map", + hasAlready: "viewed the repository map", readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index b78daba76..2f9093c54 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -4,7 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const viewSubdirectoryTool: Tool = { type: "function", displayTitle: "View Subdirectory", - wouldLikeTo: 'view the contents of "{{{ directory_path }}}"', + wouldLikeTo: 'view a map of "{{{ directory_path }}}"', + isCurrently: 'getting a map of "{{{ directory_path }}}"', + hasAlready: 'viewed a map of "{{{ directory_path }}}"', readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index b5d5e6c1b..5a89141eb 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -1,6 +1,7 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils"; import { ToolImpl } from "."; +import { getCleanUriPath, getUriPathBasename } from "../../util/uri"; export const createNewFileImpl: ToolImpl = async (args, extras) => { const resolvedFileUri = await inferResolvedUriFromRelativePath( @@ -8,8 +9,26 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { extras.ide, ); if (resolvedFileUri) { + const exists = await extras.ide.fileExists(resolvedFileUri); + if (exists) { + throw new Error( + `File ${args.filepath} already exists. Use the edit tool to edit this file`, + ); + } await extras.ide.writeFile(resolvedFileUri, args.contents); await extras.ide.openFile(resolvedFileUri); + return [ + { + name: getUriPathBasename(resolvedFileUri), + description: getCleanUriPath(resolvedFileUri), + content: "File created successfuly", + uri: { + type: "file", + value: resolvedFileUri, + }, + }, + ]; + } else { + throw new Error("Failed to resolve path"); } - return []; }; diff --git a/core/tools/implementations/exactSearch.ts b/core/tools/implementations/exactSearch.ts deleted file mode 100644 index ae8f6fd02..000000000 --- a/core/tools/implementations/exactSearch.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ToolImpl } from "."; - -export const exactSearchImpl: ToolImpl = async (args, extras) => { - const content = await extras.ide.getSearchResults(args.query); - return [ - { - name: "Search results", - description: "Results from exact search", - content, - }, - ]; -}; diff --git a/core/tools/implementations/globSearch.ts b/core/tools/implementations/globSearch.ts new file mode 100644 index 000000000..c0b214357 --- /dev/null +++ b/core/tools/implementations/globSearch.ts @@ -0,0 +1,12 @@ +import { ToolImpl } from "."; + +export const fileGlobSearchImpl: ToolImpl = async (args, extras) => { + const results = await extras.ide.getFileResults(args.pattern); + return [ + { + name: "File results", + description: "Results from file glob search", + content: results.join("\n"), + }, + ]; +}; diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts new file mode 100644 index 000000000..a506be9cd --- /dev/null +++ b/core/tools/implementations/grepSearch.ts @@ -0,0 +1,13 @@ +import { ToolImpl } from "."; +import { formatGrepSearchResults } from "../../util/grepSearch"; + +export const grepSearchImpl: ToolImpl = async (args, extras) => { + const results = await extras.ide.getSearchResults(args.query); + return [ + { + name: "Search results", + description: "Results from grep search", + content: formatGrepSearchResults(results), + }, + ]; +}; diff --git a/core/tools/implementations/lsTool.ts b/core/tools/implementations/lsTool.ts new file mode 100644 index 000000000..4a7f8bcb5 --- /dev/null +++ b/core/tools/implementations/lsTool.ts @@ -0,0 +1,31 @@ +import { ToolImpl } from "."; +import { walkDir } from "../../indexing/walkDir"; +import { resolveRelativePathInDir } from "../../util/ideUtils"; + +export const lsToolImpl: ToolImpl = async (args, extras) => { + const uri = await resolveRelativePathInDir(args.dirPath, extras.ide); + if (!uri) { + throw new Error( + `Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`, + ); + } + + const entries = await walkDir(uri, extras.ide, { + returnRelativeUrisPaths: true, + include: "both", + recursive: args.recursive ?? false, + }); + + const content = + entries.length > 0 + ? entries.join("\n") + : `No files/folders found in ${args.dirPath}`; + + return [ + { + name: "File/folder list", + description: `Files/folders in ${args.dirPath}`, + content, + }, + ]; +}; diff --git a/core/tools/index.ts b/core/tools/index.ts index c27860a6f..c9875c5eb 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,21 +1,28 @@ import { createNewFileTool } from "./definitions/createNewFile"; -import { exactSearchTool } from "./definitions/exactSearch"; +import { editFileTool } from "./definitions/editFile"; +import { globSearchTool } from "./definitions/globSearch"; +import { grepSearchTool } from "./definitions/grepSearch"; +import { lsTool } from "./definitions/lsTool"; import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile"; import { readFileTool } from "./definitions/readFile"; import { runTerminalCommandTool } from "./definitions/runTerminalCommand"; import { searchWebTool } from "./definitions/searchWeb"; import { viewDiffTool } from "./definitions/viewDiff"; -import { viewRepoMapTool } from "./definitions/viewRepoMap"; -import { viewSubdirectoryTool } from "./definitions/viewSubdirectory"; export const allTools = [ readFileTool, + editFileTool, createNewFileTool, runTerminalCommandTool, - viewSubdirectoryTool, - viewRepoMapTool, - exactSearchTool, + + grepSearchTool, + globSearchTool, searchWebTool, viewDiffTool, readCurrentlyOpenFileTool, + + lsTool, + // replacing with ls tool for now + // viewSubdirectoryTool, + // viewRepoMapTool, ]; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 3c6963071..c59eb3320 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -238,6 +238,10 @@ class FileSystemIde implements IDE { return ""; } + async getFileResults(pattern: string): Promise { + return []; + } + async getProblems(fileUri?: string | undefined): Promise { return Promise.resolve([]); } diff --git a/core/util/grepSearch.ts b/core/util/grepSearch.ts new file mode 100644 index 000000000..a30982e77 --- /dev/null +++ b/core/util/grepSearch.ts @@ -0,0 +1,61 @@ +export function formatGrepSearchResults(results: string): string { + const keepLines: string[] = []; + + function countLeadingSpaces(line: string) { + return line?.match(/^ */)?.[0].length ?? 0; + } + + const processResult = (lines: string[]) => { + // Skip results in which only the file path was kept + const resultPath = lines[0]; + const resultContent = lines.slice(1); + if (resultContent.length === 0) { + return; + } + + // Add path + keepLines.push(resultPath); + + // Find the minimum indentation of content lines + let minIndent = Infinity; + for (const line of resultContent) { + const indent = countLeadingSpaces(line); + if (indent < minIndent) { + minIndent = indent; + } + } + + // Make all lines line up to 2-space indent + const changeIndentBy = 2 - minIndent; + if (changeIndentBy === 0) { + keepLines.push(...resultContent); + } else if (changeIndentBy < 0) { + keepLines.push( + ...resultContent.map((line) => line.substring(-changeIndentBy)), + ); + } else { + keepLines.push( + ...resultContent.map((line) => " ".repeat(changeIndentBy) + line), + ); + } + }; + + let resultLines: string[] = []; + for (const line of results.split("\n").filter((l) => !!l)) { + if (line.startsWith("./") || line === "--") { + processResult(resultLines); // process previous result + resultLines = [line]; + continue; + } + + // Exclude leading zero- or single-char lines + if (resultLines.length === 1 && line.trim().length <= 1) { + continue; + } + + resultLines.push(line); + } + processResult(resultLines); + + return keepLines.join("\n"); +} diff --git a/core/util/paths.ts b/core/util/paths.ts index 0fa64d109..a277d4977 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -1,8 +1,9 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; +import * as YAML from "yaml"; -import { DevEventName } from "@continuedev/config-yaml"; +import { ConfigYaml, DevEventName } from "@continuedev/config-yaml"; import * as JSONC from "comment-json"; import dotenv from "dotenv"; @@ -91,27 +92,20 @@ export function getSessionsListPath(): string { return filepath; } -export function getConfigJsonPath(ideType: IdeType = "vscode"): string { +export function getConfigJsonPath(): string { const p = path.join(getContinueGlobalPath(), "config.json"); - if (!fs.existsSync(p)) { - if (ideType === "jetbrains") { - fs.writeFileSync(p, JSON.stringify(defaultConfigJetBrains, null, 2)); - } else { - fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2)); - } - } return p; } export function getConfigYamlPath(ideType?: IdeType): string { const p = path.join(getContinueGlobalPath(), "config.yaml"); - // if (!fs.existsSync(p)) { - // if (ideType === "jetbrains") { - // fs.writeFileSync(p, YAML.stringify(defaultConfigYamlJetBrains)); - // } else { - // fs.writeFileSync(p, YAML.stringify(defaultConfigYaml)); - // } - // } + if (!fs.existsSync(p) && !fs.existsSync(getConfigJsonPath())) { + if (ideType === "jetbrains") { + fs.writeFileSync(p, YAML.stringify(defaultConfigJetBrains)); + } else { + fs.writeFileSync(p, YAML.stringify(defaultConfig)); + } + } return p; } @@ -234,7 +228,7 @@ export function getDevDataFilePath( return path.join(versionPath, `${String(eventName)}.jsonl`); } -export function editConfigJson( +function editConfigJson( callback: (config: SerializedContinueConfig) => SerializedContinueConfig, ): void { const config = fs.readFileSync(getConfigJsonPath(), "utf8"); @@ -248,6 +242,31 @@ export function editConfigJson( } } +function editConfigYaml(callback: (config: ConfigYaml) => ConfigYaml): void { + const config = fs.readFileSync(getConfigYamlPath(), "utf8"); + let configYaml = YAML.parse(config); + // Check if it's an object + if (typeof configYaml === "object" && configYaml !== null) { + configYaml = callback(configYaml as any) as any; + fs.writeFileSync(getConfigYamlPath(), YAML.stringify(configYaml)); + } else { + console.warn("config.yaml is not a valid object"); + } +} + +export function editConfigFile( + configJsonCallback: ( + config: SerializedContinueConfig, + ) => SerializedContinueConfig, + configYamlCallback: (config: ConfigYaml) => ConfigYaml, +): void { + if (fs.existsSync(getConfigYamlPath())) { + editConfigYaml(configYamlCallback); + } else if (fs.existsSync(getConfigJsonPath())) { + editConfigJson(configJsonCallback); + } +} + function getMigrationsFolderPath(): string { const migrationsPath = path.join(getContinueGlobalPath(), ".migrations"); if (!fs.existsSync(migrationsPath)) { diff --git a/docs/docs/actions/context-selection.md b/docs/docs/actions/context-selection.md deleted file mode 100644 index 90bc7c0d2..000000000 --- a/docs/docs/actions/context-selection.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Context selection -description: Actions \-context selection -keywords: [context, slash, debug, quick fix, right click] -sidebar_position: 3 ---- - -## Slash commands - -Slash commands can be combined with additional instructions, including [context providers](../customize/context-providers.mdx) or [highlighted code](../edit/context-selection#highlighted-code). - -## Quick actions - -Quick actions are always displayed above a class or function and will edit that class or function, but nothing outside of it. - -## Right click actions - -The highlighted code you’ve selected will be included in your prompt alongside a pre-written set of instructions depending on the selected action. This is the only section of code that the model will attempt to edit. - -## Debug action - -The debug action selects the most recently run terminal command and its output and then injects the following prompt into the chat window. There is no additional, non-visible information sent to the language model. - -``` -I got the following error, can you please help explain how to fix it? - -[ERROR_MESSAGE] -``` - -## Quick fixes - -Similarly to the debug action, quick actions transparently inject a prompt into the chat window. When you select “Ask Continue”, the 3 lines above and below the error are sent to the chat followed by the question “How do I fix the following problem in the above code?: [ERROR_MESSAGE]”. diff --git a/docs/docs/actions/how-it-works.mdx b/docs/docs/actions/how-it-works.mdx deleted file mode 100644 index afacc3dbe..000000000 --- a/docs/docs/actions/how-it-works.mdx +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: How it works -description: How Actions work -keywords: [how, slash, commands, prompt, right click, quick fix, debug, action] -sidebar_position: 4 ---- - -While many Actions are based on templated prompts and can be customized with .prompt files, there are a number that execute more complex code under the hood. - -Right click actions that generate inline diffs, use the same prompt and response processing logic as [Edit](../edit/how-it-works.md). - -To learn how other slash commands work, see the full reference [here](../customize/slash-commands.mdx). diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md deleted file mode 100644 index 2f13e4f1a..000000000 --- a/docs/docs/actions/how-to-customize.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: How to customize -description: How to customize Actions -keywords: [customize, actions] -sidebar_position: 5 ---- - -The easiest way to add actions is by adding [`prompt` blocks](../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../chat/how-it-works.md). - -Check out the [slash commands deep dive](../customize/slash-commands.mdx) for more information on extending actions. diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md deleted file mode 100644 index d69ec3851..000000000 --- a/docs/docs/actions/how-to-use-it.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Actions -description: How to use Actions -sidebar_label: How to use it -keywords: [how, slash, commands, prompt, right click, quick fix, debug, action] -sidebar_position: 1 ---- - -![actions](/img/actions.gif) - -## How to use it - -Actions are shortcuts for common use cases. For example, you might want to review code, write tests, or add a docstring. - -### Slash commands - -The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. - -![slash-commands](/img/slash-commands.png) - -In YAML assistants, slash commands are generated from [`prompts` blocks](../hub/blocks/block-types.md#prompts). - -Learn more about slash commands [here](../customize/slash-commands.mdx). - -:::info -Important: For assistants, slash commands only come from `prompts` blocks. When using older `config.json` configuration, other slash commands like `/share` and `/cmd` are included by default. -::: - -### Prompt files - -It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. - -Learn more about prompt files [here](../customize/deep-dives/prompt-files.md) - -### Other triggers for Actions (VS Code) - -:::info -Currently all of these are only available in VS Code -::: - -To make common use cases even more accessible, we provide a handful of other ways to invoke actions. - -#### Quick actions - -Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They can also be customized with .prompt files to perform custom actions. - -![quick-actions](/img/quick-actions.png) - -By default, quick actions are disabled, but can be enabled with the “Continue: Enable Quick Actions” in VS Code settings. - -#### Right click actions - -Right click actions let you highlight a desired region of code, right click, and then select an action from the dropdown menu. - -![context-menu](/img/context-menu.png) - -#### Debug action - -The debug action is a special built-in keyboard shortcut in the VS Code extension. Use cmd/ctrl + shift + R to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. - -#### Quick fixes - -Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut cmd/ctrl + . will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use cmd/ctrl + . again and Continue will attempt to help solve the problem. - -![ask-continue](/img/ask-continue.png) diff --git a/docs/docs/actions/model-setup.md b/docs/docs/actions/model-setup.md deleted file mode 100644 index 91912dcbf..000000000 --- a/docs/docs/actions/model-setup.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Model setup -description: Actions model setup -keywords: [model] -sidebar_position: 2 ---- - -By default, Actions uses the same model as [Chat](chat/model-setup.mdx), since we recommend a similar, 400B+ parameter model or one of the frontier models for the complex instructions that will be carried out. - -You can also set specific models to be used for Edit and Apply actions. See the [Model roles](../customize/model-roles/intro.mdx) page for more details. diff --git a/docs/docs/agent/context-selection.md b/docs/docs/agent/context-selection.md new file mode 100644 index 000000000..e341707d7 --- /dev/null +++ b/docs/docs/agent/context-selection.md @@ -0,0 +1,12 @@ +--- +title: Context selection +description: How context can be selected for Chat +keywords: [context] +sidebar_position: 3 +--- + +You can use the same [methods to manually add context as Chat](../chat/context-selection.md). + +In addition, tool call responses are automatically included as context items. + +This enables Agent mode to see the result of the previous action and decide what to do next. \ No newline at end of file diff --git a/docs/docs/agent/how-it-works.md b/docs/docs/agent/how-it-works.md new file mode 100644 index 000000000..b89c7ac85 --- /dev/null +++ b/docs/docs/agent/how-it-works.md @@ -0,0 +1,38 @@ +--- +title: How it works +description: How Agent works +keywords: [how, agent, works] +sidebar_position: 4 +--- + +Agent offers the same functionality as Chat, while also including tools in the request to the model and an interface for handling tool calls and responses. + +## The tool handshake + +Tools provide a flexible, powerful way for models to interface with the external world. They are provided to the model as a JSON object with a name and an arguments schema. For example, a `read_file` tool with a `filepath` argument will give the model the ability to request the contents of a specific file. + +The following handshake describes how Agent uses tools: +1. In Agent mode, available tools are sent along with `user` chat requests +2. The model can choose to include a tool call in its response +3. The user gives permission. This step is skipped if the policy for that tool is set to `Automatic` +4. Continue calls the tool using built-in functionality or the MCP server that offers that particular tool +5. Continue sends the result back to the model +6. The model responds, potentially with another tool call and step 2 begins again + +:::info +In [Chat mode](../chat/how-to-use-it.md), tools are **not** included in the request to the model. +::: + +## Built-in tools + +Continue includes several built-in tools which provide the model access to IDE functionality: + +- **Read file** (`builtin_read_file`): read the contents of a file within the project +- **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file +- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model +- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project +- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root +- **Search web** (`builtin_search_web`): Perform a web search to get top results +- **View diff** (`builtin_view_diff`): View the current working git diff +- **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map) +- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project \ No newline at end of file diff --git a/docs/docs/agent/how-to-customize.md b/docs/docs/agent/how-to-customize.md new file mode 100644 index 000000000..9159ea871 --- /dev/null +++ b/docs/docs/agent/how-to-customize.md @@ -0,0 +1,32 @@ +--- +title: How to customize +description: How to customize Chat +keywords: [customize, chat] +sidebar_position: 5 +--- + +## Add MCP tools + +You can add MCP servers to your assistant to give Agent access to more tools. [Explore MCP Servers on the Hub](https://hub.continue.dev/explore/mcp) and see the [MCP guide](../customize/deep-dives/mcp.mdx) for more details. + +## Tool policies + +You can adjust Agent's usage behavior for each tool in your assistant to one of these options: + +- **Ask First (default)** - request permission from the user; show the `Cancel` and `Continue` buttons +- **Automatic** - do not request permission, automatically call the tool and feed the response back to the model +- **Excluded** - do not send this tool to the model + +:::warning +Be careful setting any tools to `automatic` if their behavior is not read-only. +::: + +First, open `Tool Policies` by clicking the tools icon in the input toolbar + +![Input Toolbar](/img/lump-toolbar.png) + +Then, you can view and change tool policies. To change a policy, click on the policy text ("Excluded", etc.) to toggle it. You can also turn groups of tools (e.g. all Built-in tools or all tools from a specific MCP server) off using the section toggles. + +![Tool Policies](/img/tool-policies.png) + +Tool policies are stored locally per user. \ No newline at end of file diff --git a/docs/docs/agent/how-to-use-it.md b/docs/docs/agent/how-to-use-it.md new file mode 100644 index 000000000..780163faf --- /dev/null +++ b/docs/docs/agent/how-to-use-it.md @@ -0,0 +1,49 @@ +--- +title: Agent +description: How to use Agent +sidebar_label: How to use it +keywords: [how, use, agent] +sidebar_position: 1 +--- + +![agent mode](/img/agent.gif) + +## How to use it + +Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions. + +### Use Agent + +You can switch to `Agent` in the mode selector below the chat input box. + +![How to select agent mode](/img/mode-select-agent.png) + +:::info +If Agent is disabled with a `Not Supported` message, the selected model or provider doesn't support tools, or Continue doesn't yet support tools with it. See [Model Setup](./model-setup.mdx) for more information. +::: + +### Chat with Agent + +Agent lives within the same interface as [Chat](../chat/how-it-works.md), so the same [input](../chat/how-to-use-it.md#type-a-request-and-press-enter) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](../chat/how-to-use-it.md#reference-context-with-the--symbol) or adding [highlighted code from the editor](../chat/how-to-use-it.md#highlight-a-code-section-to-include-as-context). + +#### Use natural language + +With Agent, you can provide natural language instruction and let the model do the work. As an example, you might say + +> Set the @typescript-eslint/naming-convention rule to "off" for all eslint configurations in this project + +Agent will then decide which tools to use to get the job done. + +## Give Agent permission + +By default, Agent will ask permission when it wants to use a tool. Click `Continue` to allow Agent mode to proceed with the tool call or `Cancel` to reject it. + +![agent requesting permission](/img/agent-permission.png) + +You can use tool policies to exclude or make usage automatic for specific tools. See [How to Customize](./how-to-customize.md) for more background. + +## View Tool Responses + +Any data returned from a tool call is automatically fed back into the model as a context item. Most errors are also caught and returned, so that Agent mode can decide how to proceed. + +![agent response](/img/agent-response.png) \ No newline at end of file diff --git a/docs/docs/agent/model-setup.mdx b/docs/docs/agent/model-setup.mdx new file mode 100644 index 000000000..89e1cdf7e --- /dev/null +++ b/docs/docs/agent/model-setup.mdx @@ -0,0 +1,19 @@ +--- +title: Model setup +description: Models for Continue Agent +keywords: [model, agent] +sidebar_position: 2 +--- + +Agent can be used with models that support tool use through Continue. + +For the best Agent experience we recommend Claude 3.7 Sonnet from Anthropic. Add Claude 3.7 Sonnet to your assistant from the hub [here](https://hub.continue.dev/anthropic/claude-3-7-sonnet). You can get an API key from the [Anthropic console](https://console.anthropic.com/settings/keys). + +Currently the following providers are supported: + +- [Anthropic](../customize/model-providers/top-level/anthropic.mdx) - we recommend [Claude Sonnet 3.7](https://hub.continue.dev/anthropic/claude-3-7-sonnet) +- [Ollama](../customize/model-providers/top-level/ollama.mdx) - we recommend [Qwen 2.5 Coder 7b](https://hub.continue.dev/ollama/qwen2.5-coder-7b). Also see all Ollama models that support tools [here](https://ollama.com/search?c=tools). +- [OpenAI](../customize/model-providers/top-level/openai.mdx) - we recommend [GPT-4o](https://hub.continue.dev/openai/gpt-4o) +- [Gemini](../customize/model-providers/top-level/gemini.mdx) - we recommend [Gemini 2.0 Flash](https://hub.continue.dev/google/gemini-2.0-flash) + +The best chat models generally support tool usage. See [recommended chat models](../customize/model-roles/chat.mdx#recommended-chat-models) for more. diff --git a/docs/docs/autocomplete/how-to-customize.md b/docs/docs/autocomplete/how-to-customize.md index db77a43f0..5f7327a0d 100644 --- a/docs/docs/autocomplete/how-to-customize.md +++ b/docs/docs/autocomplete/how-to-customize.md @@ -5,6 +5,6 @@ keywords: [customize] sidebar_position: 5 --- -Continue offers a handful of settings to customize autocomplete behavior. For the most part, these options can be found in the [User Settings Page](../customize/settings.md). +Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](../customize/deep-dives/settings.md) to manage these settings. For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](../customize/deep-dives/autocomplete.mdx). diff --git a/docs/docs/chat/how-to-customize.md b/docs/docs/chat/how-to-customize.md index acb357983..ce8c9ff1b 100644 --- a/docs/docs/chat/how-to-customize.md +++ b/docs/docs/chat/how-to-customize.md @@ -10,6 +10,5 @@ There are a number of different ways to customize Chat: - You can add a [`rules` block](../hub/blocks/block-types.md#rules) to your assistant to give the model persistent instructions through the system prompt. See the [rules deep dive](../customize/deep-dives/rules.md) for more information. - You can configure [`@Codebase`](../customize/deep-dives/codebase.mdx) - You can configure [`@Docs`](../customize/deep-dives/docs.mdx) -- You can configure and create custom [tools](../customize/tools.mdx) - You can [build your own context provider](../customize/tutorials/build-your-own-context-provider.mdx) - You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.mdx) diff --git a/docs/docs/customize/context-providers.mdx b/docs/docs/customize/context-providers.mdx index b31deedf4..204f680f0 100644 --- a/docs/docs/customize/context-providers.mdx +++ b/docs/docs/customize/context-providers.mdx @@ -530,10 +530,6 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a You'll then be able to type "@" and see "MCP" in the context providers dropdown. -### Prompt Files - -See [Prompt Files](./deep-dives/prompt-files.md). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers. - ### `@Issue` Reference the conversation in a GitHub issue. @@ -883,7 +879,6 @@ You can override this query by setting the `issueQuery` parameter. You can set the `maxResults` parameter to limit the number of results returned. The default is `50`. - ### `@Discord` Reference the messages in a Discord channel. diff --git a/docs/docs/customize/deep-dives/autocomplete.mdx b/docs/docs/customize/deep-dives/autocomplete.mdx index c350b4d2c..6fd498e8d 100644 --- a/docs/docs/customize/deep-dives/autocomplete.mdx +++ b/docs/docs/customize/deep-dives/autocomplete.mdx @@ -90,15 +90,15 @@ Explore autocomplete model configurations on [the hub](https://hub.continue.dev/ ### Autocomplete User Settings -The following settings can be configured for autocompletion in the IDE extension [User Settings Page](../settings.md): +{/* - `Use autocomplete cache`: If on, caches completions */} +The following settings can be configured for autocompletion in the IDE extension [User Settings Page](./settings.md): -- `Use autocomplete cache`: If on, caches completions - `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` - `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" ### `config.json` Configuration -The `config.json` configuration format (deprecated) offers further configuration options through `tabAutocompleteOptions`. See the [JSON Reference](../../reference.md#tabautocompleteoptions) for more details. +The `config.json` configuration format (deprecated) offers further configuration options through `tabAutocompleteOptions`. See the [JSON Reference](../../json-reference.md#tabautocompleteoptions) for more details. ## FAQs diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index dd48ddbe7..c6c87ae7a 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -5,20 +5,26 @@ keywords: [config, settings, customize] # Configuration +You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon. + +![configure an assistant](/img/configure-continue.png) + +## Hub Assistants + +Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editing an Assistant](../../hub/assistants/edit-an-assistant.md) + ## YAML Config -Continue can be deeply customized. Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: +Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: To open `config.yaml`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open Assistant configuration` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below. - `~/.continue/config.yaml` (MacOS / Linux) - `%USERPROFILE%\.continue\config.yaml` (Windows) -To open your configuration file, you can click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or check the reference below. - When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. -See the full reference for `config.yaml` [here](../../yaml-reference.md). +See the full reference for `config.yaml` [here](../../reference.md). ## Deprecated configuration methods @@ -26,7 +32,7 @@ See the full reference for `config.yaml` [here](../../yaml-reference.md). View the `config.json` migration guide [here](../../yaml-migration.md) ::: -- [`config.json`](../../reference.md) - The original configuration format which is stored in a file at the same location as `config.yaml` +- [`config.json`](../../json-reference.md) - The original configuration format which is stored in a file at the same location as `config.yaml` - [`.continuerc.json`](#continuercjson) - Workspace-level configuration - [`config.ts`](#configts) - Advanced configuration (probably unnecessary) - a TypeScript file in your home directory that can be used to programmatically modify (_merged_) the `config.json` schema: - `~/.continue/config.ts` (MacOS / Linux) @@ -49,7 +55,9 @@ Example ### `config.ts` -To programatically extend `config.json`, you can place a `config.ts` script in same directory as `config.json` and export a `modifyConfig` function, like: +`config.yaml` or `config.json` can handle the vast majority of necessary configuration, so we recommend using it whenever possible. However, if you need to programmatically extend Continue configuration, you can use a `config.ts` file, placed at `~/.continue/config.ts` (MacOS / Linux) or `%USERPROFILE%\.continue\config.ts` (Windows). + +`config.ts` must export a `modifyConfig` function, like: ```ts title="config.ts" export function modifyConfig(config: Config): Config { @@ -75,4 +83,4 @@ export function modifyConfig(config: Config): Config { } ``` -This can be used for slash commands and custom context providers. +For examples of how to use `config.ts`, see [writing custom slash commands](../tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](../tutorials/build-your-own-context-provider.mdx). diff --git a/docs/docs/customize/deep-dives/development-data.md b/docs/docs/customize/deep-dives/development-data.md index da9f5136c..dd1e0c546 100644 --- a/docs/docs/customize/deep-dives/development-data.md +++ b/docs/docs/customize/deep-dives/development-data.md @@ -16,6 +16,6 @@ You can also configure custom destinations for your data, including remote HTTP For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data). -See more details about adding `data` blocks to your configuration files in the [YAML specification](../../yaml-reference.md#data) +See more details about adding `data` blocks to your configuration files in the [YAML specification](../../reference.md#data) When sending development data to your own HTTP endpoint, it will receive an event JSON blob at the given `schema` version. You can view event names, schema versions, and fields [here in the source code](https://github.com/continuedev/continue/tree/main/packages/config-yaml/src/schemas/data). diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index ee806263e..b21f78092 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -54,12 +54,6 @@ The `@Docs` context provider works by 3. Storing the embeddings locally on your machine 4. Embedding chat input to include similar documentation chunks as context -## Pre-indexed Documentation Sites - -In VS Code, Continue offers a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). - -Pre-indexed docs are only available in VS Code because the VS Code extension ships with the Transformers.js embedder built in, while Jetbrains currently does not. You can override a pre-indexed doc to index it with your own embeddings provider by adding it to your config (unique by `startUrl`). Otherwise, it will always use Transformers.js for queries. - ## Indexing Your Own Documentation ### Hub `docs` Blocks @@ -221,7 +215,10 @@ If your documentation is private, you can skip the default crawler and use a loc -The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../settings.md) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. +:::info +Chromium crawling has been deprecated +{/* The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../deep-dives/settings.md) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. */} +::: Further notes: @@ -248,7 +245,7 @@ You can also use the following IDE command to force a re-index of all docs: `Con ### VS Code minimal setup -The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. Pre-indexed docs will be accessible. +The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. @@ -282,7 +279,7 @@ The following configuration example works out of the box for VS Code. This uses ### Jetbrains minimal setup -Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-roles/embeddings.mdx). Pre-indexed docs will _not_ be accessible. +Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-roles/embeddings.mdx). @@ -407,4 +404,4 @@ The following configuration example includes: -This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../settings.md). +{/* This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../deep-dives/settings.md). */} diff --git a/docs/docs/customize/tools.mdx b/docs/docs/customize/deep-dives/mcp.mdx similarity index 52% rename from docs/docs/customize/tools.mdx rename to docs/docs/customize/deep-dives/mcp.mdx index 1aad549f1..e4e828520 100644 --- a/docs/docs/customize/tools.mdx +++ b/docs/docs/customize/deep-dives/mcp.mdx @@ -1,36 +1,19 @@ --- -title: Tools -description: Tool use and customization +title: MCP +description: MCP use and customization keywords: [tool, use, function calling, claude, automatic] --- import TabItem from "@theme/TabItem"; import Tabs from "@theme/Tabs"; -Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported for the following providers: - -- [Anthropic](./model-providers/top-level/anthropic.mdx) - see recommended models [here](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#choosing-a-model). -- [Ollama](./model-providers/top-level/ollama.mdx) - see recommended models [here](https://ollama.com/search?c=tools). -- [OpenAI](./model-providers/top-level/openai.mdx) -- [Gemini](./model-providers/top-level/gemini.mdx) - -To use tools, click on the icon in the input toolbar like below. - -![tools](/img/tool-use-example.png) - -To let you balance speed and safety, each tool can be set to 1 of 3 modes: - -- `Automatic`: When the LLM requests to use the tool, Continue will automatically call it and send the response to the LLM. -- `Allowed`: When the LLM requests to use the tool, Continue will first give you the opportunity to "Cancel" or "Continue" with the tool. -- `Disabled`: The LLM will not know about or be able to use the tool. - -### Custom tools +## MCP Currently custom tools can be configured using the [Model Context Protocol](https://modelcontextprotocol.io/introduction), a standard proposed by Anthropic to unify prompts, context, and tool use. MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp). -To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md): +To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](./configuration.md): diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md deleted file mode 100644 index 68995746f..000000000 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Prompt files ---- - -Prompt files allow you to build and use local prompts, and provide a convenient way to test and iterate on prompts before publishing them to the Hub. - -:::info -Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts) -::: - -## Quick start - -Below is a quick example of setting up a prompt file: - -1. Create a folder called `.continue/prompts` at the top level of your workspace (or you can use the button in the UI by typing @, selecting "Prompt Files", and selecting "New Prompt File"). -2. Add a file called `rails.prompt` to this folder. -3. Write the following contents to `rails.prompt` and save. - -```.prompt -name: Rails Project -description: Information about this project ---- -Attached is a summary of the current Ruby on Rails application, including the @Gemfile and database schema in @db/schema.rb -``` - -Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. - -Then, type / and choose the "Rails Project" prompt. You can now ask any question as usual and the LLM will have the information from your .prompt file. - -## Format - -The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers. - -:::info -The current state of this format is experimental and subject to change -::: - -### Preamble - -The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: - -- `name` - The display title -- `description` - The description you will see in the dropdown -- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set) - -If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. - -### Context - -Many [context provider](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: - -- `@terminal` - The contents of the terminal -- `@currentFile` - The currently active file -- `@open` - All open files -- `@os` - Information about the operating system -- `@problems` - Problems reported by the language server in the active file -- `@repo-map` - A map of files in the repository -- `@tree` - A tree view of the repository structure - -Or you can directly type URLs and file paths: - -- `@https://github.com/continuedev/continue` - The contents of a URL -- `@src/index.ts` - The contents of a file (VS Code only) - -All references will be attached as context items, rather than injected directly inline. - -## Feedback - -If you have ideas about how to improve the `.prompt` file format, please reach out on [Discord](https://discord.gg/NWtdYexhMs). diff --git a/docs/docs/customize/deep-dives/prompts.md b/docs/docs/customize/deep-dives/prompts.md new file mode 100644 index 000000000..1cd1c0085 --- /dev/null +++ b/docs/docs/customize/deep-dives/prompts.md @@ -0,0 +1,97 @@ +--- +title: Prompts +--- + +Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. + +:::info +Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts) +::: + +## Examples + +Below are some examples to get you started. + +### Security review + +```text title="Security best practices review" +@open - Review these files for the following security best practices: +- Does the architecture follow security-by-design principles? +- Are there potential security vulnerabilities in the system design? +- Is sensitive data handled appropriately throughout the lifecycle? +``` + +### Reference best practice guides + +```text title="Redux best practices review" +@https://redux.js.org/style-guide/ +@currentFile + +Review this code for adherence to Redux best practices. +``` + +### Pull in commonly used files for tasks + +```text title="Generate a new TypeORM entity" +@src/db/dataSource.ts @src/db/entity/SampleEntity.ts + +Use these files to generate a new TypeORM entity based on the following requirements: +``` + +## Including Context Providers in your prompts + +Many [context providers](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: + +- `@terminal` - The contents of the terminal +- `@currentFile` - The currently active file +- `@open` - All open files +- `@os` - Information about the operating system +- `@problems` - Problems reported by the language server in the active file +- `@repo-map` - A map of files in the repository +- `@tree` - A tree view of the repository structure + +Or you can directly type URLs and file paths: + +- `@https://github.com/continuedev/continue` - The contents of a URL +- `@src/index.ts` - The contents of a file (VS Code only) + +All references will be attached as context items, rather than injected directly inline. + +## Local `.prompt` files + +In addition to Prompt blocks on the Hub, you can also define prompts in local `.prompt` files, located in the `.continue/prompts` folder at the top level of your workspace. This is useful for quick iteration on prompts to test them out before pushing up to the Hub. + +### Quick Start + +Below is a quick example of setting up a prompt file: + +1. Create a folder called `.continue/prompts` at the top level of your workspace +2. Add a file called `test.prompt` to this folder. +3. Write the following contents to `test.prompt` and save. + +```.prompt +name: Current file prompt +description: A test prompt using the current file context provider +--- +@currentFile +``` + +Now to use this prompt, you can open Chat, type /, select the prompt, and add type out some additional text such as "Review the code for any issues". + +### Format + +The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers. + +:::info +The current state of this format is experimental and subject to change +::: + +### Preamble + +The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: + +- `name` - The display title +- `description` - The description you will see in the dropdown +- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set) + +If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. diff --git a/docs/docs/customize/settings.md b/docs/docs/customize/deep-dives/settings.md similarity index 50% rename from docs/docs/customize/settings.md rename to docs/docs/customize/deep-dives/settings.md index f76494032..0d3b57127 100644 --- a/docs/docs/customize/settings.md +++ b/docs/docs/customize/deep-dives/settings.md @@ -14,21 +14,21 @@ Which takes you to this page: ![User Settings Page](/img/settings-page.png) -Click the `Open Assistant configuration` button to open your configuration file. See the [Configuration Reference](../reference.md) for more information. - Below that, the following settings which are not part of a configuration file are available: +- `Show Session Tabs`: If on, displays tabs above the chat as an alternative way to organize and access your sessions. Off by default - `Wrap Codeblocks`: If on, enables text wrapping in code blocks. Off by default. -- `Display Raw Markdown`: If on, shows raw markdown in responses. Off by default. -- `Allow Anonymous Telemetry`: If on, allows Continue to send anonymous telemetry. **On** by default. -- `Disable Indexing`: Prevents indexing of the codebase, useful primarily for debugging purposes. Off by default. -- `Disable Session Titles`: Prevents generating summary titles for each chat session when turned on. Off by default -- `Response Text to Speech`: If on, reads LLM responses aloud with TTS. Off by default. - `Show Chat Scrollbar`: If on, enables a scrollbar in the chat window. Off by default. -- `Use autocomplete cache`: If on, caches completions. -- `Use Chromium for Docs Crawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to ~/.continue/.utils. Off by default -- `Codeblock Actions Position`: Sets the position for the actions that show when hovering over codeblocks. Defaults to `top` -- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` +- `Text-to-Speech Output`: If on, reads LLM responses aloud with TTS. Off by default. +- `Enable Session Titles`: If on, generates summary titles for each chat session after the first message, using the current Chat model. On by default. +- `Format Markdown`: If off, shows responses as raw text. On by default. +- `Allow Anonymous Telemetry`: If on, allows Continue to send anonymous telemetry. **On** by default. +- `Enable Indexing`: Enables indexing of the codebase for the @codebase and @code context providers. **On** by default. - `Font Size`: Specifies base font size for UI elements -- `Workspace prompts path`: Where to find Prompt Files in a workspace - replaces the default .continue/prompts +- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` - `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" + + + + + diff --git a/docs/docs/customize/deep-dives/slash-commands.mdx b/docs/docs/customize/deep-dives/slash-commands.mdx new file mode 100644 index 000000000..059cf8213 --- /dev/null +++ b/docs/docs/customize/deep-dives/slash-commands.mdx @@ -0,0 +1,33 @@ +--- +title: Slash commands +description: Shortcuts that can be activated by prefacing your input with '/' +keywords: [slash command, custom commands, step] +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +![actions](/img/actions.gif) + +## Slash commands + +Slash commands are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. +{/* ![slash-commands](/img/slash-commands.png) */} + +Slash commands can be combined with additional instructions, including [context providers](../context-providers.mdx) or [highlighted code](../../edit/context-selection#highlighted-code). + +## Prompts + +### Assistant prompt blocks + +The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../../chat/how-it-works.md). + +### Prompt files + +It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. + +Learn more about prompt files [here](./prompts.md) + +### MCP Server prompts + +Any prompts provided by [Model Context Protocol](https://modelcontextprotocol.io/introduction) servers are also accessible in chat as Slash Commands. See the [MCP Server Deep Dive](./mcp.mdx) for more details. diff --git a/docs/docs/customize/deep-dives/vscode-actions.md b/docs/docs/customize/deep-dives/vscode-actions.md new file mode 100644 index 000000000..d9f1b7b66 --- /dev/null +++ b/docs/docs/customize/deep-dives/vscode-actions.md @@ -0,0 +1,49 @@ +--- +title: VS Code Actions +description: VS Code Actions +keywords: [vscode, quick actions, quick, actions] +--- + +### Other triggers for Actions (VS Code) + +:::info +Currently all of these are only available in VS Code +::: + +To make common use cases even more accessible, we provide a handful of other ways to invoke actions in VS Code. + +## Quick actions + +Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompts.md) to perform custom actions. + +![quick-actions](/img/quick-actions.png) + +By default, quick actions are disabled, but can be enabled with the “Continue: Enable Quick Actions” in VS Code settings. + +## Right click actions + +Right click actions let you highlight a desired region of code, right click, and then select an action from the dropdown menu. + +The highlighted code you’ve selected will be included in your prompt alongside a pre-written set of instructions depending on the selected action. This is the only section of code that the model will attempt to edit. + +Right click actions that generate inline diffs use the same prompt and response processing logic as [Edit](../../edit/how-it-works.md). + +![context-menu](/img/context-menu.png) + +## Debug action + +The debug action is a special built-in keyboard shortcut in the VS Code extension. Use cmd/ctrl + shift + R to instantly copy the contents of the most recent terminal output into the chat sidebar and get debugging advice. There is no additional, non-visible information sent to the language model. + +``` +I got the following error, can you please help explain how to fix it? + +[ERROR_MESSAGE] +``` + +## Quick fixes + +Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut cmd/ctrl + . will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use cmd/ctrl + . again and Continue will attempt to help solve the problem. + +Similarly to the debug action, quick actions transparently inject a prompt into the chat window. When you select “Ask Continue”, the 3 lines above and below the error are sent to the chat followed by the question “How do I fix the following problem in the above code?: [ERROR_MESSAGE]”. + +![ask-continue](/img/ask-continue.png) diff --git a/docs/docs/customize/model-providers/more/nebius.mdx b/docs/docs/customize/model-providers/more/nebius.mdx index 12a660ead..35c654bbb 100644 --- a/docs/docs/customize/model-providers/more/nebius.mdx +++ b/docs/docs/customize/model-providers/more/nebius.mdx @@ -15,9 +15,9 @@ Available models can be found on the [Nebius AI Studio models page](https://stud ```yaml title="config.yaml" models: - - name: Llama 3.1 405b + - name: DeepSeek R1 provider: nebius - model: llama3.1-405b + model: deepseek-ai/DeepSeek-R1 apiKey: ``` @@ -26,9 +26,9 @@ Available models can be found on the [Nebius AI Studio models page](https://stud { "models": [ { - "title": "Llama 3.1 405b", + "title": "DeepSeek R1", "provider": "nebius", - "model": "llama3.1-405b", + "model": "deepseek-ai/DeepSeek-R1", "apiKey": "" } ] diff --git a/docs/docs/customize/model-providers/more/watsonx.mdx b/docs/docs/customize/model-providers/more/watsonx.mdx index f2360788f..1bc247399 100644 --- a/docs/docs/customize/model-providers/more/watsonx.mdx +++ b/docs/docs/customize/model-providers/more/watsonx.mdx @@ -128,8 +128,8 @@ You can also configure generation parameters, such as temperature, topP, topK, f apiBase: watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com apiKey: API_KEY/ZENAPI_KEY/USERNAME:PASSWORD template: granite - contextLength: 8000 defaultCompletionOptions: + contextLength: 8000 temperature: 0.1 topP: 0.3 topK: 20 @@ -245,7 +245,6 @@ To view the list of available embeddings models, visit [this page](https://datap - ## Reranker diff --git a/docs/docs/customize/model-providers/top-level/bedrock.mdx b/docs/docs/customize/model-providers/top-level/bedrock.mdx index 9582428a4..45cf5e5eb 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.mdx +++ b/docs/docs/customize/model-providers/top-level/bedrock.mdx @@ -80,7 +80,7 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. ## Autocomplete model -Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolisde](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. +Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolside](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. In the meantime, you can view a list of autocomplete model providers [here](../../model-roles/autocomplete.md). diff --git a/docs/docs/customize/model-providers/top-level/openai.mdx b/docs/docs/customize/model-providers/top-level/openai.mdx index 8ed706213..7e3870720 100644 --- a/docs/docs/customize/model-providers/top-level/openai.mdx +++ b/docs/docs/customize/model-providers/top-level/openai.mdx @@ -21,7 +21,7 @@ We recommend configuring **GPT-4o** as your chat model. - name: GPT-4o provider: openai model: gpt-4o - apiKey: + apiKey: ``` @@ -32,7 +32,7 @@ We recommend configuring **GPT-4o** as your chat model. "title": "GPT-4o", "provider": "openai", "model": "gpt-4o", - "apiKey": "" + "apiKey": "" } ] } @@ -57,7 +57,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. - name: OpenAI Embeddings provider: openai model: text-embedding-3-large - apiKey: + apiKey: roles: - embed ``` @@ -68,7 +68,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. "embeddingsProvider": { "provider": "openai", "model": "text-embedding-3-large", - "apiKey": "" + "apiKey": "" } } ``` diff --git a/docs/docs/customize/model-roles/chat.mdx b/docs/docs/customize/model-roles/chat.mdx index 90b97e17c..aca683782 100644 --- a/docs/docs/customize/model-roles/chat.mdx +++ b/docs/docs/customize/model-roles/chat.mdx @@ -10,7 +10,7 @@ import Tabs from "@theme/Tabs"; A "chat model" is an LLM that is trained to respond in a conversational format. Because they should be able to answer general questions and generate complex code, the best chat models are typically large, often 405B+ parameters. -In Continue, these models are used for [Chat](../../chat/how-to-use-it.md) and [Actions](../../actions/how-to-use-it.md). The selected chat model will also be used for [Edit](../../edit/how-to-use-it.md) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively. +In Continue, these models are used for normal [Chat](../../chat/how-to-use-it.md) and [VS Code actions](../deep-dives/vscode-actions.md). The selected chat model will also be used for [Edit](../../edit/how-to-use-it.md) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively. ## Recommended Chat models @@ -51,117 +51,66 @@ Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-pr -### Llama 3.1 405B from Meta +### Gemma from Google DeepMind -If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../model-providers/more/together.mdx) or [Groq](../model-providers/more/groq.mdx)) or self-host it (e.g. using [vLLM](../model-providers//more/vllm.mdx) or [Ollama](../model-providers/top-level/ollama.mdx)). +If you prefer to use an open-weight model, then the Gemma family of Models from Google DeepMind is a good choice. You will need to decide if you use it through a SaaS model provider, e.g. [Together](../model-providers/more/together.mdx), or self-host it, e.g. [Ollama](../model-providers/top-level/ollama.mdx). - {/* HUB_TODO nonexistent blocks */} - {/* + - - Add the [Together Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub - - - Add the [Groq Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub - - - Add the [vLLM Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub - - Add the [Ollama Llama 3.1 405b block](https://hub.continue.dev/explore/assistants) from the hub + Add the [Ollama Gemma 3 27B block](https://hub.continue.dev/ollama/gemma3-27b) from the hub + + + Add the [Together Gemma 2 27B Instruct block](https://hub.continue.dev/togetherai/gemma-2-instruct-27b) from the hub - */} + - - ```yaml title="config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "together" - model: "llama3.1-405b" - apiKey: - ``` - - - ```yaml title="config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "groq" - model: "llama3.1-405b" - apiKey: - ``` - - - ```yaml title="config.yaml" - models: - - name: "Llama 3.1 405B" - provider: "vllm" - model: "llama3.1-405b" - ``` - ```yaml title="config.yaml" models: - - name: "Llama 3.1 405B" + - name: "Gemma 3 27B" provider: "ollama" - model: "llama3.1:405b" + model: "gemma3:27b" + ``` + + + ```yaml title="config.yaml" + models: + - name: "Gemma 3 27B" + provider: "together" + model: "google/gemma-2-27b-it" + apiKey: ``` - - ```json title="config.json" - { - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "together", - "model": "llama3.1-405b", - "apiKey": "" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "groq", - "model": "llama3.1-405b", - "apiKey": "" - } - ] - } - ``` - - - ```json title="config.json" - { - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "vllm", - "model": "llama3.1-405b" - } - ] - } - ``` - ```json title="config.json" { "models": [ { - "title": "Llama 3.1 405B", + "title": "Gemma 3 27B", "provider": "ollama", - "model": "llama3.1:405b" + "model": "gemma3:27b" + } + ] + } + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Gemma 3 27B", + "provider": "together", + "model": "google/gemma-2-27b-it", + "apiKey": "" } ] } diff --git a/docs/docs/customize/model-roles/intro.mdx b/docs/docs/customize/model-roles/intro.mdx index 3c3a6476e..5a2cb4b05 100644 --- a/docs/docs/customize/model-roles/intro.mdx +++ b/docs/docs/customize/model-roles/intro.mdx @@ -18,14 +18,14 @@ Models in Continue can be configured to be used for various roles in the extensi - [`embed`](./embeddings.mdx): Used to generate embeddings used for vector search (@Codebase and @Docs context providers) - [`rerank`](./reranking.mdx): Used to rerank results from vector search -These roles can be specified for a `config.yaml` model block using `roles`. See the [YAML Specification](../../yaml-reference.md#models) for more details. +These roles can be specified for a `config.yaml` model block using `roles`. See the [YAML Specification](../../reference.md#models) for more details. ## Selecting model roles -You can control which of the models in your assistant for a given role will be currently used for that role. Visit the [Settings page](../settings.md) and go to the **Active Models** section. +You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role. ![Settings Active Models Section](/img/settings-model-roles.png) :::info -Note that `roles` do not exist within `config.json` - they are infered by the top level keys like `embeddingsProvider` +`roles` are not explicitly defined within `config.json` (deprecated) - they are infered by the top level keys like `embeddingsProvider` ::: diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index ae2baf79a..3cd6f2615 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -7,44 +7,18 @@ keywords: [customize, configure, config] Continue can be deeply customized. For example you might: - **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](../customize/model-providers/). -- **Select different model providers for each Compose feature**. Different Continue features can use different model providers. We call these _model types_. For example, you can use a different model provider for chat than you do for autocomplete. Learn more about [model types](../customize/model-roles/) . -- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/context-providers). -- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/slash-commands). -- **Call external tools and functions**. Unchain your LLM with the power of _Tools_. You can call any external tool or function from your prompts. Currently only available with Anthropic. Learn more about [Tools](/customize/tools). +- **Select different models for specific tasks**. Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](./model-roles/) . +- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](./context-providers.mdx). +- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](./deep-dives/slash-commands.mdx). +- **Call external tools and functions**. Unchain your LLM with the power of tools using [Agent](../agent/how-to-use-it.md). Add custom tools using [MCP Servers](./deep-dives/mcp.mdx) -Whatever you choose, you'll probably start by editing `config.yaml`. +Whatever you choose, you'll probably start by editing your Assistant. -## Editing config.json +## Editing your assistant -Most custom configuration is done by editing `config.yaml` (or the older `config.json`). This is a YAML file that allows you to customize Continue to your liking. It is found at: +You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon. -- MacOS and Linux: `~/.continue/config.yaml` -- Windows: `%USERPROFILE%\.continue\config.yaml` +![configure an assistant](/img/configure-continue.png) -You can easily access config file from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the "gear" icon in header to open the Settings page. Then click the button labeled `Open Assistant configuration`. - -![configure-continue](/img/configure-continue.png) - -When editing this file, you can see the available options suggested as you type, or you can check the [full reference](./deep-dives/configuration.md). - -:::info - -A configuration file is created the first time you use Continue. If you'd like to reset your configuration to the default, you can delete this file and Continue will automatically recreate it with the default settings. - -::: - -:::info - -When you save a configuration file from the IDE, Continue will automatically refresh to take into account your changes. - -::: - -## Per-workspace configuration - -If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. It has the same [definition](./deep-dives/configuration.md) as `config.json`, and will automatically be applied on top of the local config.json. - -## Programmatic configuration - -`config.yaml` or `config.json` can handle the vast majority of necessary configuration, so we recommend using it whenever possible. However, if you need to programmatically configure Continue, you can use `config.ts`, which is located at `~/.continue/config.ts` (MacOS / Linux) or `%USERPROFILE%\.continue\config.ts` (Windows). - -For examples of how to use `config.ts`, see [writing custom slash commands](./tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](./tutorials/build-your-own-context-provider.mdx). +- See [Editing Hub Assistants](../hub/assistants/edit-an-assistant.md) for more details on managing your hub assistant +- See the [Config Deep Dive](./deep-dives/configuration.md) for more details on configuring local assistants. diff --git a/docs/docs/customize/slash-commands.mdx b/docs/docs/customize/slash-commands.mdx deleted file mode 100644 index e1890ba81..000000000 --- a/docs/docs/customize/slash-commands.mdx +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Slash commands -description: Shortcuts that can be activated by prefacing your input with '/' -keywords: [slash command, custom commands, step] ---- - -import TabItem from "@theme/TabItem"; -import Tabs from "@theme/Tabs"; - -:::info -Slash commands can currently only be added using [`config.json`](../reference.md). The [`YAML Config Format`](../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../customize/deep-dives/prompt-files.md) to achieve similar functionality. -::: - -Slash commands are shortcuts that can be activated by typing '/' and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. - -![slash-commands](/img/slash-commands.png) - -## Built-in Slash Commands - -To use any of the built-in slash commands, open `config.json` and add it to the `slashCommands` list. - -### `/share` - -Generate a shareable markdown transcript of your current chat history. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "share", - "description": "Export the current chat session to markdown", - "params": { "outputDir": "~/.continue/session-transcripts" } - } - ] -} -``` - -Use the `outputDir` parameter to specify where you want to the markdown file to be saved. - -### `/cmd` - -Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "cmd", - "description": "Generate a shell command" - } - ] -} -``` - -### `/commit` - -Shows the LLM your current git diff and asks it to generate a commit message. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "commit", - "description": "Generate a commit message for the current changes" - } - ] -} -``` - -### `/http` - -Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "http", - "description": "Does something custom", - "params": { "url": "" } - } - ] -} -``` - -### `/issue` - -Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "issue", - "description": "Generate a link to a drafted GitHub issue", - "params": { "repositoryUrl": "https://github.com/continuedev/continue" } - } - ] -} -``` - -### `/onboard` - -The onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "onboard", - "description": "Familiarize yourself with the codebase" - } - ] -} -``` - -### Model Context Protocol - -The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports MCP "prompts" by creating slash commands. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this: - - - - ```yaml title="config.yaml" - mcpServers: - - name: My MCP Server - command: uvx - args: - - mcp-server-sqlite - - --db-path - - /Users/NAME/test.db - ``` - - - ```json title="config.json" - { - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } - } - ] - } - } - ``` - - - -### Build your own Slash Command - -You can build your own slash command by following [this tutorial](/customize/tutorials/build-your-own-slash-command). diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.mdx b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx index 7710a84c2..1494680c0 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.mdx +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx @@ -50,7 +50,7 @@ Then, create a server that responds to requests as are made from [HttpContextPro The `"options"` property can be used to send additional parameters to your endpoint, which will be included in the request body. :::info -The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompt files](../deep-dives/prompt-files.md) where possible. +The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompts](../deep-dives/prompts.md) where possible. ::: ## Using CustomContextProvider diff --git a/docs/docs/customize/tutorials/build-your-own-slash-command.md b/docs/docs/customize/tutorials/build-your-own-slash-command.md index f0cc1147f..03543a22f 100644 --- a/docs/docs/customize/tutorials/build-your-own-slash-command.md +++ b/docs/docs/customize/tutorials/build-your-own-slash-command.md @@ -3,7 +3,7 @@ title: Build your own slash command --- :::info -Slash commands can currently only be added using [`config.json`](../../reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompt-files.md) to achieve similar functionality. +Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompts.md) to achieve similar functionality. ::: There are two ways to add custom slash commands: diff --git a/docs/docs/customize/tutorials/running-continue-without-internet.md b/docs/docs/customize/tutorials/running-continue-without-internet.md index e3de1e79e..2ba683909 100644 --- a/docs/docs/customize/tutorials/running-continue-without-internet.md +++ b/docs/docs/customize/tutorials/running-continue-without-internet.md @@ -7,6 +7,6 @@ keywords: [no internet, air-gapped, local model] Continue can be run even on an air-gapped computer if you use a local model. Only a few adjustments are required for this to work. 1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix). -2. Open the [User Settings Page](../settings.md) and turn off "Allow Anonymous Telemetry". This will stop Continue from attempting requests to PostHog for [anonymous telemetry](../../telemetry.md). +2. Open the [User Settings Page](../deep-dives/settings.md) and turn off "Allow Anonymous Telemetry". This will stop Continue from attempting requests to PostHog for [anonymous telemetry](../../telemetry.md). 3. Also in `config.json`, set the default model to a local model. You can available options [here](../model-providers/). 4. Restart VS Code to ensure that the changes to `config.json` or `config.yaml` take effect. diff --git a/docs/docs/customize/tutorials/set-up-codestral.mdx b/docs/docs/customize/tutorials/set-up-codestral.mdx index 97ec3c981..1ace12f2f 100644 --- a/docs/docs/customize/tutorials/set-up-codestral.mdx +++ b/docs/docs/customize/tutorials/set-up-codestral.mdx @@ -45,13 +45,15 @@ import TabItem from "@theme/TabItem"; "apiBase": "https://codestral.mistral.ai/v1" } ], - "tabAutocompleteModel": { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest", - "apiKey": "", - "apiBase": "https://codestral.mistral.ai/v1" - } + "tabAutocompleteModel": [ + { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "", + "apiBase": "https://codestral.mistral.ai/v1" + } + ] } ``` diff --git a/docs/docs/edit/context-selection.md b/docs/docs/edit/context-selection.md index 0a4fbe3f8..ebe12d8da 100644 --- a/docs/docs/edit/context-selection.md +++ b/docs/docs/edit/context-selection.md @@ -9,10 +9,10 @@ keywords: [edit, cmd i, works] The input you provide is included in the prompt. -## Highlighted code +## Code to Edit -The highlighted code you’ve selected is included in the prompt. This is the only section of code that the model will attempt to edit. +The **entire contents** of each file (the current file for Jetbrains inline Edit, each `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges. -## Current file +## Context Providers -The entire contents of the file containing your highlighted code selection are included as additional context. This gives the model a broader understanding of the code's environment. If the file is too large to fit within the context window, we will trim the file's contents to fit. \ No newline at end of file +In VS Code Edit mode, you can use `@` to add context using [Context Providers](../customize/context-providers.mdx), similar to [Chat](../chat/context-selection.md). Some context providers may be disabled in Edit mode. diff --git a/docs/docs/edit/how-it-works.md b/docs/docs/edit/how-it-works.md index 453d1e98f..e9ff3bbb1 100644 --- a/docs/docs/edit/how-it-works.md +++ b/docs/docs/edit/how-it-works.md @@ -1,14 +1,14 @@ --- title: How Edit works sidebar_position: 4 -description: How Edit works +description: How it works keywords: [edit, cmd l, works] --- -Using the highlighted code, the contents of the file containing your highlight, and your input instructions, we prompt the model to edit the code according to your instructions. No other additional context is provided to the model. +Using the highlighted code, the contents of the current file containing your highlight, and your input instructions, we prompt the model to edit the code according to your instructions. No other additional context is provided to the model. The model response is then streamed directly back to the highlighted range in your code, where we apply a diff formatting to show the proposed changes. If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes. -If you would like to view the exact prompt that is sent to the model during an edit, you can [view this in the prompt logs](../troubleshooting.mdx#check-the-logs). +If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](../troubleshooting.mdx#check-the-logs). diff --git a/docs/docs/edit/how-to-customize.mdx b/docs/docs/edit/how-to-customize.mdx index 35b918393..46dd5e3da 100644 --- a/docs/docs/edit/how-to-customize.mdx +++ b/docs/docs/edit/how-to-customize.mdx @@ -5,7 +5,10 @@ description: How to customize Edit keywords: [edit, cmd i, works] --- -import TabItem from "@theme/TabItem"; -import Tabs from "@theme/Tabs"; +## Setting active Edit/Apply model -You can configure a particular model to be used for Edit by setting/overriding `roles` in the model's YAML config. See [Edit role](../customize/model-roles/edit.mdx) for more details. +You can configure particular models from your Assistant to be used for Edit and Apply requests (see [How it Works](./how-it-works.md)). Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then, you can use the dropdowns to select models to use for Edit and Apply. + +![Settings Active Models Section](/img/model-roles-edit.png) + +See [Edit role](../customize/model-roles/edit.mdx) and [Apply role](../customize/model-roles/apply.mdx) for more details. diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 850c34b60..620a18eda 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -10,9 +10,9 @@ keywords: [edit, cmd l, use] ## How to use it -Edit is a convenient way to modify code without leaving your current file. Highlight a block of code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject. +Edit is a convenient way to make quick changes to specific code and files. Select code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject. -Edit is best used for small, quick changes such as: +Edit is recommended for small, targeted changes, such as - Writing comments - Generating unit tests @@ -20,7 +20,7 @@ Edit is best used for small, quick changes such as: ## Highlight code and activate -Highlight the block of code you would like to modify, and press cmd/ctrl + i to activate the edit input. +Highlight the block of code you would like to modify and press cmd/ctrl + i to active Edit mode. You can also enter Edit mode by pressing cmd/ctrl + i with no code highlighted. ## Describe code changes @@ -35,3 +35,45 @@ You can navigate through each proposed change, accepting or rejecting them using You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. + +## VS Code + +In VS Code, Edit is implemented in the extension sidebar with a similar interface to [Chat](../chat/how-it-works.md), and you can also enter Edit mode by using the Mode Selector below the main Chat input to select `Edit`. + +![edit mode selected](/img/select-edit-mode.png) + +You can also reject and accept diffs using the `Reject All` and `Accept All` buttons that show up in the Chat when diffs are present (see examples below). + +### Adding Code to Edit + +Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor. + +**_Add file combobox_** + +![edit mode add file combobox](/img/edit-mode-add-files.png) + +**_Add all open files dropdown_** + +![edit mode add file combobox](/img/edit-mode-add-all-open-files.png) + +### Single File Edit + +If one file/range is present in `Code to Edit` on submission, Continue will prompt the Edit model and then automatically stream the diff into the editor. + +![Edit mode single file diffs](/img/edit-mode-single-file-diff.png) + +### Multi-File Edit + +If multiple files/ranges are present in `Code to Edit` on submission, Continue will prompt the Edit model to output codeblocks per-file, which the user can then choose to apply and accept/reject independently. + +**_Generated Content_** + +![Edit mode multi file generated content](/img/edit-mode-multi-file-generation.png) + +**_Diffs_** + +![Edit mode multi file diffs](/img/edit-mode-multi-file-diffs.png) + +## Jetbrains + +In Jetbrains, Edit is implemented as an inline popup (see the header GIF example) for single-file edit. Multi-file edit mode is not currently implemented. diff --git a/docs/docs/edit/model-setup.md b/docs/docs/edit/model-setup.md index 606bd0654..a76865dcd 100644 --- a/docs/docs/edit/model-setup.md +++ b/docs/docs/edit/model-setup.md @@ -5,8 +5,6 @@ description: How to set up an Edit model keywords: [edit, cmd l, model] --- -By default, Edit uses the [same model as Chat](../chat/model-setup.mdx) since we recommend a similar, 400B+ parameter model or one of the frontier model for code edits. +By default, Edit uses the [same model as Chat](../chat/model-setup.mdx), and we recommend [Claude 3.7 Sonnet](https://hub.continue.dev/anthropic/claude-3-7-sonnet) from Anthropic. Visit [the Hub](https://hub.continue.dev/explore/models?roles=edit) to explore other Edit models. -Visit [the hub](https://hub.continue.dev/explore/models?roles=edit) to explore Edit models. - -You can configure a different model to be used for edits by updating your [configuration](../customize/model-roles/edit.mdx). +For the best Edit experience, we also recommend setting up an Apply model, specially trained to apply diffs to files. We recommend [Morph v0 Fast Apply](https://hub.continue.dev/morphllm/morph-v0) or [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply). Explore other apply models on the [the Hub](https://hub.continue.dev/explore/models?roles=apply). diff --git a/docs/docs/getting-started/overview.mdx b/docs/docs/getting-started/overview.mdx index 446031fa7..fdd6a46d7 100644 --- a/docs/docs/getting-started/overview.mdx +++ b/docs/docs/getting-started/overview.mdx @@ -4,9 +4,9 @@ description: Getting started with Continue keywords: [quickstart, start, overview, chat, autocomplete, edit, actions] --- -import Tabs from "@theme/Tabs"; -import TabItem from "@theme/TabItem"; import Admonition from "@theme/Admonition"; +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; To quickly understand what you can do with Continue, check out each tab below. @@ -33,26 +33,29 @@ To quickly understand what you can do with Continue, check out each tab below. + - [Edit](../edit/how-to-use-it.md#how-to-use-it) is a convenient way to modify code without leaving your current file + [Edit](../edit/how-to-use-it.md#how-to-use-it) is a convenient way to modify code without leaving your current file - ![edit](/img/edit.gif) + ![edit](/img/edit.gif) + + + Learn more about [Edit](../edit/how-to-use-it.md#how-to-use-it) + + + + + + + [Agent](../agent/how-to-use-it.md#how-to-use-it) equips the Chat model with the tools needed to handle a wide range of coding tasks + + ![agent](/img/agent.gif) - Learn more about [Edit](../edit/how-to-use-it.md#how-to-use-it) + Learn more about [Agent](../agent/how-to-use-it.md#how-to-use-it) - - [Actions](../actions/how-to-use-it.md#how-to-use-it) are shortcuts for common use cases - - ![actions](/img/actions.gif) - - - Learn more about how to use [Actions](../actions/how-to-use-it.md#how-to-use-it) - - - diff --git a/docs/docs/hub/assistants/create-an-assistant.md b/docs/docs/hub/assistants/create-an-assistant.md index 207f1c955..62fdf666c 100644 --- a/docs/docs/hub/assistants/create-an-assistant.md +++ b/docs/docs/hub/assistants/create-an-assistant.md @@ -32,7 +32,6 @@ Choose a name, slug, description, and icon for your assistant. The easiest way to create an assistant is to click "Create assistant" with the default configuration and then add / remove blocks using the sidebar. -Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](../../yaml-reference.md#complete-yaml-config-example) docs for more details. +Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](../../reference.md#complete-yaml-config-example) docs for more details. ![New assistant YAML](/img/hub/assistant-create-yaml.png) - diff --git a/docs/docs/hub/blocks/block-types.md b/docs/docs/hub/blocks/block-types.md index 9091184d4..b9c5bbd13 100644 --- a/docs/docs/hub/blocks/block-types.md +++ b/docs/docs/hub/blocks/block-types.md @@ -11,45 +11,40 @@ sidebar_label: Types Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/explore/models). -Continue supports [many model providers](../../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](../../customize/model-roles). View [`models`](../../yaml-reference.md#models) in the YAML Reference for more details. +Continue supports [many model providers](../../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](../../customize/model-roles). View [`models`](../../reference.md#models) in the YAML Reference for more details. ## Context Context blocks define a context provider which can be referenced in Chat with `@` to pull in data from external sources such as files and folders, a URL, Jira or Confluence, and Github issues, among others. [Explore context provider blocks](https://hub.continue.dev/explore/context) on the hub. -Learn more about context providers [here](../../yaml-reference.md#context), and check out [this guide](../../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. The `config.yaml` spec for context can be found [`here`](../../yaml-reference.md#context). +Learn more about context providers [here](../../reference.md#context), and check out [this guide](../../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. The `config.yaml` spec for context can be found [`here`](../../reference.md#context). ## Docs Docs are blocks that point to documentation sites, which will be indexed locally and then can be referenced as context using @Docs in Chat. [Explore docs](https://hub.continue.dev/explore/docs) on the hub. -Learn more in the [@Docs deep dive](../../customize/deep-dives/docs.mdx), and view [`docs`](../../yaml-reference.md#docs) in the YAML Reference for more details. +Learn more in the [@Docs deep dive](../../customize/deep-dives/docs.mdx), and view [`docs`](../../reference.md#docs) in the YAML Reference for more details. ## MCP Servers Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks. [Explore MCP Servers](https://hub.continue.dev/explore/mcp) on the hub. -Learn more in the [Tools deep dive](../../customize/tools.mdx), and view [`mcpServers`](../../yaml-reference.md#mcpservers) in the YAML Reference for more details. +Learn more in the [MCP deep dive](../../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../../reference.md#mcpservers) in the YAML Reference for more details. ## Rules Rules blocks are instructions that your custom AI code assistant will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub. -Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and view [`rules`](../../yaml-reference.md#rules) in the YAML Reference for more details. +Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and view [`rules`](../../reference.md#rules) in the YAML Reference for more details. ## Prompts Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub. -Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). There are two important differences between prompt blocks and prompt files: - -1. Currently, prompt blocks cannot use context providers -2. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and - -The `config.yaml` spec for `prompts` can be found [here](../../yaml-reference.md#prompts). +Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts). ## Data Data blocks allow you send your development data to custom destinations of your choice. Development data can be used for a variety of purposes, including analyzing usage, gathering insights, or fine-tuning models. You can read more about development data [here](../../customize/deep-dives/development-data.md). Explore data block examples [here](https://hub.continue.dev/explore/data). -Data destinations are configured in the [`data`](../../yaml-reference.md#data) section of `config.yaml`. +Data destinations are configured in the [`data`](../../reference.md#data) section of `config.yaml`. diff --git a/docs/docs/hub/blocks/create-a-block.md b/docs/docs/hub/blocks/create-a-block.md index 870295c99..fcf12acfd 100644 --- a/docs/docs/hub/blocks/create-a-block.md +++ b/docs/docs/hub/blocks/create-a-block.md @@ -23,10 +23,10 @@ To create a block from scratch, you will need to click “New block” in the to ![New block button](/img/hub/block-new-button.png) -After filling out information on the block, you will want to create a block following the `config.yaml` [reference documentation](../../yaml-reference.md). Refer to examples of blocks on [hub.continue.dev](https://hub.continue.dev/explore/models) and visit the [YAML Reference](../../yaml-reference.md#complete-yaml-config-example) docs for more details. +After filling out information on the block, you will want to create a block following the `config.yaml` [reference documentation](../../reference.md). Refer to examples of blocks on [hub.continue.dev](https://hub.continue.dev/explore/models) and visit the [YAML Reference](../../reference.md#complete-yaml-config-example) docs for more details. ![New block page](/img/hub/block-new-page.png) ### Block inputs -Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant. \ No newline at end of file +Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant. diff --git a/docs/docs/hub/blocks/intro.md b/docs/docs/hub/blocks/intro.md index 919aa9f7d..69d0f9224 100644 --- a/docs/docs/hub/blocks/intro.md +++ b/docs/docs/hub/blocks/intro.md @@ -9,4 +9,4 @@ keywords: [blocks, introduction, basics] Blocks are the components you use to build a custom AI code assistant. These include [models](./block-types.md#models), [rules](./block-types.md#rules), [context providers](./block-types.md#context), [prompts](./block-types.md#prompts), [docs](./block-types.md#docs), [data destinations](./block-types.md#data), and [MCP servers](./block-types.md#mcp-servers). -Blocks follow the [`config.yaml`](../../yaml-reference.md) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant. +Blocks follow the [`config.yaml`](../../reference.md) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant. diff --git a/docs/docs/hub/governance/creating-an-org.md b/docs/docs/hub/governance/creating-an-org.md new file mode 100644 index 000000000..aa91d8f5e --- /dev/null +++ b/docs/docs/hub/governance/creating-an-org.md @@ -0,0 +1,20 @@ +--- +title: Creating an Organization +description: Creating an Organization +keywords: [governance, organization, org, create] +--- + +To Create an Organization, click the organization selector in the top right and select `Create Organization` + +![create an org selector](/img/hub/org-selector.png) + +1. Choose a name, which will be used as the display name for your organization throughout the hub +2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and assistant slugs +3. Select an icon for your organization using the image uploader +4. Finally, add a Biography, which will be displayed on your org Home Page + +![Creating an org](/img/hub/create-org-form.png) + +You will then be signed in to your org and taken to the org home page + +![Org home page](/img/hub/org-home-page.png) diff --git a/docs/docs/introduction.md b/docs/docs/introduction.md index 9628dd4cb..e8bd4269e 100644 --- a/docs/docs/introduction.md +++ b/docs/docs/introduction.md @@ -22,4 +22,4 @@ keywords: - [Chat](chat/how-to-use-it) to understand and iterate on code in the sidebar - [Autocomplete](autocomplete/how-to-use-it) to receive inline code suggestions as you type - [Edit](edit/how-to-use-it) to modify code without leaving your current file -- [Actions](actions/how-to-use-it) to establish shortcuts for common use cases +- [Agent](agent/how-to-use-it) to make more substantial changes to your codebase diff --git a/docs/docs/json-reference.md b/docs/docs/json-reference.md index 11e92a183..0fa8e2d25 100644 --- a/docs/docs/json-reference.md +++ b/docs/docs/json-reference.md @@ -5,7 +5,7 @@ keywords: [config, config_schema.json, json] --- :::info -`config.json` is the original Continue configuration format. The newer and preferred format is [`YAML Config`](./reference). See the [migration guide](./yaml-migration). +We recently introduced a new configuration format, `config.yaml`, to replace `config.json`. See the `config.yaml` reference and migration guide [here](./reference.md). ::: Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). @@ -14,7 +14,8 @@ Below are details for each property that can be set in `config.json`. The config ### `models` -Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it), [Edit](./edit/how-to-use-it), and [Actions](./actions/how-to-use-it). +Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md) and [VS Code actions](./customize/deep-dives/vscode-actions.md). + Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. **Properties:** @@ -36,7 +37,7 @@ Each model has specific configuration options tailored to its provider and funct - `engine`: Engine for Azure OpenAI requests. - `capabilities`: Override auto-detected capabilities: - `uploadImage`: Boolean indicating if the model supports image uploads. - - `tools`: Boolean indicating if the model supports tool calls. + - `tools`: Boolean indicating if the model supports tool use. _(AWS Only)_ @@ -59,7 +60,7 @@ Example: "contextLength": 128000, "title": "GPT-4o", "provider": "openai", - "apiKey": "" + "apiKey": "YOUR_API_KEY" } ] } @@ -97,7 +98,7 @@ Specifies options for tab autocompletion behavior. Example -````json title="config.json" +```json title="config.json" { "tabAutocompleteOptions": { "debounceDelay": 500, @@ -105,6 +106,7 @@ Example "disableInFiles": ["*.md"] } } +``` ### `embeddingsProvider` @@ -117,8 +119,8 @@ Embeddings model settings - the model used for @Codebase and @docs. - `apiKey`: API key for the provider. - `apiBase`: Base URL for API requests. - `requestOptions`: Additional HTTP request settings specific to the embeddings provider. -- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. -- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. +- `maxEmbeddingChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxEmbeddingBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. (AWS ONLY) @@ -132,12 +134,12 @@ Example: "embeddingsProvider": { "provider": "openai", "model": "text-embedding-ada-002", - "apiKey": "", - "maxChunkSize": 256, - "maxBatchSize": 5 + "apiKey": "", + "maxEmbeddingChunkSize": 256, + "maxEmbeddingBatchSize": 5 } } -```` +``` ### `completionOptions` @@ -150,7 +152,7 @@ Parameters that control the behavior of text generation and completion settings. - `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. - `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. - `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. -- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. +- `frequencyPenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. - `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). - `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. - `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). @@ -220,7 +222,7 @@ Example "name": "voyage", "params": { "model": "rerank-2", - "apiKey": "" + "apiKey": "" } } } @@ -234,23 +236,21 @@ List of documentation sites to index. - `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs -- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -- `maxDepth`: Maximum depth for crawling. Default `3` + +- `maxDepth`: Maximum link depth for crawling. Default `4` - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). +- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. Example ```json title="config.json" -{ - "docs": [ +"docs": [ { - "title": "Continue", - "startUrl": "https://docs.continue.dev/intro", - "rootUrl": "https://docs.continue.dev", - "faviconUrl": "https://docs.continue.dev/favicon.ico" - } - ] -} + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] ``` ### `slashCommands` @@ -261,9 +261,106 @@ Custom commands initiated by typing "/" in the sidebar. Commands include predefi - `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". - `description`: Brief description of the command. -- `step`: Used for built-in commands; set the name for pre-configured options. +- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. - `params`: Additional parameters to configure command behavior (command-specific - see code for command) +The following commands are built-in and can be added to `config.json` to make them visible: + +#### `/share` + +Generate a shareable markdown transcript of your current chat history. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "share", + "description": "Export the current chat session to markdown", + "params": { "outputDir": "~/.continue/session-transcripts" } + } + ] +} +``` + +Use the `outputDir` parameter to specify where you want to the markdown file to be saved. + +#### `/cmd` + +Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +#### `/commit` + +Shows the LLM your current git diff and asks it to generate a commit message. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message for the current changes" + } + ] +} +``` + +#### `/http` + +Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "http", + "description": "Does something custom", + "params": { "url": "" } + } + ] +} +``` + +#### `/issue` + +Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "issue", + "description": "Generate a link to a drafted GitHub issue", + "params": { "repositoryUrl": "https://github.com/continuedev/continue" } + } + ] +} +``` + +#### `/onboard` + +The onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture. + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "onboard", + "description": "Familiarize yourself with the codebase" + } + ] +} +``` + Example: ```json title="config.json" @@ -285,6 +382,8 @@ Example: } ``` +You can also add your own slash command by following [this tutorial](./customize/tutorials/build-your-own-slash-command.md). + ### `customCommands` User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. @@ -343,40 +442,6 @@ Example } ``` -### `disableSessionTitles` - -Prevents generating summary titles for each chat session when set to `true`. - -### `ui` - -Customizable UI settings to control interface appearance and behavior. - -**Properties:** - -- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. -- `fontSize`: Specifies font size for UI elements. -- `displayRawMarkdown`: If `true`, shows raw markdown in responses. -- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. -- `codeWrap`: If `true`, enables text wrapping in code blocks. - -Example: - -```json title="config.json" -{ - "ui": { - "codeBlockToolbarPosition": "bottom", - "fontSize": 14, - "displayRawMarkdown": false, - "showChatScrollbar": false, - "codeWrap": false - } -} -``` - -### `allowAnonymousTelemetry` - -When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. - ### `userToken` An optional token that identifies the user, primarily for authenticated services. @@ -437,3 +502,28 @@ Example } } ``` + +### Fully deprecated settings + +Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/deep-dives/settings.md). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`. + +- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`). +- `promptPath`: This value will override during migration. +- `disableIndexing`: This value will be migrated to the safest merged value (`true` if either are `true`). +- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false +- `tabAutocompleteOptions` + - `useCache`: This value will override during migration. + - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) + - `multilineCompletions`: This value will override during migration. +- `experimental` + - `useChromiumForDocsCrawling`: This value will override during migration. + - `readResponseTTS`: This value will override during migration. +- `ui` - all will override during migration + + - `codeBlockToolbarPosition` + - `fontSize` + - `codeWrap` + - `displayRawMarkdown` + - `showChatScrollbar` + + See [User Settings Page](./customize/deep-dives/settings.md) for more information about each option. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 143fec98b..757cfa13e 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -1,231 +1,278 @@ --- -title: config.json Reference -description: Reference for the Continue _config.json_ configuration file -keywords: [config, config_schema.json, json] +title: Config YAML Reference +description: Reference for the Continue configuration YAML file +keywords: [config, yaml, configuration, customize, customization] --- +# config.yaml Reference + +## Introduction + +Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded from [the Hub](https://hub.continue.dev/explore/assistants) or locally + +- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to the extension +- Locally + - in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`. The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml` + - in your workspace in a `/.continue/assistants` folder, with the same naming convention + :::info -We recently introduced a new configuration format, `config.yaml`, to replace `config.json`. See the `config.yaml` reference and migration guide [here](./yaml-reference.md). +Config YAML replaces [`config.json`](./json-reference.md), which is deprecated. View the **[Migration Guide](./yaml-migration.md)**. ::: -Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). +An assistant is made up of: -**All properties at all levels are optional unless explicitly marked required** +1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant +2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers. + +A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. + +Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants). + +Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. + +### Using Blocks + +Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization. + +Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. + +:::info +Note that local assistants cannot use blocks that require organization-level secrets. +::: + +For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one. + +```yaml title="Assistant models section" +models: + - uses: anthropic/claude-3.5-sonnet # an imported model block + - model: deepseek-reasoner # an explicit model block + provider: ollama +``` + +### Inputs + +Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: + +```yaml title="Block config.yaml" +name: myprofile/custom-model +models: + - name: My Favorite Model + provider: anthropic + apiKey: ${{ inputs.ANTHROPIC_API_KEY }} + defaultCompletionOptions: + temperature: ${{ inputs.TEMP }} +``` + +Which can then be imported like + +```yaml title="Assistant config.yaml" +name: myprofile/custom-assistant +models: + - uses: myprofile/custom-model + with: + ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} + TEMP: 0.9 +``` + +Note that hub secrets can be passed as inputs, using the a similar mustache format: `secrets.SECRET_NAME`. + +### Overrides + +Block properties can be also be directly overriden using `override`. For example: + +```yaml title="Assistant config.yaml" +name: myprofile/custom-assistant +models: + - uses: myprofile/custom-model + with: + ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} + TEMP: 0.9 + override: + roles: + - chat +``` + +## Properties + +Below are details for each property that can be set in `config.yaml`. + +**All properties at all levels are optional unless explicitly marked as required.** + +The top-level properties in the `config.yaml` configuration file are: + +- [`name`](#name) (**required**) +- [`version`](#version) (**required**) +- [`schema`](#schema) (**required**) +- [`models`](#models) +- [`context`](#context) +- [`rules`](#rules) +- [`prompts`](#prompts) +- [`docs`](#docs) +- [`mcpServers`](#mcpservers) +- [`data`](#data) + +--- + +### `name` + +The `name` property specifies the name of your project or configuration. + +```yaml title="config.yaml" +name: MyProject +``` + +--- + +### `version` + +The `version` property specifies the version of your project or configuration. + +### `schema` + +The `schema` property specifies the schema version used for the `config.yaml`, e.g. `v1` + +--- ### `models` -Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md). -Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. +The `models` section defines the language models used in your configuration. Models are used for functionalities such as chat, editing, and summarizing. **Properties:** -- `title` (**required**): The title to assign to your model, shown in dropdowns, etc. -- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, `xAI`, etc., see IntelliJ suggestions. -- `model` (**required**): The name of the model, used for prompt template auto-detection. Use `AUTODETECT` special name to get all available models. -- `apiKey`: API key required by providers like OpenAI, Anthropic, Cohere, and xAI. -- `apiBase`: The base URL of the LLM API. -- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048). -- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. -- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions. -- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt). -- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override. -- `systemMessage`: A system message that will precede responses from the LLM. -- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override. -- `apiType`: Specifies the type of API (`openai` or `azure`). -- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`). -- `engine`: Engine for Azure OpenAI requests. -- `capabilities`: Override auto-detected capabilities: - - `uploadImage`: Boolean indicating if the model supports image uploads. - - `tools`: Boolean indicating if the model supports tool use. +- `name` (**required**): A unique name to identify the model within your configuration. +- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). +- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). +- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. +- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. +- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: -_(AWS Only)_ + - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. + - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. -- `profile`: AWS security profile for authorization. -- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider). -- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`). +- `defaultCompletionOptions`: Default completion options for model settings. -Example: + **Properties:** -```json title="config.json" -{ - "models": [ - { - "title": "Ollama", - "provider": "ollama", - "model": "AUTODETECT" - }, - { - "model": "gpt-4o", - "contextLength": 128000, - "title": "GPT-4o", - "provider": "openai", - "apiKey": "YOUR_API_KEY" - } - ] -} + - `contextLength`: Maximum context length of the model, typically in tokens. + - `maxTokens`: Maximum number of tokens to generate in a completion. + - `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random). + - `topP`: The cumulative probability for nucleus sampling. + - `topK`: Maximum number of tokens considered at each step. + - `stop`: An array of stop tokens that will terminate the completion. + - `n`: Number of completions to generate. + +- `requestOptions`: HTTP request options specific to the model. + + **Properties:** + + - `timeout`: Timeout for each request to the language model. + - `verifySsl`: Whether to verify SSL certificates for requests. + - `caBundlePath`: Path to a custom CA bundle for HTTP requests. + - `proxy`: Proxy URL for HTTP requests. + - `headers`: Custom headers for HTTP requests. + - `extraBodyProperties`: Additional properties to merge with the HTTP request body. + - `noProxy`: List of hostnames that should bypass the specified proxy. + - `clientCertificate`: Client certificate for HTTP requests. + - `cert`: Path to the client certificate file. + - `key`: Path to the client certificate key file. + - `passphrase`: Optional passphrase for the client certificate key file. + +#### Example: + +```yaml title="config.yaml" +models: + - name: GPT-4o + provider: openai + model: gpt-4o + roles: + - chat + - edit + - apply + defaultCompletionOptions: + temperature: 0.7 + maxTokens: 1500 + + - name: Codestral + provider: mistral + model: codestral-latest + roles: + - autocomplete + + - name: My Model - OpenAI-Compatible + provider: openai + apiBase: http://my-endpoint/v1 + model: my-custom-model + capabilities: + - tool_use + - image_input + roles: + - chat + - edit ``` -### `tabAutocompleteModel` +--- -Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model. +### `context` + +The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters. + +More information about usage/params for each context provider can be found [here](/customize/context-providers.mdx) + +**Properties:** + +- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). +- `params`: Optional parameters to configure the context provider's behavior. + +**Example:** + +```yaml title="config.yaml" +context: + - provider: file + - provider: code + - provider: codebase + params: + nFinal: 10 + - provider: docs + - provider: diff + - provider: folder + - provider: terminal +``` + +--- + +### `rules` + +List of rules that the LLM should follow. These are inserted into the system message for all chat requests. Example -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "My Starcoder", - "provider": "ollama", - "model": "starcoder2:3b" - } -} +```yaml title="config.yaml" +rules: + - uses: myprofile/my-mood-setter + with: + MOOD: happy + - Always annotate Python functions with their parameter and return types + - Always write Google style docstrings for functions and classes ``` -### `tabAutocompleteOptions` +--- -Specifies options for tab autocompletion behavior. +### `prompts` -**Properties:** +A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. -- `disable`: If `true`, disables tab autocomplete (default: `false`). -- `maxPromptTokens`: Maximum number of tokens for the prompt (default: `1024`). -- `debounceDelay`: Delay (in ms) before triggering autocomplete (default: `350`). -- `maxSuffixPercentage`: Maximum percentage of prompt for suffix (default: `0.2`). -- `prefixPercentage`: Percentage of input for prefix (default: `0.3`). -- `template`: Template string for autocomplete, using Mustache templating. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. -- `onlyMyCode`: If `true`, only includes code within the repository (default: `true`). - -Example - -```json title="config.json" -{ - "tabAutocompleteOptions": { - "debounceDelay": 500, - "maxPromptTokens": 1500, - "disableInFiles": ["*.md"] - } -} +```yaml title="config.yaml" +prompts: + - name: check + description: Check for mistakes in my code + prompt: | + Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: + - Syntax errors + - Logic errors + - Security vulnerabilities ``` -### `embeddingsProvider` - -Embeddings model settings - the model used for @Codebase and @docs. - -**Properties:** - -- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `gemini`, etc -- `model`: Model name for embeddings. -- `apiKey`: API key for the provider. -- `apiBase`: Base URL for API requests. -- `requestOptions`: Additional HTTP request settings specific to the embeddings provider. -- `maxEmbeddingChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. -- `maxEmbeddingBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. - -(AWS ONLY) - -- `region`: Specifies the region hosting the model. -- `profile`: AWS security profile. - -Example: - -```json title="config.json" -{ - "embeddingsProvider": { - "provider": "openai", - "model": "text-embedding-ada-002", - "apiKey": "", - "maxEmbeddingChunkSize": 256, - "maxEmbeddingBatchSize": 5 - } -} -``` - -### `completionOptions` - -Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_. - -**Properties:** - -- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`). -- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs. -- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. -- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. -- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. -- `frequencyPenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. -- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). -- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. -- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). -- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. -- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). -- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. - -Example - -```json title="config.json" -{ - "completionOptions": { - "stream": false, - "temperature": 0.5 - } -} -``` - -### `requestOptions` - -Default HTTP request options that apply to all models and context providers, unless overridden at the model level. - -**Properties:** - -- `timeout`: Timeout for each request to the LLM (default: 7200 seconds). -- `verifySsl`: Whether to verify SSL certificates for requests. -- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths) -- `proxy`: Proxy URL to use for HTTP requests. -- `headers`: Custom headers for HTTP requests. -- `extraBodyProperties`: Additional properties to merge with the HTTP request body. -- `noProxy`: List of hostnames that should bypass the specified proxy. -- `clientCertificate`: Client certificate for HTTP requests. - - - `cert`: Path to the client certificate file. - - `key`: Path to the client certificate key file. - - `passphrase`: Optional passphrase for the client certificate key file. - -Example - -```json title="config.json" -{ - "requestOptions": { - "headers": { - "X-Auth-Token": "xxx" - } - } -} -``` - -### `reranker` - -Configuration for the reranker model used in response ranking. - -**Properties:** - -- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `huggingface-tei`, `bedrock` -- `params`: - - `model`: Model name - - `apiKey`: Api key - - `region`: Region (for Bedrock only) - -Example - -```json title="config.json" -{ - "reranker": { - "name": "voyage", - "params": { - "model": "rerank-2", - "apiKey": "" - } - } -} -``` +--- ### `docs` @@ -233,7 +280,7 @@ List of documentation sites to index. **Properties:** -- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. +- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs - `maxDepth`: Maximum link depth for crawling. Default `4` @@ -242,188 +289,193 @@ List of documentation sites to index. Example -```json title="config.json" -"docs": [ - { - "title": "Continue", - "startUrl": "https://docs.continue.dev/intro", - "faviconUrl": "https://docs.continue.dev/favicon.ico", - } -] +```yaml title="config.yaml" +docs: + - name: Continue + startUrl: https://docs.continue.dev/intro + favicon: https://docs.continue.dev/favicon.ico ``` -### `slashCommands` +--- -Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined. +### `mcpServers` + + + +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. **Properties:** -- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". -- `description`: Brief description of the command. -- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. -- `params`: Additional parameters to configure command behavior (command-specific - see code for command) +- `name` (**required**): The name of the MCP server. +- `command` (**required**): The command used to start the server. +- `args`: An optional array of arguments for the command. +- `env`: An optional map of environment variables for the server process. -Example: +**Example:** -```json title="config.json" -{ - "slashCommands": [ - { - "name": "commit", - "description": "Generate a commit message" - }, - { - "name": "share", - "description": "Export this session as markdown" - }, - { - "name": "cmd", - "description": "Generate a shell command" - } - ] -} +```yaml title="config.yaml" +mcpServers: + - name: My MCP Server + command: uvx + args: + - mcp-server-sqlite + - --db-path + - /Users/NAME/test.db ``` -### `customCommands` +### `data` -User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. +Destinations to which [development data](./customize/deep-dives/development-data.md) will be sent. **Properties:** -- `name`: The name of the custom command. -- `prompt`: Text prompt for the command. -- `description`: Brief description explaining the command's function. +- `name` (**required**): The display name of the data destination +- `destination` (**required**): The destination/endpoint that will receive the data. Can be: + - an HTTP endpoint that will receive a POST request with a JSON blob + - a file URL to a directory in which events will be dumpted to `.jsonl` files +- `schema` (**required**): the schema version of the JSON blobs to be sent +- `events`: an array of event names to include. Defaults to all events if not specified. +- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file contents, prompts, and completions. Defaults to `all` +- `apiKey`: api key to be sent with request (Bearer header) +- `requestOptions`: Options for event POST requests. Same format as [model requestOptions](#models). -Example: + **Example:** -```json title="config.json" -{ - "customCommands": [ - { - "name": "test", - "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - "description": "Write unit tests for highlighted code" - } - ] -} +```yaml title="config.yaml" +data: + - name: Local Data Bank + destination: file:///Users/dallin/Documents/code/continuedev/continue-extras/external-data + schema: 0.2.0 + level: all + - name: My Private Company + destination: https://mycompany.com/ingest + schema: 0.2.0 + level: noCode + events: + - autocomplete + - chatInteraction ``` -### `contextProviders` +--- -List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`. +## Complete YAML Config Example -**Properties:** +Putting it all together, here's a complete example of a `config.yaml` configuration file: -- `name`: Name of the context provider, e.g. `docs` or `web` -- `params`: A context-provider-specific record of params to configure the context behavior +```yaml title="config.yaml" +name: MyProject +version: 0.0.1 +schema: v1 -Example +models: + - uses: anthropic/claude-3.5-sonnet + with: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + override: + defaultCompletionOptions: + temperature: 0.8 + - name: GPT-4 + provider: openai + model: gpt-4 + roles: + - chat + - edit + defaultCompletionOptions: + temperature: 0.5 + maxTokens: 2000 + requestOptions: + headers: + Authorization: Bearer YOUR_OPENAI_API_KEY -```json title="config.json" -{ - "contextProviders": [ - { - "name": "code", - "params": {} - }, - { - "name": "docs", - "params": {} - }, - { - "name": "diff", - "params": {} - }, - { - "name": "open", - "params": {} - } - ] -} + - name: Ollama Starcoder + provider: ollama + model: starcoder + roles: + - autocomplete + defaultCompletionOptions: + temperature: 0.3 + stop: + - "\n" + +rules: + - Give concise responses + - Always assume TypeScript rather than JavaScript + +prompts: + - name: test + description: Unit test a function + prompt: | + Please write a complete suite of unit tests for this function. You should use the Jest testing framework. The tests should cover all possible edge cases and should be as thorough as possible. You should also include a description of each test case. + - uses: myprofile/my-favorite-prompt + +context: + - provider: diff + - provider: file + - provider: codebase + - provider: code + - provider: docs + params: + startUrl: https://docs.example.com/introduction + rootUrl: https://docs.example.com + maxDepth: 3 + +mcpServers: + - name: DevServer + command: npm + args: + - run + - dev + env: + PORT: "3000" + +data: + - name: My Private Company + destination: https://mycompany.com/ingest + schema: 0.2.0 + level: noCode + events: + - autocomplete + - chatInteraction ``` -### `userToken` +## Using YAML anchors to avoid config duplication -An optional token that identifies the user, primarily for authenticated services. +You can also use node anchors to avoid duplication of properties. To do so, +adding the YAML version header `%YAML 1.1` is needed, here's an example of +a `config.yaml` configuration file using anchors: -### `systemMessage` +```yaml title="config.yaml" +%YAML 1.1 +--- +name: MyProject +version: 0.0.1 +schema: v1 -Defines a system message that appears before every response from the language model, providing guidance or context. +model_defaults: &model_defaults + provider: openai + apiKey: my-api-key + apiBase: https://api.example.com/llm -### `experimental` +models: + - name: mistral + <<: *model_defaults + model: mistral-7b-instruct + roles: + - chat + - edit -Several experimental config parameters are available, as described below: + - name: qwen2.5-coder-7b-instruct + <<: *model_defaults + model: qwen2.5-coder-7b-instruct + roles: + - chat + - edit -`experimental`: - -- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= -- `modelRoles`: - - `inlineEdit`: Model title for inline edits. - - `applyCodeBlock`: Model title for applying code blocks. - - `repoMapFileSelection`: Model title for repo map selections. -- `quickActions`: Array of custom quick actions - - `title` (**required**): Display title for the quick action. - - `prompt` (**required**): Prompt for quick action. - - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. -- `contextMenuPrompts`: - - `comment`: Prompt for commenting code. - - `docstring`: Prompt for adding docstrings. - - `fix`: Prompt for fixing code. - - `optimize`: Prompt for optimizing code. -- `modelContextProtocolServers`: See [Model Context Protocol](/customize/context-providers#model-context-protocol) - -Example - -```json title="config.json" -{ - "experimental": { - "modelRoles": { - "inlineEdit": "Edit Model" - }, - "quickActions": [ - { - "title": "Tags", - "prompt": "Return a list of any function and class names from the included code block", - "sendToChat": true - } - ], - "contextMenuPrompts": { - "fixGrammar": "Fix grammar in the above but allow for typos." - }, - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } - } - ] - } -} + - name: qwen2.5-coder-7b + <<: *model_defaults + model: qwen2.5-coder-7b + env: + useLegacyCompletionsEndpoint: false + roles: + - autocomplete ``` - -### Fully deprecated settings - -Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. - -- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`). -- `promptPath`: This value will override during migration. -- `disableIndexing`: This value will be migrated to the safest merged value (`true` if either are `true`). -- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false -- `tabAutocompleteOptions` - - `useCache`: This value will override during migration. - - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) - - `multilineCompletions`: This value will override during migration. -- `experimental` - - `useChromiumForDocsCrawling`: This value will override during migration. - - `readResponseTTS`: This value will override during migration. -- `ui` - all will override during migration - - - `codeBlockToolbarPosition` - - `fontSize` - - `codeWrap` - - `displayRawMarkdown` - - `showChatScrollbar` - - See [User Settings Page](./customize/settings.md) for more information about each option. diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index e21a93164..2383b6242 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -26,6 +26,6 @@ The following usage information is collected and reported: ## How to Opt Out -You can disable anonymous telemetry by visiting the [User Settings Page](./customize/settings.md) and toggling "Allow Anonymous Telemetry" off. +You can disable anonymous telemetry by visiting the [User Settings Page](./customize/deep-dives/settings.md) and toggling "Allow Anonymous Telemetry" off. Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut ctrl + , on Windows/Linux or cmd + , on macOS). diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index ec189e429..82df8edd2 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -12,7 +12,7 @@ See also - [Intro to YAML](https://yaml.org/) - [JSON Continue Config Reference](/json-reference) -- [YAML Continue Config Reference](/yaml-reference) +- [YAML Continue Config Reference](/reference) ## Create YAML file @@ -38,9 +38,9 @@ Add all model configurations in `config.json`, including models in `models`, `ta - `inlineEdit` -> e.g. `roles: [chat, edit]` - `applyCodeBlock` -> e.g. `roles: [chat, apply]` -Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions) +Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](./reference.md#models) -Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions) +Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](./reference.md#models) @@ -327,9 +327,9 @@ mcpServers: ## Deprecated configuration options -Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md) (Gear Icon). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. +Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/deep-dives/settings.md) (Gear Icon). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`. -See the [JSON Config Reference](./reference#fully-deprecated-settings) for more information on fully deprecated options. +See the [JSON Config Reference](./json-reference#fully-deprecated-settings) for more information on fully deprecated options. The following top-level fields from `config.json` still work when using `config.json` but have been deprecated and don't have a YAML equivalent: diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md deleted file mode 100644 index 2039c3887..000000000 --- a/docs/docs/yaml-reference.md +++ /dev/null @@ -1,500 +0,0 @@ ---- -title: Config YAML Reference -description: Reference for the Continue configuration YAML file -keywords: [config, yaml, configuration, customize, customization] ---- - -# config.yaml Reference - -## Introduction - -Continue hub assistants are defined using the `config.yaml` specification. Local assistants can also be configured using a YAML file `config.yaml` placed in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) - -:::info -Config YAML replaces `config.json`. View the **[Migration Guide](/yaml-migration)**. -::: - -An assistant is made up of: - -1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant -2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers. - -A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. - -Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants). - -Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. - -### Using Blocks - -Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization. - -Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. - -:::info -Note that `uses` blocks cannot be used with a local `config.yaml` -::: - -For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one. - -```yaml title="Assistant models section" -models: - - uses: anthropic/claude-3.5-sonnet # an imported model block - - model: deepseek-reasoner # an explicit model block - provider: ollama -``` - -### Inputs - -Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: - -```yaml title="Block config.yaml" -name: myprofile/custom-model -models: - - name: My Favorite Model - provider: anthropic - apiKey: ${{ inputs.ANTHROPIC_API_KEY }} - defaultCompletionOptions: - temperature: ${{ inputs.TEMP }} -``` - -Which can then be imported like - -```yaml title="Assistant config.yaml" -name: myprofile/custom-assistant -models: - - uses: myprofile/custom-model - with: - ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} - TEMP: 0.9 -``` - -Note that hub secrets can be passed as inputs, using the a similar mustache format: `secrets.SECRET_NAME`. - -### Overrides - -Block properties can be also be directly overriden using `override`. For example: - -```yaml title="Assistant config.yaml" -name: myprofile/custom-assistant -models: - - uses: myprofile/custom-model - with: - ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }} - TEMP: 0.9 - override: - roles: - - chat -``` - -## Properties - -Below are details for each property that can be set in `config.yaml`. - -**All properties at all levels are optional unless explicitly marked as required.** - -The top-level properties in the `config.yaml` configuration file are: - -- [`name`](#name) (**required**) -- [`version`](#version) (**required**) -- [`schema`](#schema) (**required**) -- [`models`](#models) -- [`context`](#context) -- [`rules`](#rules) -- [`prompts`](#prompts) -- [`docs`](#docs) -- [`mcpServers`](#mcpservers) -- [`data`](#data) - ---- - -### `name` - -The `name` property specifies the name of your project or configuration. - -```yaml title="config.yaml" -name: MyProject -``` - ---- - -### `version` - -The `version` property specifies the version of your project or configuration. - -### `schema` - -The `schema` property specifies the schema version used for the `config.yaml`, e.g. `v1` - ---- - -### `models` - -The `models` section defines the language models used in your configuration. Models are used for functionalities such as chat, editing, and summarizing. - -**Properties:** - -- `name` (**required**): A unique name to identify the model within your configuration. -- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). -- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). -- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. -- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. -- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: - - - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. - - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. - -- `defaultCompletionOptions`: Default completion options for model settings. - - **Properties:** - - - `contextLength`: Maximum context length of the model, typically in tokens. - - `maxTokens`: Maximum number of tokens to generate in a completion. - - `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random). - - `topP`: The cumulative probability for nucleus sampling. - - `topK`: Maximum number of tokens considered at each step. - - `stop`: An array of stop tokens that will terminate the completion. - - `n`: Number of completions to generate. - -- `requestOptions`: HTTP request options specific to the model. - - **Properties:** - - - `timeout`: Timeout for each request to the language model. - - `verifySsl`: Whether to verify SSL certificates for requests. - - `caBundlePath`: Path to a custom CA bundle for HTTP requests. - - `proxy`: Proxy URL for HTTP requests. - - `headers`: Custom headers for HTTP requests. - - `extraBodyProperties`: Additional properties to merge with the HTTP request body. - - `noProxy`: List of hostnames that should bypass the specified proxy. - - `clientCertificate`: Client certificate for HTTP requests. - - `cert`: Path to the client certificate file. - - `key`: Path to the client certificate key file. - - `passphrase`: Optional passphrase for the client certificate key file. - -#### Example: - -```yaml title="config.yaml" -models: - - name: GPT-4o - provider: openai - model: gpt-4o - roles: - - chat - - edit - - apply - defaultCompletionOptions: - temperature: 0.7 - maxTokens: 1500 - - - name: Codestral - provider: mistral - model: codestral-latest - roles: - - autocomplete - - - name: My Model - OpenAI-Compatible - provider: openai - apiBase: http://my-endpoint/v1 - model: my-custom-model - capabilities: - - tool_use - - image_input - roles: - - chat - - edit -``` - ---- - -### `context` - -The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters. - -More information about usage/params for each context provider can be found [here](/customize/context-providers.mdx) - -**Properties:** - -- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). -- `params`: Optional parameters to configure the context provider's behavior. - -**Example:** - -```yaml title="config.yaml" -context: - - provider: files - - provider: code - - provider: codebase - params: - nFinal: 10 - - provider: docs - - provider: diff - - provider: folder - - provider: terminal -``` - ---- - -### `rules` - -List of rules that the LLM should follow. These are inserted into the system message for all chat requests. - -Example - -```yaml title="config.yaml" -rules: - - uses: myprofile/my-mood-setter - with: - MOOD: happy - - Always annotate Python functions with their parameter and return types - - Always write Google style docstrings for functions and classes -``` - ---- - -### `prompts` - -A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. - -```yaml title="config.yaml" -prompts: - - name: check - description: Check for mistakes in my code - prompt: | - Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: - - Syntax errors - - Logic errors - - Security vulnerabilities -``` - ---- - -### `docs` - -List of documentation sites to index. - -**Properties:** - -- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. -- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs - -- `maxDepth`: Maximum link depth for crawling. Default `4` -- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). -- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. - -Example - -```yaml title="config.yaml" -docs: - - name: Continue - startUrl: https://docs.continue.dev/intro - favicon: https://docs.continue.dev/favicon.ico -``` - ---- - -### `mcpServers` - - - -The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. - -**Properties:** - -- `name` (**required**): The name of the MCP server. -- `command` (**required**): The command used to start the server. -- `args`: An optional array of arguments for the command. -- `env`: An optional map of environment variables for the server process. - -**Example:** - -```yaml title="config.yaml" -mcpServers: - - name: My MCP Server - command: uvx - args: - - mcp-server-sqlite - - --db-path - - /Users/NAME/test.db -``` - -### `data` - -Destinations to which [development data](./customize/deep-dives/development-data.md) will be sent. - -**Properties:** - -- `name` (**required**): The display name of the data destination -- `destination` (**required**): The destination/endpoint that will receive the data. Can be: - - an HTTP endpoint that will receive a POST request with a JSON blob - - a file URL to a directory in which events will be dumpted to `.jsonl` files -- `schema` (**required**): the schema version of the JSON blobs to be sent -- `events`: an array of event names to include. Defaults to all events if not specified. -- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file contents, prompts, and completions. Defaults to `all` -- `apiKey`: api key to be sent with request (Bearer header) -- `requestOptions`: Options for event POST requests. Same format as [model requestOptions](#models). - - **Example:** - -```yaml title="config.yaml" -data: - - name: Local Data Bank - destination: file:///Users/dallin/Documents/code/continuedev/continue-extras/external-data - schema: 0.2.0 - level: all - - name: My Private Company - destination: https://mycompany.com/ingest - schema: 0.2.0 - level: noCode - events: - - autocomplete - - chatInteraction -``` - ---- - -## Complete YAML Config Example - -Putting it all together, here's a complete example of a `config.yaml` configuration file: - -```yaml title="config.yaml" -name: MyProject -version: 0.0.1 -schema: v1 - -models: - - uses: anthropic/claude-3.5-sonnet - with: - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - override: - defaultCompletionOptions: - temperature: 0.8 - - name: GPT-4 - provider: openai - model: gpt-4 - roles: - - chat - - edit - defaultCompletionOptions: - temperature: 0.5 - maxTokens: 2000 - requestOptions: - headers: - Authorization: Bearer YOUR_OPENAI_API_KEY - - - name: Ollama Starcoder - provider: ollama - model: starcoder - roles: - - autocomplete - defaultCompletionOptions: - temperature: 0.3 - stop: - - "\n" - -rules: - - Give concise responses - - Always assume TypeScript rather than JavaScript - -prompts: - - name: test - description: Unit test a function - prompt: | - Please write a complete suite of unit tests for this function. You should use the Jest testing framework. The tests should cover all possible edge cases and should be as thorough as possible. You should also include a description of each test case. - - uses: myprofile/my-favorite-prompt - -context: - - provider: diff - - provider: file - - provider: codebase - - provider: code - - provider: docs - params: - startUrl: https://docs.example.com/introduction - rootUrl: https://docs.example.com - maxDepth: 3 - -mcpServers: - - name: DevServer - command: npm - args: - - run - - dev - env: - PORT: "3000" - -data: - - name: My Private Company - destination: https://mycompany.com/ingest - schema: 0.2.0 - level: noCode - events: - - autocomplete - - chatInteraction -``` - -## Using YAML anchors to avoid config duplication - -You can also use node anchors to avoid duplication of properties. To do so, -adding the YAML version header `%YAML 1.1` is needed, here's an example of -a `config.yaml` configuration file using anchors: - -```yaml title="config.yaml" -%YAML 1.1 ---- -name: MyProject -version: 0.0.1 -schema: v1 - -model_defaults: &model_defaults - provider: openai - apiKey: my-api-key - apiBase: https://api.example.com/llm - -models: - - name: mistral - <<: *model_defaults - model: mistral-7b-instruct - roles: - - chat - - edit - - - name: qwen2.5-coder-7b-instruct - <<: *model_defaults - model: qwen2.5-coder-7b-instruct - roles: - - chat - - edit - - - name: qwen2.5-coder-7b - <<: *model_defaults - model: qwen2.5-coder-7b - useLegacyCompletionsEndpoint: false - roles: - - autocomplete -``` - -### Fully deprecated settings - -Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. - -- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`). -- `promptPath`: This value will override during migration. -- `disableIndexing`: This value will be migrated to the safest merged value (`true` if either are `true`). -- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false -- `tabAutocompleteOptions` - - `useCache`: This value will override during migration. - - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) - - `multilineCompletions`: This value will override during migration. -- `experimental` - - `useChromiumForDocsCrawling`: This value will override during migration. - - `readResponseTTS`: This value will override during migration. -- `ui` - all will override during migration - - - `codeBlockToolbarPosition` - - `fontSize` - - `codeWrap` - - `displayRawMarkdown` - - `showChatScrollbar` - - See [User Settings Page](./customize/settings.md) for more information about each option. diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c8d987266..06e717ad7 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -93,6 +93,13 @@ const config = { label: "User Guide", href: "/", }, + { + type: "docSidebar", + sidebarId: "hubSidebar", + position: "left", + label: "Hub", + href: "/hub/introduction", + }, { type: "docSidebar", sidebarId: "customizingSidebar", @@ -107,13 +114,7 @@ const config = { label: "Reference", href: "/reference", }, - { - type: "docSidebar", - sidebarId: "hubSidebar", - position: "left", - label: "Hub", - href: "/hub/introduction", - }, + { to: "https://github.com/continuedev/continue", label: "GitHub", @@ -222,20 +223,20 @@ const config = { }, { to: "/customize/overview", - from: "/customize", + from: ["/customize", "/customization"], }, { - to: "/customize/overview", - from: "/customization", + to: "/customize/deep-dives/mcp", + from: "/customize/tools", }, { to: "/getting-started/install", from: ["/install/vscode", "/install/jetbrains"], }, - // { - // to: "/getting-started/install", - // from: "/getting-started", - // }, + { + to: "/customize/deep-dives/settings", + from: "/customize/settings", + }, { to: "/customize/model-roles", from: ["/customize/model-types", "/setup/overview"], @@ -285,12 +286,27 @@ const config = { ], }, { - to: "/customize/deep-dives/prompt-files", + to: "/customize/deep-dives/prompts", from: ["/walkthroughs/prompt-files", "/features/prompt-files"], }, + // TODO - actions redirects { - to: "/actions/how-to-use-it#quick-actions", - from: "/walkthroughs/quick-actions", + to: "/customize/deep-dives/slash-commands", + from: [ + "/actions/how-to-use-it", + "/actions/how-to-customize", + "/actions", + "/actions/model-setup", + "/actions/context-selection", + "/actions/how-it-works", + "/customize/slash-commands", + "/customization/slash-commands", + ], + }, + + { + to: "/customize/deep-dives/vscode-actions", + from: ["/walkthroughs/quick-actions"], }, { to: "/customize/changelog", @@ -298,7 +314,11 @@ const config = { }, { to: "/reference", - from: ["/customization/code-config", "/reference/config"], + from: [ + "/customization/code-config", + "/reference/config", + "/yaml-reference", + ], }, { to: "/customize/context-providers", @@ -348,10 +368,6 @@ const config = { to: "/customize/model-providers/openai", from: "/reference/Model Providers/openai", }, - { - to: "/customize/slash-commands", - from: "/customization/slash-commands", - }, { to: "/customize/tutorials/custom-code-rag", from: "/walkthroughs/custom-code-rag", @@ -458,12 +474,12 @@ const config = { from: "/chat", }, { - to: "/edit/how-to-use-it", - from: "/edit", + to: "/agent/how-to-use-it", + from: "/agent", }, { - to: "/actions/how-to-use-it", - from: "/actions", + to: "/edit/how-to-use-it", + from: "/edit", }, { to: "/autocomplete/how-to-use-it", @@ -473,6 +489,10 @@ const config = { to: "/getting-started/install", from: "/getting-started", }, + { + to: "/customize/deep-dives/prompts", + from: "/customize/deep-dives/prompt-files", + }, ], }, ], diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md index 2ffc4d0f2..d3c1097e7 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md @@ -13,7 +13,7 @@ Continue 有一个大的内置斜杠命令库,但是当你首次安装时, 有两种方法添加定制斜杠命令: -1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompt-files.md) 查看完整参考。 +1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompts.md) 查看完整参考。 2. 使用 `config.ts` - 这给你对于 LLM, IDE 和其他重要的入口可编程的访问,通过编写 JavaScript/TypeScript 函数 ### 使用 `config.ts` 定制斜杠命令 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md index f265a9885..a0d4c0023 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md @@ -24,7 +24,7 @@ Actions 是常见用例的快捷方式。例如,你可能想要审查代码, 通过定义一个 ".prompt 文件" ,也可以编写你自己的斜杠命令。 prompt 文件可以是个简单的文本文件,但是也包含模板,所以你可以引用文件, URL ,高亮代码以及更多。 -完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt-files.md) 。 +完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt.md) 。 :::tip[Prompt 库] 为了帮助你开始,[我们精心编写了一个小的 `.prompt` 文件库](https://github.com/continuedev/prompt-file-examples) 。我们鼓励社区贡献到这个仓库,所以请考虑为你的 prompt 创建一个拉取请求! diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md index e14ac4afc..151eb87e8 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md @@ -31,12 +31,6 @@ toc_max_heading_level: 5 3. 本地保存嵌入在你的机器上 4. 通过 `@Docs` 上下文提供者提供访问索引内容 -## 预先索引文档网站 - -我们提供一个流行的框架和库的预先索引文档网站的选择。你可以 [在这里查看可用的预先索引网站和请求附加内容](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts) 列表。 - -## 索引你自己的文档 - ### 通过 `@Docs` 上下文提供者 为了添加一个单独的文档网站,我们推荐使用 `@Docs` 上下文提供者。 diff --git a/docs/package-lock.json b/docs/package-lock.json index abd1275c6..f9c2ca21c 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -9617,9 +9617,10 @@ "license": "ISC" }, "node_modules/image-size": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.0.tgz", - "integrity": "sha512-4S8fwbO6w3GeCVN6OPtA9I5IGKkcDMPcKndtUlpJuCwu7JLjtj7JZpwqLuyY2nrmQT3AWsCJLSKPsc2mPBSl3w==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.1.tgz", + "integrity": "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw==", + "license": "MIT", "dependencies": { "queue": "6.0.2" }, diff --git a/docs/sidebars.js b/docs/sidebars.js index 0e83628a4..20a47be93 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -47,11 +47,11 @@ const sidebars = { }, { type: "category", - label: "Actions", + label: "Agent", items: [ { type: "autogenerated", - dirName: "actions", + dirName: "agent", }, ], }, @@ -59,8 +59,8 @@ const sidebars = { "troubleshooting", { type: "link", - label: "Customize", - href: "/customize/overview", + label: "Hub", + href: "/hub/introduction", }, ], customizingSidebar: [ @@ -128,18 +128,11 @@ const sidebars = { }, ], }, - "customize/settings", { type: "link", label: "Reference", href: "/reference", }, - { - type: "link", - label: "YAML Reference", - href: "/yaml-reference", - }, - "customize/changelog", ], hubSidebar: [ "hub/introduction", @@ -172,7 +165,16 @@ const sidebars = { { type: "category", label: "Governance", - items: ["hub/governance/org-permissions", "hub/governance/pricing"], + items: [ + "hub/governance/org-permissions", + "hub/governance/creating-an-org", + "hub/governance/pricing", + ], + }, + { + type: "link", + label: "Customize", + href: "/customize/overview", }, ], }; diff --git a/docs/static/img/agent-permission.png b/docs/static/img/agent-permission.png new file mode 100644 index 000000000..ca7cfaf4f Binary files /dev/null and b/docs/static/img/agent-permission.png differ diff --git a/docs/static/img/agent-response.png b/docs/static/img/agent-response.png new file mode 100644 index 000000000..472360df1 Binary files /dev/null and b/docs/static/img/agent-response.png differ diff --git a/docs/static/img/agent.gif b/docs/static/img/agent.gif new file mode 100644 index 000000000..7edf735a6 Binary files /dev/null and b/docs/static/img/agent.gif differ diff --git a/docs/static/img/configure-continue.png b/docs/static/img/configure-continue.png index 57355638f..bb1d5ed30 100644 Binary files a/docs/static/img/configure-continue.png and b/docs/static/img/configure-continue.png differ diff --git a/docs/static/img/edit-mode-add-all-open-files.png b/docs/static/img/edit-mode-add-all-open-files.png new file mode 100644 index 000000000..9aa981347 Binary files /dev/null and b/docs/static/img/edit-mode-add-all-open-files.png differ diff --git a/docs/static/img/edit-mode-add-files.png b/docs/static/img/edit-mode-add-files.png new file mode 100644 index 000000000..b2f97f314 Binary files /dev/null and b/docs/static/img/edit-mode-add-files.png differ diff --git a/docs/static/img/edit-mode-multi-file-diffs.png b/docs/static/img/edit-mode-multi-file-diffs.png new file mode 100644 index 000000000..caa9f2d25 Binary files /dev/null and b/docs/static/img/edit-mode-multi-file-diffs.png differ diff --git a/docs/static/img/edit-mode-multi-file-generation.png b/docs/static/img/edit-mode-multi-file-generation.png new file mode 100644 index 000000000..20f3fe98e Binary files /dev/null and b/docs/static/img/edit-mode-multi-file-generation.png differ diff --git a/docs/static/img/edit-mode-multi-file-output.png b/docs/static/img/edit-mode-multi-file-output.png new file mode 100644 index 000000000..1ceb00714 Binary files /dev/null and b/docs/static/img/edit-mode-multi-file-output.png differ diff --git a/docs/static/img/edit-mode-single-file-diff.png b/docs/static/img/edit-mode-single-file-diff.png new file mode 100644 index 000000000..90e33cfc7 Binary files /dev/null and b/docs/static/img/edit-mode-single-file-diff.png differ diff --git a/docs/static/img/header-buttons.png b/docs/static/img/header-buttons.png index f6a644d03..6824043cf 100644 Binary files a/docs/static/img/header-buttons.png and b/docs/static/img/header-buttons.png differ diff --git a/docs/static/img/hub/assistant-create-sidebar.png b/docs/static/img/hub/assistant-create-sidebar.png index 159806d31..45a1e22ee 100644 Binary files a/docs/static/img/hub/assistant-create-sidebar.png and b/docs/static/img/hub/assistant-create-sidebar.png differ diff --git a/docs/static/img/hub/create-org-form.png b/docs/static/img/hub/create-org-form.png new file mode 100644 index 000000000..db4497ec2 Binary files /dev/null and b/docs/static/img/hub/create-org-form.png differ diff --git a/docs/static/img/hub/org-home-page.png b/docs/static/img/hub/org-home-page.png new file mode 100644 index 000000000..a85e283c4 Binary files /dev/null and b/docs/static/img/hub/org-home-page.png differ diff --git a/docs/static/img/hub/org-selector.png b/docs/static/img/hub/org-selector.png new file mode 100644 index 000000000..a154659be Binary files /dev/null and b/docs/static/img/hub/org-selector.png differ diff --git a/docs/static/img/lump-toolbar.png b/docs/static/img/lump-toolbar.png new file mode 100644 index 000000000..b3dcf88c2 Binary files /dev/null and b/docs/static/img/lump-toolbar.png differ diff --git a/docs/static/img/mode-select-agent.png b/docs/static/img/mode-select-agent.png new file mode 100644 index 000000000..2940a94fb Binary files /dev/null and b/docs/static/img/mode-select-agent.png differ diff --git a/docs/static/img/model-roles-edit.png b/docs/static/img/model-roles-edit.png new file mode 100644 index 000000000..2d033a5d1 Binary files /dev/null and b/docs/static/img/model-roles-edit.png differ diff --git a/docs/static/img/select-edit-mode.png b/docs/static/img/select-edit-mode.png new file mode 100644 index 000000000..e68d6dc25 Binary files /dev/null and b/docs/static/img/select-edit-mode.png differ diff --git a/docs/static/img/settings-model-roles.png b/docs/static/img/settings-model-roles.png index 7a2d24407..347140c7e 100644 Binary files a/docs/static/img/settings-model-roles.png and b/docs/static/img/settings-model-roles.png differ diff --git a/docs/static/img/settings-page.png b/docs/static/img/settings-page.png index f4b58cfd5..53bd1296f 100644 Binary files a/docs/static/img/settings-page.png and b/docs/static/img/settings-page.png differ diff --git a/docs/static/img/tool-policies.png b/docs/static/img/tool-policies.png new file mode 100644 index 000000000..d5e52a607 Binary files /dev/null and b/docs/static/img/tool-policies.png differ diff --git a/docs/static/img/tool-use-example.png b/docs/static/img/tool-use-example.png deleted file mode 100644 index 63f1c456a..000000000 Binary files a/docs/static/img/tool-use-example.png and /dev/null differ diff --git a/extensions/intellij/README.md b/extensions/intellij/README.md index dccf4a7f1..45a1f05f0 100644 --- a/extensions/intellij/README.md +++ b/extensions/intellij/README.md @@ -28,11 +28,11 @@ To enable it, simply click the "Continue" button in the status bar at the bottom Highlight a block of code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject. -## 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 -For example, you might want to review code, write tests, or add a docstring. +Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions. diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 0d846c3d2..7c00cb65c 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.5 +pluginVersion=1.0.12 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 9d48705df..031c6b2e9 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -1,4 +1,5 @@ package com.github.continuedev.continueintellijextension.activities +import IntelliJIDE import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.github.continuedev.continueintellijextension.auth.AuthListener import com.github.continuedev.continueintellijextension.auth.ContinueAuthService @@ -152,17 +153,12 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { val connection = ApplicationManager.getApplication().messageBus.connect() connection.subscribe(SettingsListener.TOPIC, object : SettingsListener { override fun settingsUpdated(settings: ContinueExtensionSettings.ContinueState) { - continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", settings, null) { _ -> } - continuePluginService.sendToWebview( - "didChangeIdeSettings", mapOf( - "settings" to mapOf( - "remoteConfigServerUrl" to settings.remoteConfigServerUrl, - "remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod, - "userToken" to settings.userToken, - "enableControlServerBeta" to settings.enableContinueTeamsBeta - ) - ) - ) + continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", mapOf( + "remoteConfigServerUrl" to settings.remoteConfigServerUrl, + "remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod, + "userToken" to settings.userToken, + "enableControlServerBeta" to settings.enableContinueTeamsBeta + ), null) { _ -> } } }) @@ -185,6 +181,8 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { // Notify core of content changes if (changedURIs.isNotEmpty()) { + continuePluginService.updateLastFileSaveTimestamp() + val data = mapOf("uris" to changedURIs) continuePluginService.coreMessenger?.request("files/changed", data, null) { _ -> } } @@ -236,7 +234,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { "sessionInfo" to initialSessionInfo ) continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", data, null) { _ -> } - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data) } connection.subscribe(AuthListener.TOPIC, object : AuthListener { @@ -253,7 +250,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { data, null ) { _ -> } - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data) } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 665b393c0..60d2d3b33 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -23,6 +23,7 @@ class MessageTypes { "getCurrentFile", "getPinnedFiles", "getSearchResults", + "getFileResults", "getProblems", "subprocess", "getBranch", @@ -65,12 +66,10 @@ class MessageTypes { "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", - "didChangeAvailableProfiles", "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", "didCloseFiles", - "didSelectOrganization" ) // Note: If updating these values, make a corresponding update in @@ -83,12 +82,10 @@ class MessageTypes { "history/save", "devdata/log", "config/addModel", - "config/addContextProvider", "config/newPromptFile", "config/ideSettingsUpdate", "config/getSerializedProfileInfo", "config/deleteModel", - "config/listProfiles", "config/refreshProfiles", "config/openProfile", "config/updateSharedConfig", @@ -129,8 +126,6 @@ class MessageTypes { "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", - "controlPlane/listOrganizations" - ) } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt new file mode 100644 index 000000000..a378820e8 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GitService.kt @@ -0,0 +1,94 @@ +package com.github.continuedev.continueintellijextension.`continue` + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.toUriOrNull +import com.intellij.openapi.project.Project +import com.intellij.openapi.project.guessProjectDir +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.BufferedReader +import java.io.File +import java.io.InputStreamReader +import java.net.URI + +class GitService( + private val project: Project, + private val continuePluginService: ContinuePluginService +) { + // Add a simple cache for diff results + private data class DiffCache( + val timestamp: Long, + val diffs: List + ) + + // Cache the last diff result + private var diffCache: DiffCache? = null + private var lastFileSaveTimestamp: Long = System.currentTimeMillis() + + /** + * Updates the timestamp when a file is saved + */ + fun updateLastFileSaveTimestamp() { + lastFileSaveTimestamp = System.currentTimeMillis() + } + + /** + * Returns the git diff for all workspace directories + */ + suspend fun getDiff(includeUnstaged: Boolean): List { + // Check if we have a valid cache entry + if (diffCache != null && diffCache!!.timestamp == lastFileSaveTimestamp) { + return diffCache!!.diffs + } + + // If no cache hit, compute the diff + val workspaceDirs = workspaceDirectories() + val diffs = mutableListOf() + + for (workspaceDir in workspaceDirs) { + val output = StringBuilder() + val builder = if (includeUnstaged) { + ProcessBuilder("git", "diff") + } else { + ProcessBuilder("git", "diff", "--cached") + } + builder.directory(File(URI(workspaceDir))) + val process = withContext(Dispatchers.IO) { + builder.start() + } + + val reader = BufferedReader(InputStreamReader(process.inputStream)) + var line: String? = withContext(Dispatchers.IO) { + reader.readLine() + } + while (line != null) { + output.append(line) + output.append("\n") + line = withContext(Dispatchers.IO) { + reader.readLine() + } + } + + withContext(Dispatchers.IO) { + process.waitFor() + } + + diffs.add(output.toString()) + } + + // Cache the result + diffCache = DiffCache(lastFileSaveTimestamp, diffs) + return diffs + } + + private fun workspaceDirectories(): Array { + val dirs = this.continuePluginService.workspacePaths + + if (dirs?.isNotEmpty() == true) { + return dirs + } + + return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() + } + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 268a7674f..41c2c4892 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -16,6 +16,7 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager @@ -45,6 +46,10 @@ class IdeProtocolClient( ) } + fun updateLastFileSaveTimestamp() { + (ide as IntelliJIDE).updateLastFileSaveTimestamp() + } + fun handleMessage(msg: String, respond: (Any?) -> Unit) { coroutineScope.launch(Dispatchers.IO) { val message = Gson().fromJson(msg, Message::class.java) @@ -110,7 +115,7 @@ class IdeProtocolClient( .handleUpdatedSessionInfo(null) // Tell the webview that session info changed - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", null, uuid()) + continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", null, null) { _ -> } respond(null) } @@ -343,6 +348,15 @@ class IdeProtocolClient( respond(results) } + "getFileResults" -> { + val params = Gson().fromJson( + dataElement.toString(), + GetFileResultsParams::class.java + ) + val results = ide.getFileResults(params.pattern) + respond(results) + } + "getOpenFiles" -> { val openFiles = ide.getOpenFiles() respond(openFiles) @@ -419,11 +433,43 @@ class IdeProtocolClient( dataElement.toString(), ApplyToFileParams::class.java ) + val filepath = params.filepath - val editor = FileEditorManager.getInstance(project).selectedTextEditor + continuePluginService.sendToWebview("updateApplyState", mapOf( + "streamId" to params.streamId, + "status" to "streaming", + "fileContent" to params.text, + "toolCallId" to params.toolCallId, + "filepath" to filepath + )) + + + fun closeStream () { + continuePluginService.sendToWebview("updateApplyState", mapOf( + "numDiffs" to 0, + "streamId" to params.streamId, + "status" to "closed", + "fileContent" to params.text, + "toolCallId" to params.toolCallId, + "filepath" to filepath + )) + } + + var editor: Editor? = null; + + if (!filepath.isNullOrEmpty()) { + val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() + } + } + } + editor = FileEditorManager.getInstance(project).selectedTextEditor if (editor == null) { ide.showToast(ToastType.ERROR, "No active editor to apply edits to") + closeStream() respond(null) return@launch } @@ -432,6 +478,7 @@ class IdeProtocolClient( WriteCommandAction.runWriteCommandAction(project) { editor.document.insertString(0, params.text) } + closeStream() respond(null) return@launch } @@ -477,6 +524,7 @@ class IdeProtocolClient( ToastType.ERROR, "Failed to fetch model configuration" ) } + closeStream() respond(null) return@launch } @@ -515,7 +563,11 @@ class IdeProtocolClient( editor, rif?.range?.start?.line ?: 0, rif?.range?.end?.line ?: (editor.document.lineCount - 1), - {}, {}) + {}, + {}, + params.streamId, + params.toolCallId + ) diffStreamService.register(diffStreamHandler, editor) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index e903e1238..a23f2d716 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -1,13 +1,9 @@ import com.github.continuedev.continueintellijextension.* import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.github.continuedev.continueintellijextension.`continue`.GitService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.OS -import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID -import com.github.continuedev.continueintellijextension.utils.getOS -import com.github.continuedev.continueintellijextension.utils.toUriOrNull -import com.github.continuedev.continueintellijextension.utils.Desktop -import com.google.gson.Gson +import com.github.continuedev.continueintellijextension.utils.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil @@ -31,12 +27,7 @@ import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile -import com.intellij.util.containers.toArray import kotlinx.coroutines.* -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.OkHttpClient -import okhttp3.Request -import okhttp3.RequestBody.Companion.toRequestBody import java.awt.Toolkit import java.awt.datatransfer.DataFlavor import java.io.BufferedReader @@ -44,7 +35,6 @@ import java.io.File import java.io.FileInputStream import java.io.InputStreamReader import java.net.URI -import java.net.URL import java.nio.charset.Charset import java.nio.file.Paths @@ -52,7 +42,10 @@ class IntelliJIDE( private val project: Project, private val continuePluginService: ContinuePluginService, - ) : IDE { +) : IDE { + + private val gitService = GitService(project, continuePluginService) + private val ripgrep: String init { @@ -66,6 +59,13 @@ class IntelliJIDE( Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + if (os == OS.WINDOWS) ".exe" else "").toString() } + /** + * Updates the timestamp when a file is saved + */ + override fun updateLastFileSaveTimestamp() { + gitService.updateLastFileSaveTimestamp() + } + override suspend fun getIdeInfo(): IdeInfo { val applicationInfo = ApplicationInfo.getInstance() val ideName: String = applicationInfo.fullApplicationName @@ -110,41 +110,7 @@ class IntelliJIDE( } override suspend fun getDiff(includeUnstaged: Boolean): List { - val workspaceDirs = workspaceDirectories() - val diffs = mutableListOf() - - for (workspaceDir in workspaceDirs) { - val output = StringBuilder() - val builder = if (includeUnstaged) { - ProcessBuilder("git", "diff") - } else { - ProcessBuilder("git", "diff", "--cached") - } - builder.directory(File(URI(workspaceDir))) - val process = withContext(Dispatchers.IO) { - builder.start() - } - - val reader = BufferedReader(InputStreamReader(process.inputStream)) - var line: String? = withContext(Dispatchers.IO) { - reader.readLine() - } - while (line != null) { - output.append(line) - output.append("\n") - line = withContext(Dispatchers.IO) { - reader.readLine() - } - } - - withContext(Dispatchers.IO) { - process.waitFor() - } - - diffs.add(output.toString()) - } - - return diffs + return gitService.getDiff(includeUnstaged) } override suspend fun getClipboardContent(): Map { @@ -185,7 +151,7 @@ class IntelliJIDE( } override suspend fun getWorkspaceConfigs(): List { - val workspaceDirs = workspaceDirectories() + val workspaceDirs = this.getWorkspaceDirs() val configs = mutableListOf() @@ -342,12 +308,116 @@ class IntelliJIDE( return getOpenFiles() } - override suspend fun getSearchResults(query: String): String { - val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--heading", "-e", query, ".") - command.setWorkDirectory(project.basePath) - return ExecUtil.execAndGetOutput(command).stdout + override suspend fun getFileResults(pattern: String): List { + val ideInfo = this.getIdeInfo() + if (ideInfo.remoteName == "local") { + val command = GeneralCommandLine( + ripgrep, + "--files", + "--iglob", + pattern, + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + ) + + command.setWorkDirectory(project.basePath) + val results = ExecUtil.execAndGetOutput(command).stdout + return results.split("\n") + } else { + throw NotImplementedError("Ripgrep not supported, this workspace is remote") + + // Leaving in here for ideas + // val projectBasePath = project.basePath ?: return emptyList() + // val scope = GlobalSearchScope.projectScope(project) + // + // // Get all ignore patterns from .continueignore files + // val ignorePatterns = mutableSetOf() + // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> + // VfsUtil.collectChildrenRecursively(root).forEach { file -> + // if (file.name == ".continueignore") { + // file.inputStream.bufferedReader().useLines { lines -> + // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) + // } + // } + // } + // } + // + // return FilenameIndex.getAllFilesByExt(project, "*", scope) + // .filter { file -> + // val relativePath = file.path.removePrefix("$projectBasePath/") + // // Check if file matches pattern and isn't ignored + // PatternUtil.(relativePath, pattern) && + // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } + // } + // .map { it.path.removePrefix("$projectBasePath/") } + } } + override suspend fun getSearchResults(query: String): String { + val ideInfo = this.getIdeInfo() + if (ideInfo.remoteName == "local") { + val command = GeneralCommandLine( + ripgrep, + "-i", + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + "-C", + "2", + "--heading", + "-e", + query, + "." + ) + + command.setWorkDirectory(project.basePath) + return ExecUtil.execAndGetOutput(command).stdout + } else { + throw NotImplementedError("Ripgrep not supported, this workspace is remote") + + // For remote workspaces, use JetBrains search functionality + // val searchResults = StringBuilder() + // ApplicationManager.getApplication().invokeAndWait { + // val options = FindModel().apply { + // stringToFind = query + // isCaseSensitive = false + // isRegularExpressions = false + // isWholeWordsOnly = false + // searchContext = FindModel.SearchContext.ANY // or IN_CODE, IN_COMMENTS, IN_STRING_LITERALS, etc. + // isMultiline = true // Allow matching across multiple lines + // } + // + // val progressIndicator = EmptyProgressIndicator() + // val presentation = FindUsagesProcessPresentation( + // UsageViewPresentation() + // ) + // val filesToSearch = ProjectFileIndex.getInstance(project) + // .iterateContent(::ArrayList) + // .filterNot { it.isDirectory } + // .toSet() + // + // + // FindInProjectUtil.findUsages( + // options, + // project, + // progressIndicator, + // presentation, + // filesToSearch + // ) { result -> + // val virtualFile = result.virtualFile + // searchResults.append(virtualFile.path).append("\n") + // searchResults.append("${result..trim()}\n") + // true // continue searching + // } + // } + // return searchResults.toString() + } + } + + override suspend fun subprocess(command: String, cwd: String?): List { val commandList = command.split(" ") val builder = ProcessBuilder(commandList) @@ -434,7 +504,7 @@ class IntelliJIDE( } override suspend fun getTags(artifactId: String): List { - val workspaceDirs = workspaceDirectories() + val workspaceDirs = this.getWorkspaceDirs() // Collect branches concurrently using Kotlin coroutines val branches = withContext(Dispatchers.IO) { @@ -577,4 +647,5 @@ class IntelliJIDE( return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray() } + } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 55df303a8..f6cf5972f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -27,14 +27,15 @@ class DiffStreamHandler( private val startLine: Int, private val endLine: Int, private val onClose: () -> Unit, - private val onFinish: () -> Unit + private val onFinish: () -> Unit, + private val streamId: String?, + private val toolCallId: String? ) { private data class CurLineState( var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null ) private var curLine = CurLineState(startLine) - private var isRunning: Boolean = false private var hasAcceptedOrRejectedBlock: Boolean = false @@ -48,8 +49,26 @@ class DiffStreamHandler( initUnfinishedRangeHighlights() } + private fun sendUpdate(status: String) { + if(this.streamId == null) { + return + } + val virtualFile = getVirtualFile() + val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) + continuePluginService.sendToWebview("updateApplyState", mapOf( + "numDiffs" to this.diffBlocks.size, + "streamId" to this.streamId, + "status" to status, + "fileContent" to "not implemented", + "toolCallId" to this.toolCallId, + "filepath" to virtualFile?.url + )) + } + fun acceptAll() { - editor.markupModel.removeAllHighlighters() + editor.markupModel.removeAllHighlighters(); + sendUpdate("closed") + resetState() } @@ -62,6 +81,7 @@ class DiffStreamHandler( } else { undoChanges() } + sendUpdate("closed") resetState() } @@ -70,6 +90,7 @@ class DiffStreamHandler( input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String ) { isRunning = true + this.sendUpdate("streaming") val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) val virtualFile = getVirtualFile() @@ -83,6 +104,7 @@ class DiffStreamHandler( if (response["done"] as? Boolean == true) { handleFinishedResponse() + sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done") return@request } @@ -133,7 +155,10 @@ class DiffStreamHandler( } if (diffBlocks.isEmpty()) { + sendUpdate("closed") onClose() + } else { + sendUpdate("done") } } @@ -144,6 +169,7 @@ class DiffStreamHandler( ) diffBlocks.add(diffBlock) + sendUpdate("streaming") return diffBlock } @@ -234,6 +260,7 @@ class DiffStreamHandler( undoManager.undo(fileEditor) } } + sendUpdate("done") } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index faaf7d058..fd910308d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -207,7 +207,10 @@ fun openInlineEdit(project: Project?, editor: Editor) { textArea.document.insertString(textArea.caretPosition, ", ", null) textArea.requestFocus() customPanelRef.get().finish() - }) + }, + null, + null + ) val diffStreamService = project.service() diffStreamService.register(diffStreamHandler, editor) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 5ce49e80a..4c66fcc0c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -23,6 +23,7 @@ typealias getTagsParams = String data class GetSearchResultsParams(val query: String) +data class GetFileResultsParams(val pattern: String) data class SaveFileParams(val filepath: String) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 07988ad0e..5c587c54d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -12,7 +12,8 @@ data class ApplyToFileParams( val text: String, val streamId: String, val curSelectedModelTitle: String, - val filepath: String? + val filepath: String?, + val toolCallId: String? ) data class InsertAtCursorParams( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index cf1005596..d3b8ea68a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -41,4 +41,8 @@ class ContinuePluginService : Disposable, DumbAware { ) { continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId) } + + fun updateLastFileSaveTimestamp() { + ideProtocolClient?.updateLastFileSaveTimestamp() + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 7dfa83da4..2970ca84a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -159,6 +159,8 @@ interface IDE { suspend fun getSearchResults(query: String): String + suspend fun getFileResults(pattern: String): List + // Note: This should be a `Pair` but we use `List` because the keys of `Pair` // will serialize to `first and `second` rather than `0` and `1` like in JavaScript suspend fun subprocess(command: String, cwd: String? = null): List @@ -192,6 +194,10 @@ interface IDE { // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) + + fun updateLastFileSaveTimestamp() { + // Default implementation does nothing + } } data class GetGhTokenArgs( diff --git a/extensions/vscode/README.md b/extensions/vscode/README.md index 9470b2d5e..1bc087276 100644 --- a/extensions/vscode/README.md +++ b/extensions/vscode/README.md @@ -44,11 +44,11 @@ ![edit](docs/static/img/edit.gif) -## 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 -![actions](docs/static/img/actions.gif) +![agent](docs/static/img/agent.gif) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 2a908c045..801bba5ea 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -956,7 +956,10 @@ "gemini-2.0-flash", "gemini-2.0-flash-thinking-exp-01-21", "gemini-2.0-pro-exp-02-05", - "gemini-2.0-flash-lite-preview-02-05" + "gemini-2.0-flash-lite-preview-02-05", + "gemini-2.0-flash-lite", + "gemini-2.0-flash-exp-image-generation", + "gemini-2.5-pro-exp-03-25" ] } } @@ -2886,7 +2889,8 @@ "watsonx", "llm", "free-trial", - "huggingface-tei" + "huggingface-tei", + "siliconflow" ] }, "params": { @@ -3053,6 +3057,40 @@ "required": ["truncation_direction"] } } + }, + { + "if": { + "properties": { + "name": { + "enum": ["siliconflow"] + } + }, + "required": ["name"] + }, + "then": { + "properties": { + "params": { + "type": "object", + "properties": { + "model": { + "enum": [ + "BAAI/bge-reranker-v2-m3", + "netease-youdao/bce-reranker-base_v1", + "Pro/BAAI/bge-reranker-v2-m3" + ], + "default": "BAAI/bge-reranker-v2-m3" + }, + "apiBase": { + "type": "string" + }, + "apiKey": { + "type": "string" + } + }, + "required": ["apiKey"] + } + } + } } ] }, @@ -3063,7 +3101,7 @@ "default": { "title": "Tab Autocomplete Model", "provider": "ollama", - "model": "deepseek-coder:1.3b-base" + "model": "qwen2.5-coder:1.5b-base" }, "oneOf": [ { diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts index ace296ca3..ef2bf0c16 100644 --- a/extensions/vscode/e2e/actions/GUI.actions.ts +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -16,8 +16,12 @@ export class GUIActions { await GUIActions.toggleGui(); await TestUtils.waitForSuccess(async () => { await new Workbench().executeCommand("View: Move View"); - await (await InputBox.create(DEFAULT_TIMEOUT.MD)).selectQuickPick(4); - await (await InputBox.create(DEFAULT_TIMEOUT.MD)).selectQuickPick(14); + await ( + await InputBox.create(DEFAULT_TIMEOUT.MD) + ).selectQuickPick("Continue"); + await ( + await InputBox.create(DEFAULT_TIMEOUT.MD) + ).selectQuickPick("New Secondary Side Bar Entry"); }); // first call focuses the input diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e8f7b966b..108520e49 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.13", + "version": "1.1.21", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.13", + "version": "1.1.21", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -87,8 +87,8 @@ "mocha": "^10.4.0", "ovsx": "^0.8.3", "rimraf": "^5.0.5", - "typescript": "^5.3.3", - "vite": "^4.3.9", + "typescript": "^5.6.3", + "vite": "^4.5.12", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, @@ -102,13 +102,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", @@ -125,6 +125,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", @@ -193,7 +194,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" @@ -12292,9 +12294,10 @@ } }, "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==", + "license": "MIT", "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", @@ -12391,10 +12394,11 @@ } }, "node_modules/targz/node_modules/tar-fs": { - "version": "1.16.3", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.3.tgz", - "integrity": "sha512-NvCeXpYx7OsmOh8zIOP/ebG55zZmxLE0etfWRbWok+q2Qo8x/vOR/IJT1taADXPe+jsiu9axDb3X4B+iIgNlKw==", + "version": "1.16.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.4.tgz", + "integrity": "sha512-u3XczWoYAIVXe5GOKK6+VeWaHjtc47W7hyuTo3+4cNakcCcuDmlkYiiHEsECwTkcI3h1VUgtwBQ54+RvY6cM4w==", "dev": true, + "license": "MIT", "dependencies": { "chownr": "^1.0.1", "mkdirp": "^0.5.1", @@ -13318,9 +13322,9 @@ } }, "node_modules/vite": { - "version": "4.5.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", - "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", + "version": "4.5.12", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.12.tgz", + "integrity": "sha512-qrMwavANtSz91nDy3zEiUHMtL09x0mniQsSMvDkNxuCBM1W5vriJ22hEmwTth6DhLSWsZnHBT0yHFAQXt6efGA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index c96eee528..6ac6afd30 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.14", + "version": "1.1.21", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -127,6 +127,11 @@ "default": false, "markdownDescription": "Pause Continue's codebase index on start." }, + "continue.enableConsole": { + "type": "boolean", + "default": false, + "markdownDescription": "Enable a console to log and explore model inputs and outputs. It can be found in the bottom panel." + }, "continue.remoteConfigServerUrl": { "type": "string", "default": null, @@ -252,6 +257,13 @@ "title": "View History", "group": "Continue" }, + { + "command": "continue.clearConsole", + "category": "Continue", + "title": "Clear Console", + "icon": "$(clear-all)", + "group": "Continue" + }, { "command": "continue.navigateTo", "category": "Continue", @@ -505,6 +517,11 @@ "command": "continue.openConfigPage", "group": "navigation@4", "when": "view == continue.continueGUIView" + }, + { + "command": "continue.clearConsole", + "group": "navigation@1", + "when": "view == continue.continueConsoleView" } ], "editor/title": [ @@ -533,6 +550,13 @@ "title": "Continue", "icon": "media/sidebar-icon.png" } + ], + "panel": [ + { + "id": "continueConsole", + "title": "Continue Console", + "icon": "$(window)" + } ] }, "views": { @@ -544,6 +568,16 @@ "icon": "media/sidebar-icon.png", "visibility": "visible" } + ], + "continueConsole": [ + { + "type": "webview", + "id": "continue.continueConsoleView", + "name": "Continue Console", + "icon": "$(window)", + "visibility": "visible", + "when": "config.continue.enableConsole" + } ] }, "jsonValidation": [ @@ -624,8 +658,8 @@ "mocha": "^10.4.0", "ovsx": "^0.8.3", "rimraf": "^5.0.5", - "typescript": "^5.3.3", - "vite": "^4.3.9", + "typescript": "^5.6.3", + "vite": "^4.5.12", "vsce": "^2.15.0", "vscode-extension-tester": "^8.10.0" }, diff --git a/extensions/vscode/scripts/package.js b/extensions/vscode/scripts/package.js index 35ad7d24f..2fd5177eb 100644 --- a/extensions/vscode/scripts/package.js +++ b/extensions/vscode/scripts/package.js @@ -1,6 +1,10 @@ const { exec } = require("child_process"); const fs = require("fs"); +const version = JSON.parse( + fs.readFileSync("./package.json", { encoding: "utf-8" }), +).version; + const args = process.argv.slice(2); let target; @@ -27,6 +31,6 @@ exec(command, (error) => { throw error; } console.log( - "vsce package completed - extension created at extensions/vscode/build/continue-{version}.vsix", + `vsce package completed - extension created at extensions/vscode/build/continue-${version}.vsix`, ); }); diff --git a/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts b/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts new file mode 100644 index 000000000..6427091ff --- /dev/null +++ b/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts @@ -0,0 +1,221 @@ +import { LLMInteractionItem } from "core"; +import { EXTENSION_NAME } from "core/control-plane/env"; +import { LLMLogger } from "core/llm/logger"; +import * as vscode from "vscode"; + +import { getExtensionUri, getNonce } from "./util/vscode"; + +interface FromConsoleView { + type: "start" | "stop"; + uuid: string; +} + +// Maximum interactions we retain; when we exceed this, we drop the +// oldest and also send a message to the view to do the same. +const MAX_INTERACTIONS = 50; + +export class ContinueConsoleWebviewViewProvider + implements vscode.WebviewViewProvider +{ + public static readonly viewType = "continue.continueConsoleView"; + + resolveWebviewView( + webviewView: vscode.WebviewView, + _context: vscode.WebviewViewResolveContext, + _token: vscode.CancellationToken, + ): void | Thenable { + this._webviewView = webviewView; + this._webview = webviewView.webview; + this._webviewView.onDidDispose(() => { + this._webviewView = undefined; + this._webview = undefined; + }); + webviewView.webview.html = this.getSidebarContent( + this.extensionContext, + webviewView, + ); + this._webview.onDidReceiveMessage((message: FromConsoleView) => { + if (message.type === "start") { + this._currentUuid = message.uuid; + this._webview?.postMessage({ + type: "init", + uuid: this._currentUuid, + items: this.getAllItems(), + }); + } + }); + this._webviewView.onDidDispose(() => { + this._webview = undefined; + this._webviewView = undefined; + this._currentUuid = undefined; + }); + } + + private _webview?: vscode.Webview; + private _webviewView?: vscode.WebviewView; + private _currentUuid?: string; + private _currentInteractions = new Map(); + private _completedInteractions: LLMInteractionItem[][] = []; + private _saveLog; + + constructor( + private readonly windowId: string, + private readonly extensionContext: vscode.ExtensionContext, + private readonly llmLogger: LLMLogger, + ) { + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + this._saveLog = config.get("enableConsole"); + + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration(`${EXTENSION_NAME}.enableConsole`)) { + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + this._saveLog = config.get("enableConsole"); + if (!this._saveLog) { + this.clearLog(); + } + } + }); + + llmLogger.onLogItem((item) => this.addItem(item)); + } + + private addItem(item: LLMInteractionItem) { + if (!this._saveLog) { + return; + } + + let iteractionItems = this._currentInteractions.get(item.interactionId); + if (iteractionItems === undefined) { + iteractionItems = []; + this._currentInteractions.set(item.interactionId, iteractionItems); + } + + iteractionItems.push(item); + switch (item.kind) { + case "success": + case "cancel": + case "error": + this._completedInteractions.push(iteractionItems); + this._currentInteractions.delete(item.interactionId); + break; + default: + break; + } + + if (this._currentUuid) { + this._webview?.postMessage({ + type: "item", + uuid: this._currentUuid, + item, + }); + } + + while ( + this._completedInteractions.length > 0 && + this._completedInteractions.length + this._currentInteractions.size > + MAX_INTERACTIONS + ) { + let toRemove = this._completedInteractions.shift(); + this._webview?.postMessage({ + type: "remove", + uuid: this._currentUuid, + interactionId: toRemove![0].interactionId, + }); + } + } + + private getAllItems() { + let items = this._completedInteractions.flat(); + + for (const interactionItems of this._currentInteractions.values()) { + items.push(...interactionItems); + } + + return items; + } + + clearLog() { + this._completedInteractions = []; + this._currentInteractions = new Map(); + + if (this._currentUuid) { + this._webview?.postMessage({ + type: "clear", + uuid: this._currentUuid, + }); + } + } + + private getSidebarContent( + context: vscode.ExtensionContext | undefined, + panel: vscode.WebviewPanel | vscode.WebviewView, + page: string | undefined = undefined, + ): string { + const extensionUri = getExtensionUri(); + let scriptUri: string; + let styleMainUri: string; + + const inDevelopmentMode = + context?.extensionMode === vscode.ExtensionMode.Development; + if (!inDevelopmentMode) { + scriptUri = panel.webview + .asWebviewUri( + vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.js"), + ) + .toString(); + styleMainUri = panel.webview + .asWebviewUri( + vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.css"), + ) + .toString(); + } else { + scriptUri = "http://localhost:5173/src/console.tsx"; + styleMainUri = "http://localhost:5173/src/indexConsole.css"; + } + + panel.webview.options = { + enableScripts: true, + localResourceRoots: [ + vscode.Uri.joinPath(extensionUri, "gui"), + vscode.Uri.joinPath(extensionUri, "assets"), + ], + enableCommandUris: true, + portMapping: [ + { + webviewPort: 65433, + extensionHostPort: 65433, + }, + ], + }; + + const nonce = getNonce(); + + return ` + + + + + + + + Continue + + +
+ + ${ + inDevelopmentMode + ? `` + : "" + } + + + `; + } +} diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 6972ad9ff..3c8b66dcd 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -4,7 +4,7 @@ import { exec } from "node:child_process"; import { Range } from "core"; import { EXTENSION_NAME } from "core/control-plane/env"; import { GetGhTokenArgs } from "core/protocol/ide"; -import { editConfigJson, getConfigJsonPath } from "core/util/paths"; +import { editConfigFile, getConfigJsonPath } from "core/util/paths"; import * as URI from "uri-js"; import * as vscode from "vscode"; @@ -155,26 +155,39 @@ class VsCodeIde implements IDE { ); // Remove free trial models - editConfigJson((config) => { - let tabAutocompleteModel = undefined; - if (Array.isArray(config.tabAutocompleteModel)) { - tabAutocompleteModel = config.tabAutocompleteModel.filter( - (model) => model.provider !== "free-trial", - ); - } else if ( - config.tabAutocompleteModel?.provider === "free-trial" - ) { - tabAutocompleteModel = undefined; - } + editConfigFile( + (config) => { + let tabAutocompleteModel = undefined; + if (Array.isArray(config.tabAutocompleteModel)) { + tabAutocompleteModel = config.tabAutocompleteModel.filter( + (model) => model.provider !== "free-trial", + ); + } else if ( + config.tabAutocompleteModel?.provider === "free-trial" + ) { + tabAutocompleteModel = undefined; + } - return { - ...config, - models: config.models.filter( - (model) => model.provider !== "free-trial", - ), - tabAutocompleteModel, - }; - }); + return { + ...config, + models: config.models.filter( + (model) => model.provider !== "free-trial", + ), + tabAutocompleteModel, + }; + }, + (config) => { + return { + ...config, + models: config.models?.filter( + (model) => + !( + "provider" in model && model.provider === "free-trial" + ), + ), + }; + }, + ); } else if (selection === "Learn more") { vscode.env.openExternal( vscode.Uri.parse( @@ -216,13 +229,22 @@ class VsCodeIde implements IDE { ) .then((selection) => { if (selection === "Remove for me") { - editConfigJson((configJson) => { - configJson.models = configJson.models.filter( - (model) => model.provider !== "free-trial", - ); - configJson.tabAutocompleteModel = undefined; - return configJson; - }); + editConfigFile( + (configJson) => { + configJson.models = configJson.models.filter( + (model) => model.provider !== "free-trial", + ); + configJson.tabAutocompleteModel = undefined; + return configJson; + }, + (config) => { + config.models = config.models?.filter( + (model) => + !("provider" in model && model.provider === "free-trial"), + ); + return config; + }, + ); } else if (selection === "Open Assistant configuration") { this.openFile(getConfigJsonPath()); } @@ -533,25 +555,15 @@ class VsCodeIde implements IDE { .map((t) => (t.input as vscode.TabInputText).uri.toString()); } - private async _searchDir(query: string, dir: string): Promise { - const relativeDir = vscode.Uri.parse(dir).fsPath; + runRipgrepQuery(dirUri: string, args: string[]) { + const relativeDir = vscode.Uri.parse(dirUri).fsPath; const ripGrepUri = vscode.Uri.joinPath( getExtensionUri(), "out/node_modules/@vscode/ripgrep/bin/rg", ); - const p = child_process.spawn( - ripGrepUri.fsPath, - [ - "-i", // Case-insensitive search - "-C", - "2", // Show 2 lines of context - "--heading", // Only show filepath once per result - "-e", - query, // Pattern to search for - ".", // Directory to search in - ], - { cwd: relativeDir }, - ); + const p = child_process.spawn(ripGrepUri.fsPath, args, { + cwd: relativeDir, + }); let output = ""; p.stdout.on("data", (data) => { @@ -573,55 +585,118 @@ class VsCodeIde implements IDE { }); } + async getFileResults(pattern: string): Promise { + const MAX_FILE_RESULTS = 200; + if (vscode.env.remoteName) { + // TODO better tests for this remote search implementation + // throw new Error("Ripgrep not supported, this workspace is remote"); + + // IMPORTANT: findFiles automatically accounts for .gitignore + const ignoreFiles = await vscode.workspace.findFiles( + "**/.continueignore", + null, + ); + + const ignoreGlobs: Set = new Set(); + for (const file of ignoreFiles) { + const content = await vscode.workspace.fs.readFile(file); + const filePath = vscode.workspace.asRelativePath(file); + const fileDir = filePath + .replace(/\\/g, "/") + .replace(/\/$/, "") + .split("/") + .slice(0, -1) + .join("/"); + + const patterns = Buffer.from(content) + .toString() + .split("\n") + .map((line) => line.trim()) + .filter( + (line) => line && !line.startsWith("#") && !pattern.startsWith("!"), + ); + // VSCode does not support negations + + patterns + // Handle prefix + .map((pattern) => { + const normalizedPattern = pattern.replace(/\\/g, "/"); + + if (normalizedPattern.startsWith("/")) { + if (fileDir) { + return `{/,}${normalizedPattern}`; + } else { + return `${fileDir}/${normalizedPattern.substring(1)}`; + } + } else { + if (fileDir) { + return `${fileDir}/${normalizedPattern}`; + } else { + return `**/${normalizedPattern}`; + } + } + }) + // Handle suffix + .map((pattern) => { + return pattern.endsWith("/") ? `${pattern}**/*` : pattern; + }) + .forEach((pattern) => { + ignoreGlobs.add(pattern); + }); + } + + const ignoreGlobsArray = Array.from(ignoreGlobs); + + const results = await vscode.workspace.findFiles( + pattern, + ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null, + MAX_FILE_RESULTS, + ); + return results.map((result) => vscode.workspace.asRelativePath(result)); + } else { + const results: string[] = []; + for (const dir of await this.getWorkspaceDirs()) { + const dirResults = await this.runRipgrepQuery(dir, [ + "--files", + "--iglob", + pattern, + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + ]); + + results.push(dirResults); + } + + return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS); + } + } + async getSearchResults(query: string): Promise { + if (vscode.env.remoteName) { + throw new Error("Ripgrep not supported, this workspace is remote"); + } const results: string[] = []; for (const dir of await this.getWorkspaceDirs()) { - const dirResults = await this._searchDir(query, dir); + const dirResults = await this.runRipgrepQuery(dir, [ + "-i", // Case-insensitive search + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + "-C", + "2", // Show 2 lines of context + "--heading", // Only show filepath once per result + "-e", + query, // Pattern to search for + ".", // Directory to search in + ]); - const keepLines: string[] = []; - - function countLeadingSpaces(line: string) { - return line?.match(/^ */)?.[0].length ?? 0; - } - - // function formatLine(line: string, sectionIndent: number): string { - // return line.replace(new RegExp(`^[ ]{0,${sectionIndent}}`), ""); - // } - - let leading = false; - let sectionIndent = 0; - // let sectionTrim = 0; - for (const line of dirResults.split("\n").filter((l) => !!l)) { - if (line.startsWith("./") || line === "--") { - leading = true; - keepLines.push(line); - continue; - } - - if (leading) { - // Exclude leading single-char lines - if (line.trim().length > 1) { - // Record spacing at first non-single char line - leading = false; - sectionIndent = countLeadingSpaces(line); - keepLines.push(line); - } - continue; - } - // Exclude trailing - // TODO may exclude wanted results for lines that look like - // ./filename - // thisThing - // relevantThing - // - if (countLeadingSpaces(line) >= sectionIndent) { - keepLines.push(line); - } - } - results.push(keepLines.join("\n")); + results.push(dirResults); } - return results.join("\n\n"); + return results.join("\n"); } async getProblems(fileUri?: string | undefined): Promise { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 6a1e35424..9009d2b58 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -27,6 +27,7 @@ import { setupStatusBar, StatusBarStatus, } from "./autocomplete/statusBar"; +import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; import { VerticalDiffManager } from "./diff/vertical/manager"; @@ -247,6 +248,7 @@ async function processDiff( verticalDiffManager: VerticalDiffManager, newFileUri?: string, streamId?: string, + toolCallId?: string, ) { captureCommandTelemetry(`${action}Diff`); @@ -280,6 +282,7 @@ async function processDiff( streamId, status: "closed", numDiffs: 0, + toolCallId, }); } @@ -316,6 +319,7 @@ const getCommandsMap: ( ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, + consoleView: ContinueConsoleWebviewViewProvider, configHandler: ConfigHandler, verticalDiffManager: VerticalDiffManager, continueServerClientPromise: Promise, @@ -327,6 +331,7 @@ const getCommandsMap: ( ide, extensionContext, sidebar, + consoleView, configHandler, verticalDiffManager, continueServerClientPromise, @@ -634,16 +639,6 @@ const getCommandsMap: ( editDecorationManager.clear(); void sidebar.webviewProtocol?.request("exitEditMode", undefined); }, - // "continue.quickEdit": async (args: QuickEditShowParams) => { - // let linesOfCode = undefined; - // if (args.range) { - // linesOfCode = args.range.end.line - args.range.start.line; - // } - // captureCommandTelemetry("quickEdit", { - // linesOfCode, - // }); - // quickEdit.show(args); - // }, "continue.writeCommentsForCode": async () => { captureCommandTelemetry("writeCommentsForCode"); @@ -680,6 +675,9 @@ const getCommandsMap: ( "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", ); }, + "continue.clearConsole": async () => { + consoleView.clearLog(); + }, "continue.viewLogs": async () => { captureCommandTelemetry("viewLogs"); vscode.commands.executeCommand("workbench.action.toggleDevTools"); @@ -708,37 +706,6 @@ const getCommandsMap: ( vscode.commands.executeCommand("continue.continueGUIView.focus"); sidebar.webviewProtocol?.request("addModel", undefined); }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, "continue.newSession": () => { sidebar.webviewProtocol?.request("newSession", undefined); }, @@ -1127,6 +1094,7 @@ export function registerAllCommands( ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, + consoleView: ContinueConsoleWebviewViewProvider, configHandler: ConfigHandler, verticalDiffManager: VerticalDiffManager, continueServerClientPromise: Promise, @@ -1142,6 +1110,7 @@ export function registerAllCommands( ide, extensionContext, sidebar, + consoleView, configHandler, verticalDiffManager, continueServerClientPromise, diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 34c3345ac..4d4256a1f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -190,6 +190,7 @@ export class VerticalDiffManager { diffStream: AsyncGenerator, instant: boolean, streamId: string, + toolCallId?: string, ) { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -226,6 +227,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); @@ -276,6 +278,7 @@ export class VerticalDiffManager { quickEdit?: string, range?: vscode.Range, newCode?: string, + toolCallId?: string, ): Promise { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -351,6 +354,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); diff --git a/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts b/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts new file mode 100644 index 000000000..1c0a76251 --- /dev/null +++ b/extensions/vscode/src/extension/ConfigYamlDocumentLinkProvider.ts @@ -0,0 +1,43 @@ +import * as vscode from "vscode"; + +export class ConfigYamlDocumentLinkProvider + implements vscode.DocumentLinkProvider +{ + private usesPattern = /^\s*#?\s*-\s*uses:\s*(.+)$/; + provideDocumentLinks( + document: vscode.TextDocument, + token: vscode.CancellationToken, + ): vscode.ProviderResult { + const links: vscode.DocumentLink[] = []; + + for (let lineIndex = 0; lineIndex < document.lineCount; lineIndex++) { + const line = document.lineAt(lineIndex); + const match = this.usesPattern.exec(line.text); + + if (match) { + const slug = match[1].trim(); + const startPos = line.text.indexOf(slug); + const range = new vscode.Range( + lineIndex, + startPos, + lineIndex, + startPos + slug.length, + ); + + const link = new vscode.DocumentLink( + range, + vscode.Uri.parse(`https://hub.continue.dev/${slug}`), + ); + links.push(link); + } + } + + return links; + } + resolveDocumentLink( + link: vscode.DocumentLink, + token: vscode.CancellationToken, + ): vscode.ProviderResult { + return link; + } +} diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index a4a90afd3..c955f8d51 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -21,6 +21,7 @@ import { StatusBarStatus, } from "../autocomplete/statusBar"; import { registerAllCommands } from "../commands"; +import { ContinueConsoleWebviewViewProvider } from "../ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; @@ -37,6 +38,7 @@ import { Battery } from "../util/battery"; import { FileSearch } from "../util/FileSearch"; import { VsCodeIde } from "../VsCodeIde"; +import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -47,6 +49,7 @@ export class VsCodeExtension { private configHandler: ConfigHandler; private extensionContext: vscode.ExtensionContext; private ide: VsCodeIde; + private consoleView: ContinueConsoleWebviewViewProvider; private sidebar: ContinueGUIWebviewViewProvider; private windowId: string; private editDecorationManager: EditDecorationManager; @@ -105,10 +108,6 @@ export class VsCodeExtension { ); resolveWebviewProtocol(this.sidebar.webviewProtocol); - // Config Handler with output channel - const outputChannel = vscode.window.createOutputChannel( - "Continue - LLM Prompt/Completion", - ); const inProcessMessenger = new InProcessMessenger< ToCoreProtocol, FromCoreProtocol @@ -124,19 +123,12 @@ export class VsCodeExtension { this.editDecorationManager, ); - this.core = new Core(inProcessMessenger, this.ide, async (log: string) => { - outputChannel.appendLine( - "==========================================================================", - ); - outputChannel.appendLine( - "==========================================================================", - ); - outputChannel.append(log); - }); + this.core = new Core(inProcessMessenger, this.ide); this.configHandler = this.core.configHandler; resolveConfigHandler?.(this.configHandler); this.configHandler.loadConfig(); + this.verticalDiffManager = new VerticalDiffManager( this.configHandler, this.sidebar.webviewProtocol, @@ -201,16 +193,10 @@ export class VsCodeExtension { let profileId = queryParams.get("profile_id"); let orgId = queryParams.get("org_id"); - if (orgId) { - if (orgId === "null") { - orgId = null; - } + if (orgId && orgId !== "null") { // In case org id is passed with profile id // Make sure org is updated before profile is set - if (profileId) { - if (profileId === "null") { - profileId = null; - } + if (profileId && profileId !== "null") { this.core.invoke("didChangeSelectedOrg", { id: orgId, profileId, @@ -220,10 +206,7 @@ export class VsCodeExtension { id: orgId, }); } - } else if (profileId) { - if (profileId === "null") { - profileId = null; - } + } else if (profileId && profileId !== "null") { this.core.invoke("didChangeSelectedProfile", { id: profileId, }); @@ -252,12 +235,27 @@ export class VsCodeExtension { this.fileSearch, ); + // LLM Log view + this.consoleView = new ContinueConsoleWebviewViewProvider( + this.windowId, + this.extensionContext, + this.core.llmLogger, + ); + + context.subscriptions.push( + vscode.window.registerWebviewViewProvider( + "continue.continueConsoleView", + this.consoleView, + ), + ); + // Commands registerAllCommands( context, this.ide, context, this.sidebar, + this.consoleView, this.configHandler, this.verticalDiffManager, this.core.continueServerClientPromise, @@ -333,14 +331,6 @@ export class VsCodeExtension { ); const sessionInfo = await getControlPlaneSessionInfo(true, false); - this.webviewProtocolPromise.then(async (webviewProtocol) => { - void webviewProtocol.request("didChangeControlPlaneSessionInfo", { - sessionInfo, - }); - - // To make sure continue-proxy models and anything else requiring it get updated access token - this.configHandler.reloadConfig(); - }); void this.core.invoke("didChangeControlPlaneSessionInfo", { sessionInfo, }); @@ -401,6 +391,12 @@ export class VsCodeExtension { ), ); + const linkProvider = vscode.languages.registerDocumentLinkProvider( + { language: "yaml" }, + new ConfigYamlDocumentLinkProvider(), + ); + context.subscriptions.push(linkProvider); + this.ide.onDidChangeActiveTextEditor((filepath) => { void this.core.invoke("didChangeActiveTextEditor", { filepath }); }); @@ -408,10 +404,7 @@ export class VsCodeExtension { vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { const settings = await this.ide.getIdeSettings(); - const webviewProtocol = await this.webviewProtocolPromise; - void webviewProtocol.request("didChangeIdeSettings", { - settings, - }); + void this.core.invoke("config/ideSettingsUpdate", settings); } }); } diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 23669305a..9563eb8a9 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -18,6 +18,7 @@ import { stripImages } from "core/util/messageContent"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { ILLM } from "core"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -28,7 +29,6 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -133,6 +133,7 @@ export class VsCodeMessenger { streamId: data.streamId, status: "streaming", fileContent: data.text, + toolCallId: data.toolCallId, }); if (data.filepath) { @@ -164,6 +165,7 @@ export class VsCodeMessenger { status: "closed", numDiffs: 0, fileContent: data.text, + toolCallId: data.toolCallId, }); return; @@ -211,6 +213,7 @@ export class VsCodeMessenger { diffLines, instant, data.streamId, + data.toolCallId, ); } else { const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`; @@ -232,6 +235,7 @@ export class VsCodeMessenger { undefined, rangeToApplyTo, data.text, + data.toolCallId, ); } }); @@ -391,6 +395,9 @@ export class VsCodeMessenger { this.onWebviewOrCore("getSearchResults", async (msg) => { return ide.getSearchResults(msg.data.query); }); + this.onWebviewOrCore("getFileResults", async (msg) => { + return ide.getFileResults(msg.data.pattern); + }); this.onWebviewOrCore("subprocess", async (msg) => { return ide.subprocess(msg.data.command, msg.data.cwd); }); diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b35899669..a7a58f894 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -9,6 +9,7 @@ "strict": true, "esModuleInterop": true, "resolveJsonModule": true, + "skipLibCheck": true, "types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007 }, "include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"], diff --git a/gui/indexConsole.html b/gui/indexConsole.html new file mode 100644 index 000000000..aaa69903b --- /dev/null +++ b/gui/indexConsole.html @@ -0,0 +1,13 @@ + + + + + + + Continue + + +
+ + + diff --git a/gui/package-lock.json b/gui/package-lock.json index b0918360d..69c571f84 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,8 +7,8 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.63", - "@headlessui/react": "^1.7.17", + "@continuedev/config-yaml": "^1.0.71", + "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", @@ -25,7 +25,7 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", - "@types/vscode-webview": "^1.57.1", + "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", "downshift": "^7.6.0", @@ -59,10 +59,10 @@ "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", "table": "^6.8.1", + "tailwind-merge": "^3.0.2", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", - "uuid": "^9.0.1", - "vscode-webview": "^1.0.1-beta.1" + "uuid": "^9.0.1" }, "devDependencies": { "@swc/cli": "^0.3.14", @@ -91,9 +91,9 @@ "jsdom": "^25.0.1", "postcss": "^8.4.21", "tailwindcss": "^3.2.7", - "typescript": "^4.9.3", + "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.1.0", + "vite": "^4.5.11", "vitest": "^2.1.3" }, "engines": { @@ -105,13 +105,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", @@ -128,6 +128,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", @@ -196,7 +197,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" @@ -551,9 +553,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.63", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.63.tgz", - "integrity": "sha512-KBfyOUU/mWOXeNf6v+4IfMkbvfEEe/YP6n/g/reJBhrpApchG2A/P11JviH87N2To1SrhZxnW//0g5FIGupDFw==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", + "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -1098,25 +1100,53 @@ "@floating-ui/utils": "^0.2.8" } }, + "node_modules/@floating-ui/react": { + "version": "0.26.28", + "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.26.28.tgz", + "integrity": "sha512-yORQuuAtVpiRjpMhdc0wJj06b9JFjrYF4qp96j++v2NBpbi6SEGF7donUJ3TMieerQ6qVkAv1tgr7L4r5roTqw==", + "dependencies": { + "@floating-ui/react-dom": "^2.1.2", + "@floating-ui/utils": "^0.2.8", + "tabbable": "^6.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.2.tgz", + "integrity": "sha512-06okr5cgPzMNBy+Ycse2A6udMi4bqwW/zgBF/rwjcNqWkyr82Mcg8b0vjX8OJpZFy/FKjJmw6wV7t44kK6kW7A==", + "dependencies": { + "@floating-ui/dom": "^1.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, "node_modules/@floating-ui/utils": { "version": "0.2.8", "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.8.tgz", "integrity": "sha512-kym7SodPp8/wloecOpcmSnWJsK7M0E5Wg8UcFA+uO4B9s5d0ywXOEro/8HM9x0rW+TljRzul/14UYz3TleT3ig==" }, "node_modules/@headlessui/react": { - "version": "1.7.19", - "resolved": "https://registry.npmjs.org/@headlessui/react/-/react-1.7.19.tgz", - "integrity": "sha512-Ll+8q3OlMJfJbAKM/+/Y2q6PPYbryqNTXDbryx7SXLIDamkF6iQFbriYHga0dY44PvDhvvBWCx1Xj4U5+G4hOw==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@headlessui/react/-/react-2.2.0.tgz", + "integrity": "sha512-RzCEg+LXsuI7mHiSomsu/gBJSjpupm6A1qIZ5sWjd7JhARNlMiSA4kKfJpCKwU9tE+zMRterhhrP74PvfJrpXQ==", "dependencies": { - "@tanstack/react-virtual": "^3.0.0-beta.60", - "client-only": "^0.0.1" + "@floating-ui/react": "^0.26.16", + "@react-aria/focus": "^3.17.1", + "@react-aria/interactions": "^3.21.3", + "@tanstack/react-virtual": "^3.8.1" }, "engines": { "node": ">=10" }, "peerDependencies": { - "react": "^16 || ^17 || ^18", - "react-dom": "^16 || ^17 || ^18" + "react": "^18 || ^19 || ^19.0.0-rc", + "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "node_modules/@heroicons/react": { @@ -1702,6 +1732,96 @@ "url": "https://opencollective.com/popperjs" } }, + "node_modules/@react-aria/focus": { + "version": "3.20.1", + "resolved": "https://registry.npmjs.org/@react-aria/focus/-/focus-3.20.1.tgz", + "integrity": "sha512-lgYs+sQ1TtBrAXnAdRBQrBo0/7o5H6IrfDxec1j+VRpcXL0xyk0xPq+m3lZp8typzIghqDgpnKkJ5Jf4OrzPIw==", + "dependencies": { + "@react-aria/interactions": "^3.24.1", + "@react-aria/utils": "^3.28.1", + "@react-types/shared": "^3.28.0", + "@swc/helpers": "^0.5.0", + "clsx": "^2.0.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", + "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-aria/interactions": { + "version": "3.24.1", + "resolved": "https://registry.npmjs.org/@react-aria/interactions/-/interactions-3.24.1.tgz", + "integrity": "sha512-OWEcIC6UQfWq4Td5Ptuh4PZQ4LHLJr/JL2jGYvuNL6EgL3bWvzPrRYIF/R64YbfVxIC7FeZpPSkS07sZ93/NoA==", + "dependencies": { + "@react-aria/ssr": "^3.9.7", + "@react-aria/utils": "^3.28.1", + "@react-stately/flags": "^3.1.0", + "@react-types/shared": "^3.28.0", + "@swc/helpers": "^0.5.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", + "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-aria/ssr": { + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/@react-aria/ssr/-/ssr-3.9.7.tgz", + "integrity": "sha512-GQygZaGlmYjmYM+tiNBA5C6acmiDWF52Nqd40bBp0Znk4M4hP+LTmI0lpI1BuKMw45T8RIhrAsICIfKwZvi2Gg==", + "dependencies": { + "@swc/helpers": "^0.5.0" + }, + "engines": { + "node": ">= 12" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-aria/utils": { + "version": "3.28.1", + "resolved": "https://registry.npmjs.org/@react-aria/utils/-/utils-3.28.1.tgz", + "integrity": "sha512-mnHFF4YOVu9BRFQ1SZSKfPhg3z+lBRYoW5mLcYTQihbKhz48+I1sqRkP7ahMITr8ANH3nb34YaMME4XWmK2Mgg==", + "dependencies": { + "@react-aria/ssr": "^3.9.7", + "@react-stately/flags": "^3.1.0", + "@react-stately/utils": "^3.10.5", + "@react-types/shared": "^3.28.0", + "@swc/helpers": "^0.5.0", + "clsx": "^2.0.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1", + "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-stately/flags": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@react-stately/flags/-/flags-3.1.0.tgz", + "integrity": "sha512-KSHOCxTFpBtxhIRcKwsD1YDTaNxFtCYuAUb0KEihc16QwqZViq4hasgPBs2gYm7fHRbw7WYzWKf6ZSo/+YsFlg==", + "dependencies": { + "@swc/helpers": "^0.5.0" + } + }, + "node_modules/@react-stately/utils": { + "version": "3.10.5", + "resolved": "https://registry.npmjs.org/@react-stately/utils/-/utils-3.10.5.tgz", + "integrity": "sha512-iMQSGcpaecghDIh3mZEpZfoFH3ExBwTtuBEcvZ2XnGzCgQjeYXcMdIUwAfVQLXFTdHUHGF6Gu6/dFrYsCzySBQ==", + "dependencies": { + "@swc/helpers": "^0.5.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "node_modules/@react-types/shared": { + "version": "3.28.0", + "resolved": "https://registry.npmjs.org/@react-types/shared/-/shared-3.28.0.tgz", + "integrity": "sha512-9oMEYIDc3sk0G5rysnYvdNrkSg7B04yTKl50HHSZVbokeHpnU0yRmsDaWb9B/5RprcKj8XszEk5guBO8Sa/Q+Q==", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, "node_modules/@reduxjs/toolkit": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.3.0.tgz", @@ -2201,6 +2321,14 @@ "integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==", "dev": true }, + "node_modules/@swc/helpers": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz", + "integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==", + "dependencies": { + "tslib": "^2.8.0" + } + }, "node_modules/@swc/types": { "version": "0.1.12", "resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.12.tgz", @@ -3107,11 +3235,6 @@ "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==" }, - "node_modules/@types/vscode-webview": { - "version": "1.57.5", - "resolved": "https://registry.npmjs.org/@types/vscode-webview/-/vscode-webview-1.57.5.tgz", - "integrity": "sha512-iBAUYNYkz+uk1kdsq05fEcoh8gJmwT3lqqFPN7MGyjQ3HVloViMdo7ZJ8DFIP8WOK74PjOEilosqAyxV2iUFUw==" - }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.16.0.tgz", @@ -4265,11 +4388,6 @@ "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==" }, - "node_modules/client-only": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", - "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==" - }, "node_modules/clone-response": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz", @@ -4282,6 +4400,14 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "engines": { + "node": ">=6" + } + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -5827,19 +5953,6 @@ "url": "https://github.com/sponsors/rawify" } }, - "node_modules/fs-extra": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", - "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=12" - } - }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -6043,11 +6156,6 @@ "url": "https://github.com/sindresorhus/got?sponsor=1" } }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" - }, "node_modules/graphemer": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", @@ -7534,17 +7642,6 @@ "node": ">=6" } }, - "node_modules/jsonfile": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", - "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", - "dependencies": { - "universalify": "^2.0.0" - }, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, "node_modules/jsx-ast-utils": { "version": "3.3.5", "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", @@ -11398,6 +11495,11 @@ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, + "node_modules/tabbable": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.2.0.tgz", + "integrity": "sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==" + }, "node_modules/table": { "version": "6.8.2", "resolved": "https://registry.npmjs.org/table/-/table-6.8.2.tgz", @@ -11413,6 +11515,15 @@ "node": ">=10.0.0" } }, + "node_modules/tailwind-merge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.0.2.tgz", + "integrity": "sha512-l7z+OYZ7mu3DTqrL88RiKrKIqO3NcpEO8V/Od04bNpvk0kiIFndGEoqfuzvj4yuhRkHKjRkII2z+KS2HfPcSxw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, "node_modules/tailwindcss": { "version": "3.4.12", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.12.tgz", @@ -11730,9 +11841,9 @@ "dev": true }, "node_modules/tslib": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", - "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==" + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==" }, "node_modules/type-check": { "version": "0.4.0", @@ -11833,16 +11944,16 @@ } }, "node_modules/typescript": { - "version": "4.9.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", - "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", + "version": "5.8.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.2.tgz", + "integrity": "sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ==", "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { - "node": ">=4.2.0" + "node": ">=14.17" } }, "node_modules/typescript-eslint": { @@ -12033,14 +12144,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/universalify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", - "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", - "engines": { - "node": ">= 10.0.0" - } - }, "node_modules/update-browserslist-db": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", @@ -12145,9 +12248,9 @@ } }, "node_modules/vite": { - "version": "4.5.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", - "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", + "version": "4.5.11", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.11.tgz", + "integrity": "sha512-4mVdhLkZ0vpqZLGJhNm+X1n7juqXApEMGlUXcOQawA45UmpxivOYaMBkI/Js3FlBsNA8hCgEnX5X04moFitSGw==", "dev": true, "license": "MIT", "dependencies": { @@ -13282,14 +13385,6 @@ } } }, - "node_modules/vscode-webview": { - "version": "1.0.1-beta.1", - "resolved": "https://registry.npmjs.org/vscode-webview/-/vscode-webview-1.0.1-beta.1.tgz", - "integrity": "sha512-8H2icqlb93qIvZs7Me/0sALMqJrX2e2W7JVE0mfK8exUPETP9Bmg+feivaByd1Xbg78lcKaNF9ZRrIFSenUVxQ==", - "dependencies": { - "fs-extra": "^10.0.0" - } - }, "node_modules/w3c-keyname": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", diff --git a/gui/package.json b/gui/package.json index 6724bd757..2d4ed109b 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,8 +15,8 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.63", - "@headlessui/react": "^1.7.17", + "@continuedev/config-yaml": "^1.0.71", + "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", @@ -33,7 +33,7 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", - "@types/vscode-webview": "^1.57.1", + "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", "downshift": "^7.6.0", @@ -67,10 +67,10 @@ "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", "table": "^6.8.1", + "tailwind-merge": "^3.0.2", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", - "uuid": "^9.0.1", - "vscode-webview": "^1.0.1-beta.1" + "uuid": "^9.0.1" }, "devDependencies": { "@swc/cli": "^0.3.14", @@ -99,9 +99,9 @@ "jsdom": "^25.0.1", "postcss": "^8.4.21", "tailwindcss": "^3.2.7", - "typescript": "^4.9.3", + "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.1.0", + "vite": "^4.5.11", "vitest": "^2.1.3" }, "engine-strict": true, diff --git a/gui/public/logos/docker.png b/gui/public/logos/docker.png new file mode 100644 index 000000000..600476cfe Binary files /dev/null and b/gui/public/logos/docker.png differ diff --git a/gui/public/logos/inception.png b/gui/public/logos/inception.png new file mode 100644 index 000000000..4ef5ad6a0 Binary files /dev/null and b/gui/public/logos/inception.png differ diff --git a/gui/src/App.tsx b/gui/src/App.tsx index deb1e376f..18c68721f 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -1,9 +1,9 @@ import { RouterProvider, createMemoryRouter } from "react-router-dom"; import Layout from "./components/Layout"; +import { MainEditorProvider } from "./components/mainInput/TipTapEditor"; import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; -import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; import ConfigPage from "./pages/config"; import ConfigErrorPage from "./pages/config-error"; import ErrorPage from "./pages/error"; @@ -34,14 +34,6 @@ const router = createMemoryRouter([ path: "/stats", element: , }, - { - path: "/addModel", - element: , - }, - { - path: "/addModel/provider/:providerName", - element: , - }, { path: ROUTES.CONFIG_ERROR, element: , @@ -66,9 +58,11 @@ function SetupListeners() { function App() { return ( - - - + + + + + ); diff --git a/gui/src/components/CodeToEditCard/AddFileButton.tsx b/gui/src/components/CodeToEditCard/AddFileButton.tsx index b1e1966fe..d051f847f 100644 --- a/gui/src/components/CodeToEditCard/AddFileButton.tsx +++ b/gui/src/components/CodeToEditCard/AddFileButton.tsx @@ -1,9 +1,14 @@ +import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; -import { Listbox } from "@headlessui/react"; -import { addCodeToEdit } from "../../redux/slices/sessionSlice"; import { useAppDispatch } from "../../redux/hooks"; +import { addCodeToEdit } from "../../redux/slices/sessionSlice"; +import { + Listbox, + ListboxButton, + ListboxOption, + ListboxOptions, +} from "../ui/Listbox"; export interface AddFileButtonProps { onClick: () => void; @@ -29,20 +34,20 @@ export default function AddFileButton({ onClick }: AddFileButtonProps) { return (
-
{ e.preventDefault(); e.stopPropagation(); onClick(); }} > - - + + Add file
@@ -50,16 +55,11 @@ export default function AddFileButton({ onClick }: AddFileButtonProps) {
- + - - - Add all open files - - + + Add all open files +
); diff --git a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx index 9450ba480..d096f90a2 100644 --- a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx +++ b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx @@ -1,10 +1,15 @@ -import { Combobox } from "@headlessui/react"; import { ContextSubmenuItemWithProvider } from "core"; import { useEffect, useRef, useState } from "react"; +import { + Combobox, + ComboboxButton, + ComboboxInput, + ComboboxOption, + ComboboxOptions, +} from "../../components/ui/Combobox"; import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders"; import { useAppSelector } from "../../redux/hooks"; import FileIcon from "../FileIcon"; - export interface AddFileComboboxProps { onSelect: (filepaths: string[]) => void | Promise; onEscape: () => void | Promise; @@ -54,8 +59,8 @@ export default function AddFileCombobox({ > {({ open }) => (
- - + { if (!open) { @@ -65,7 +70,7 @@ export default function AddFileCombobox({ onFocus={() => { buttonRef.current?.click(); }} - className="bg-vsc-background border-lightgray text-vsc-foreground box-border w-full rounded border border-solid py-0.5 pl-2 focus:outline-none" + className="bg-vsc-background border-lightgray text-vsc-foreground box-border w-full rounded border border-solid py-0.5 pl-2 text-xs focus:outline-none" onChange={(event) => setQuery(event.target.value)} placeholder="Type to search files..." onKeyDown={(e) => { @@ -75,10 +80,10 @@ export default function AddFileCombobox({ }} /> - + {filteredFiles.length > 0 ? ( filteredFiles.map((file) => ( - @@ -109,14 +114,14 @@ export default function AddFileCombobox({
)} - + )) ) : (
No results
)} - +
)} diff --git a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx index 99149ba5f..6e16d4d4f 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx @@ -1,16 +1,16 @@ +import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import type { CodeToEdit } from "core"; import { useContext, useState } from "react"; import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import CodeToEditListItem from "./CodeToEditListItem"; -import type { CodeToEdit } from "core"; -import AddFileButton from "./AddFileButton"; -import AddFileCombobox from "./AddFileCombobox"; -import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; import { addCodeToEdit, removeCodeToEdit, } from "../../redux/slices/sessionSlice"; +import AddFileButton from "./AddFileButton"; +import AddFileCombobox from "./AddFileCombobox"; +import CodeToEditListItem from "./CodeToEditListItem"; export default function CodeToEditCard() { const dispatch = useDispatch(); @@ -18,12 +18,12 @@ export default function CodeToEditCard() { const [showAddFileCombobox, setShowAddFileCombobox] = useState(false); const codeToEdit = useAppSelector((state) => state.session.codeToEdit); - const title = + const itemCount = codeToEdit.length === 0 - ? "Code to edit" + ? "" : codeToEdit.length === 1 - ? "Code to edit (1 item)" - : `Code to edit (${codeToEdit.length} items)`; + ? "(1 item)" + : `(${codeToEdit.length} items)`; function onDelete(rif: CodeToEdit) { dispatch(removeCodeToEdit(rif)); @@ -57,7 +57,11 @@ export default function CodeToEditCard() { return (
- {title} +
+ Code to edit + {itemCount} +
+ setShowAddFileCombobox(true)} />
diff --git a/gui/src/components/ConversationStarters/ConversationStarterCard.tsx b/gui/src/components/ConversationStarters/ConversationStarterCard.tsx index f0428a723..29ff81833 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCard.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCard.tsx @@ -1,7 +1,5 @@ import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; import { SlashCommandDescription } from "core"; -import { useState } from "react"; -import { defaultBorderRadius, vscInputBackground } from ".."; interface ConversationStarterCardProps { command: SlashCommandDescription; @@ -12,26 +10,20 @@ export function ConversationStarterCard({ command, onClick, }: ConversationStarterCardProps) { - const [isHovered, setIsHovered] = useState(false); - return (
setIsHovered(true)} - onMouseLeave={() => setIsHovered(false)} + className="bg-vsc-input-background mb-2 w-full rounded-md shadow-md hover:cursor-pointer hover:brightness-110" onClick={() => onClick(command)} >
-
+
{command.name}
-
{command.description}
+ {command.description && ( +
{command.description}
+ )}
diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 2a29d0749..776c0721b 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -1,37 +1,61 @@ import { SlashCommandDescription } from "core"; -import { useAppDispatch } from "../../redux/hooks"; -import { setMainEditorContentTrigger } from "../../redux/slices/sessionSlice"; -import { getParagraphNodeFromString } from "../mainInput/utils"; +import { useState } from "react"; +import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { useMainEditor } from "../mainInput/TipTapEditor"; import { ConversationStarterCard } from "./ConversationStarterCard"; -import { useBookmarkedSlashCommands } from "./useBookmarkedSlashCommands"; -const NUM_CARDS_TO_RENDER = 3; +const NUM_CARDS_TO_RENDER = 5; +/** + * Displays a grid of conversation starter cards for bookmarked slash commands + */ export function ConversationStarterCards() { const dispatch = useAppDispatch(); - const { cmdsSortedByBookmark } = useBookmarkedSlashCommands(); + const { mainEditor } = useMainEditor(); + const [showAll, setShowAll] = useState(false); + const { isCommandBookmarked } = useBookmarkedSlashCommands(); + const slashCommands = useAppSelector( + (state) => state.config.config.slashCommands ?? [], + ); + + const bookmarkedSlashCommands = slashCommands.filter((command) => + isCommandBookmarked(command.name), + ); function onClick(command: SlashCommandDescription) { - if (command.prompt) { - dispatch( - setMainEditorContentTrigger(getParagraphNodeFromString(command.prompt)), - ); - } + mainEditor?.commands.insertPrompt(command); } - if (!cmdsSortedByBookmark || cmdsSortedByBookmark.length === 0) { + if (bookmarkedSlashCommands.length === 0) { return null; } + const visibleCommands = showAll + ? bookmarkedSlashCommands + : bookmarkedSlashCommands.slice(0, NUM_CARDS_TO_RENDER); + + const remainingCount = bookmarkedSlashCommands.length - NUM_CARDS_TO_RENDER; + return ( -
- {cmdsSortedByBookmark.slice(0, NUM_CARDS_TO_RENDER).map((command, i) => ( - - ))} +
+
+ {visibleCommands.map((command, i) => ( + + ))} +
+ {bookmarkedSlashCommands.length > NUM_CARDS_TO_RENDER && ( + setShowAll(!showAll)} + > + {showAll ? "Show less" : `Show ${remainingCount} more...`} + + )}
); } diff --git a/gui/src/components/ConversationStarters/useBookmarkedSlashCommands.ts b/gui/src/components/ConversationStarters/useBookmarkedSlashCommands.ts deleted file mode 100644 index 786ae379a..000000000 --- a/gui/src/components/ConversationStarters/useBookmarkedSlashCommands.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { SlashCommandDescription } from "core"; -import { usePostHog } from "posthog-js/react"; -import { useMemo } from "react"; -import { - bookmarkSlashCommand, - selectBookmarkedSlashCommands, - selectSelectedProfileId, - unbookmarkSlashCommand, -} from "../../redux"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { isDeprecatedCommandName, sortCommandsByBookmarkStatus } from "./utils"; - -export function useBookmarkedSlashCommands() { - const dispatch = useAppDispatch(); - const posthog = usePostHog(); - - const slashCommands = - useAppSelector((state) => state.config.config.slashCommands) ?? []; - const selectedProfileId = useAppSelector(selectSelectedProfileId); - const bookmarkedCommands = useAppSelector(selectBookmarkedSlashCommands); - - const filteredSlashCommands = slashCommands.filter(isDeprecatedCommandName); - - // Create a map of command names to bookmark status - const bookmarkStatuses = useMemo(() => { - const statuses: Record = {}; - if (selectedProfileId) { - filteredSlashCommands.forEach((command) => { - statuses[command.name] = bookmarkedCommands.includes(command.name); - }); - } - return statuses; - }, [filteredSlashCommands, bookmarkedCommands, selectedProfileId]); - - // Sort commands by bookmark status - const cmdsSortedByBookmark = useMemo( - () => - sortCommandsByBookmarkStatus(filteredSlashCommands, bookmarkedCommands), - [filteredSlashCommands, bookmarkedCommands], - ); - - const toggleBookmark = (command: SlashCommandDescription) => { - const isBookmarked = bookmarkStatuses[command.name]; - - posthog.capture("toggle_bookmarked_slash_command", { - isBookmarked, - }); - - if (isBookmarked) { - dispatch( - unbookmarkSlashCommand({ - commandName: command.name, - }), - ); - } else { - dispatch( - bookmarkSlashCommand({ - commandName: command.name, - }), - ); - } - }; - - return { - cmdsSortedByBookmark, - bookmarkStatuses, - toggleBookmark, - }; -} diff --git a/gui/src/components/ConversationStarters/utils.ts b/gui/src/components/ConversationStarters/utils.ts index d37b45416..1f9ef09ae 100644 --- a/gui/src/components/ConversationStarters/utils.ts +++ b/gui/src/components/ConversationStarters/utils.ts @@ -1,32 +1,5 @@ import { SlashCommandDescription } from "core"; -import { - defaultSlashCommandsJetBrains, - defaultSlashCommandsVscode, -} from "core/config/default"; -import { isJetBrains } from "../../util"; - -/** - * The commands filtered here are currently inserted into the slash commands array during - * intermediary config loading, but once we get the actual prompts for an assistant, - * they are overwritten. - * - * Additionally, these default commands are all deprecated. - * - * If we don't manually filter them out, then they are displayed in the UI - * while the assistant is still loading. - * - * Once these commands are no longer inserted during intermediary config loading, - * this function can be removed. - */ -export function isDeprecatedCommandName(command: SlashCommandDescription) { - const defaultCommands = isJetBrains() - ? defaultSlashCommandsJetBrains - : defaultSlashCommandsVscode; - - return !defaultCommands.find( - (defaultCommand) => defaultCommand.name === command.name, - ); -} +import {} from "core/config/default"; /** * Sorts commands with bookmarked ones first diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx index c546becd4..bf6327c35 100644 --- a/gui/src/components/ExploreHubCard/index.tsx +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -23,12 +23,17 @@ export function ExploreHubCard() { return dispatch(setIsExploreDialogOpen(false)); }} > -
-

Create Your Own Assistant

+
+
+

+ Create Your Own Assistant +

-

- Discover and remix popular assistants, or create your own from scratch -

+

+ Discover and remix popular assistants, or create your own from + scratch +

+