diff --git a/.continueignore b/.continueignore index 79e924012..50684c187 100644 --- a/.continueignore +++ b/.continueignore @@ -5,4 +5,5 @@ docs/docs/languages .vscode/ .archive/ **/*.scm -**/*.diff \ No newline at end of file +**/*.diff +.continue/ \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..e0b32680f --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @continuedev/continue-code-reviewers diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 258ec33e2..bf8ce2ecb 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -275,7 +275,7 @@ jobs: cd core npm test env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }} + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} @@ -303,7 +303,13 @@ jobs: cd extensions/vscode npm ci npm run e2e:compile - FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then + # Exclude SSH tests for forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .) + else + # Include all tests for non-forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + fi echo "test_file_matrix<> $GITHUB_OUTPUT echo "$FILES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT @@ -409,6 +415,13 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + # We don't want to cache the Continue extension, so it is deleted at the end of the job + - uses: actions/cache@v4 + id: test-extensions-cache + with: + path: extensions/vscode/e2e/.test-extensions + key: CONSTANT + - name: Download build artifact uses: actions/download-artifact@v4 with: @@ -436,7 +449,7 @@ jobs: chmod 600 ~/.ssh/id_rsa ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config - if: ${{ github.event.pull_request.head.repo.fork == false }} + if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }} - name: Set up Xvfb run: | @@ -446,10 +459,15 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} + IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 + - name: Delete continue from test extensions + run: | + cd extensions/vscode + rm -rf e2e/.test-extensions/continue* + - name: Upload e2e test screenshots if: failure() uses: actions/upload-artifact@v4 diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml new file mode 100644 index 000000000..067f4c60f --- /dev/null +++ b/.github/workflows/stale-issue-helper.yaml @@ -0,0 +1,25 @@ +name: "Label / close stale issues" +on: + schedule: + - cron: "30 1 * * *" + +jobs: + stale: + permissions: + issues: write + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!" + stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." + days-before-stale: 90 + days-before-close: 10 + days-before-pr-stale: -1 + days-before-pr-close: -1 + operations-per-run: 1000 + stale-issue-label: "stale" + stale-pr-label: "stale" + exempt-issue-labels: "needs-triage,no-stale,high,highest" + exempt-pr-labels: "no-stale" diff --git a/.gitignore b/.gitignore index f331ec68c..763b96238 100644 --- a/.gitignore +++ b/.gitignore @@ -168,4 +168,5 @@ extensions/.continue-debug/ *.vsix -.continuerules \ No newline at end of file +.continuerules +**/.continue/assistants/ \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index 15619929d..0c55de44d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -14,4 +14,5 @@ gui/dist **/.continueignore CHANGELOG.md **/continue_tutorial.py -**/node_modules \ No newline at end of file +**/node_modules +**/CODEOWNERS \ No newline at end of file diff --git a/README.md b/README.md index bdfa8533c..fc07289d7 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@
-**[Continue](https://docs.continue.dev) enables to developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)** +**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
diff --git a/binary/package-lock.json b/binary/package-lock.json index ca7d26b85..c823d785e 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -41,14 +41,14 @@ }, "../core": { "name": "@continuedev/core", - "version": "1.0.13", + "version": "1.1.0", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.620.1", - "@aws-sdk/client-sagemaker-runtime": "^3.621.0", - "@aws-sdk/credential-providers": "^3.620.1", + "@aws-sdk/client-bedrock-runtime": "^3.758.0", + "@aws-sdk/client-sagemaker-runtime": "^3.758.0", + "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.63", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", @@ -113,7 +113,7 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", - "@types/diff": "^5.2.2", + "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", diff --git a/core/.eslintrc.json b/core/.eslintrc.json index ce1bc2575..e541d57c1 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -5,8 +5,18 @@ "project": "./tsconfig.json" }, "rules": { - "quotes": ["warn", "double", {}], + "quotes": ["off", "double", {}], "@typescript-eslint/naming-convention": "off", - "@typescript-eslint/no-floating-promises": "warn" + "@typescript-eslint/no-floating-promises": "off", + "import/order": "off", + "curly": "off", + "@typescript-eslint/semi": "off", + "eqeqeq": "error", + "complexity": ["error", { "max": 38 }], + "max-lines-per-function": ["error", { "max": 996 }], + "max-statements": ["error", { "max": 112 }], + "max-depth": ["error", { "max": 6 }], + "max-nested-callbacks": ["error", { "max": 4 }], + "max-params": ["error", { "max": 11 }] } } diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 695c9afeb..01688b694 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -73,6 +73,8 @@ export class StreamTransformPipeline { ); const timeoutValue = helper.options.modelTimeout; + + lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!); const finalGenerator = streamWithNewLines(lineGenerator); diff --git a/core/autocomplete/util/completionTestUtils.test.ts b/core/autocomplete/util/completionTestUtils.test.ts new file mode 100644 index 000000000..bdf4e209a --- /dev/null +++ b/core/autocomplete/util/completionTestUtils.test.ts @@ -0,0 +1,65 @@ +import { + processTestCase, + type CompletionTestCase, +} from "./completionTestUtils"; + +describe("processTestCase utility", () => { + it("processes simple console.log completion", () => { + const testCase: CompletionTestCase = { + original: "console.log(|cur||till|)", + completion: "\"foo,\", bar", + }; + + expect(processTestCase(testCase)).toEqual({ + input: { + lastLineOfCompletionText: "\"foo,\", bar", + currentText: ")", + cursorPosition: "console.log(".length, + }, + expectedResult: { + completionText: "\"foo,\", bar", + }, + }); + }); + + it("processes simple console.log completion with overwriting", () => { + const testCase: CompletionTestCase = { + original: "console.log(|cur|)|till|", + completion: "\"foo,\", bar);", + }; + + expect(processTestCase(testCase)).toEqual({ + input: { + lastLineOfCompletionText: "\"foo,\", bar);", + currentText: ")", + cursorPosition: "console.log(".length, + }, + expectedResult: { + completionText: "\"foo,\", bar);", + range: { + start: "console.log(".length, + end: "console.log()".length, + }, + }, + }); + }); + + it("partially applying completion", () => { + const testCase: CompletionTestCase = { + original: "|cur||till|fetch(\"https://example.com\");", + completion: "await fetch(\"https://example.com\");", + appliedCompletion: "await ", + }; + + expect(processTestCase(testCase)).toEqual({ + input: { + lastLineOfCompletionText: "await fetch(\"https://example.com\");", + currentText: "fetch(\"https://example.com\");", + cursorPosition: 0, + }, + expectedResult: { + completionText: "await ", + }, + }); + }); +}); diff --git a/core/autocomplete/util/completionTestUtils.ts b/core/autocomplete/util/completionTestUtils.ts new file mode 100644 index 000000000..a686d59e8 --- /dev/null +++ b/core/autocomplete/util/completionTestUtils.ts @@ -0,0 +1,91 @@ +export interface CompletionTestCase { + original: string; // Text with |cur| and |till| markers + completion: string; // Text to insert/overwrite + appliedCompletion?: string | null; + cursorMarker?: string; + tillMarker?: string; +} + +export interface ProcessedTestCase { + input: { + lastLineOfCompletionText: string; + currentText: string; + cursorPosition: number; + }; + expectedResult: { + completionText: string; + range?: { + start: number; + end: number; + }; + }; +} + +/** + * Transforms human-readable test case into input and expected results. + * + * - `original`: Your original text with |cur| marking where the cursor is before completion, + * and |till| marking where the cursor should be after accepting completion (and this is + * the end of the actual applied completion) + * - `completion`: LLM completion output + * - `appliedCompletion` (optional): part of the LLM completion output that is actually applied + * (written between |cur| and |till| in the original) + * + * For example, you have this line: + * + * console.log(""); + * + * and expect it to be completed this way: + * + * console.log("foo: ", bar); + * + * with your completion coming from LLM being: `'foo: ", bar);'` + * + * Your input to this function should be: + * - original: `'console.log("|cur|"|till|);'` + * - completion: `'foo: ", bar);'` + * - appliedCompletion: `'foo: ", bar'` + * + * Output: input and expected output of {@link core/autocomplete/util/processSingleLineCompletion/processSingleLineCompletion|processSingleLineCompletion()} + * + */ +export function processTestCase({ + original, + completion, + appliedCompletion = null, + cursorMarker = "|cur|", + tillMarker = "|till|", +}: CompletionTestCase): ProcessedTestCase { + // Validate cursor marker + if (!original.includes(cursorMarker)) { + throw new Error("Cursor marker not found in original text"); + } + + const cursorPos = original.indexOf(cursorMarker); + original = original.replace(cursorMarker, ""); + + let tillPos = original.indexOf(tillMarker); + if (tillPos < 0) { + tillPos = cursorPos; + } else { + original = original.replace(tillMarker, "") + } + + // Calculate currentText based on what's between cursor and till marker + const currentText = original.substring(cursorPos); + + return { + input: { + lastLineOfCompletionText: completion, + currentText, + cursorPosition: cursorPos, + }, + expectedResult: { + completionText: appliedCompletion || completion, + range: cursorPos === tillPos ? undefined : { + start: cursorPos, + end: tillPos, + }, + }, + }; +} \ No newline at end of file diff --git a/core/autocomplete/util/processSingleLineCompletion.test.ts b/core/autocomplete/util/processSingleLineCompletion.test.ts new file mode 100644 index 000000000..8081ac20c --- /dev/null +++ b/core/autocomplete/util/processSingleLineCompletion.test.ts @@ -0,0 +1,97 @@ +import { processTestCase } from "./completionTestUtils"; +import { processSingleLineCompletion } from "./processSingleLineCompletion"; + +describe("processSingleLineCompletion", () => { + + it("should handle simple end of line completion", () => { + const testCase = processTestCase({ + original: "console.log(|cur|", + completion: "\"Hello, world!\")", + }); + + const result = processSingleLineCompletion( + testCase.input.lastLineOfCompletionText, + testCase.input.currentText, + testCase.input.cursorPosition + ); + + expect(result).toEqual(testCase.expectedResult); + }); + + it("should handle midline insert repeating the end of line", () => { + const testCase = processTestCase({ + original: "console.log(|cur|);|till|", + completion: "\"Hello, world!\");", + }); + + const result = processSingleLineCompletion( + testCase.input.lastLineOfCompletionText, + testCase.input.currentText, + testCase.input.cursorPosition + ); + + expect(result).toEqual(testCase.expectedResult); + }); + + it("should handle midline insert repeating the end of line plus adding a semicolon", () => { + const testCase = processTestCase({ + original: "console.log(|cur|)|till|", + completion: "\"Hello, world!\");", + }); + + const result = processSingleLineCompletion( + testCase.input.lastLineOfCompletionText, + testCase.input.currentText, + testCase.input.cursorPosition + ); + + expect(result).toEqual(testCase.expectedResult); + }); + + it("should handle simple midline insert", () => { + const testCase = processTestCase({ + original: "console.log(|cur|)", + completion: "\"Hello, world!\"", + }); + + const result = processSingleLineCompletion( + testCase.input.lastLineOfCompletionText, + testCase.input.currentText, + testCase.input.cursorPosition + ); + + expect(result).toEqual(testCase.expectedResult); + }); + + it("should handle complex dif with addition in the beginning", () => { + const testCase = processTestCase({ + original: "console.log(|cur||till|, \"param1\", )", // TODO + completion: "\"Hello world!\", \"param1\", param1);", + appliedCompletion: "\"Hello world!\"" + }); + + const result = processSingleLineCompletion( + testCase.input.lastLineOfCompletionText, + testCase.input.currentText, + testCase.input.cursorPosition + ); + + expect(result).toEqual(testCase.expectedResult); + }); + + it("should handle simple insertion even with random equality", () => { + const testCase = processTestCase({ + original: "print(f\"Foobar length: |cur||till|\")", + completion: "{len(foobar)}", + }); + + const result = processSingleLineCompletion( + testCase.input.lastLineOfCompletionText, + testCase.input.currentText, + testCase.input.cursorPosition + ); + + expect(result).toEqual(testCase.expectedResult); + }); + +}); diff --git a/core/autocomplete/util/processSingleLineCompletion.ts b/core/autocomplete/util/processSingleLineCompletion.ts new file mode 100644 index 000000000..3dc093411 --- /dev/null +++ b/core/autocomplete/util/processSingleLineCompletion.ts @@ -0,0 +1,92 @@ +import * as Diff from "diff"; + +interface SingleLineCompletionResult { + completionText: string; + range?: { + start: number; + end: number; + }; +} + + +interface DiffType { + count?: number; + added?: boolean; + removed?: boolean; + value: string; +} + + +function diffPatternMatches( + diffs: DiffType[], + pattern: DiffPartType[], +): boolean { + if (diffs.length !== pattern.length) { + return false; + } + + for (let i = 0; i < diffs.length; i++) { + const diff = diffs[i]; + const diffPartType: DiffPartType = + !diff.added && !diff.removed ? "=" : diff.added ? "+" : "-"; + + if (diffPartType !== pattern[i]) { + return false; + } + } + + return true; +} + +type DiffPartType = "+" | "-" | "="; + +export function processSingleLineCompletion( + lastLineOfCompletionText: string, + currentText: string, + cursorPosition: number +): SingleLineCompletionResult | undefined { + const diffs: DiffType[] = Diff.diffWords(currentText, lastLineOfCompletionText); + + if (diffPatternMatches(diffs, ["+"])) { + // Just insert, we're already at the end of the line + return { + completionText: lastLineOfCompletionText, + }; + } + + if ( + diffPatternMatches(diffs, ["+", "="]) || + diffPatternMatches(diffs, ["+", "=", "+"]) + ) { + // The model repeated the text after the cursor to the end of the line + return { + completionText: lastLineOfCompletionText, + range: { + start: cursorPosition, + end: currentText.length + cursorPosition, + }, + }; + } + + if ( + diffPatternMatches(diffs, ["+", "-"]) || + diffPatternMatches(diffs, ["-", "+"]) + ) { + // We are midline and the model just inserted without repeating to the end of the line + return { + completionText: lastLineOfCompletionText, + }; + } + + // For any other diff pattern, just use the first added part if available + if (diffs[0]?.added) { + return { + completionText: diffs[0].value, + }; + } + + // Default case: treat as simple insertion + return { + completionText: lastLineOfCompletionText, + }; +} diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts index a9fa332bb..91c9dcd16 100644 --- a/core/commands/slash/mcp.ts +++ b/core/commands/slash/mcp.ts @@ -17,7 +17,7 @@ export function constructMcpSlashCommand( const userInput = context.input.split(" ").slice(1).join(" "); if (args) { args.forEach((arg, i) => { - argsObject[arg] = userInput; + argsObject[arg] = ""; // userInput }); } @@ -35,9 +35,22 @@ export function constructMcpSlashCommand( }; }); + if (messages.length === 0) { + yield "The MCP prompt returned no messages"; + return; + } + + const reversedMessages = [...messages].reverse(); + const messageToAppendInput = + reversedMessages.find((m) => m.role === "user") ?? + reversedMessages.find((m) => m.role === "assistant") ?? + reversedMessages[0]; + messageToAppendInput.content += ` ${userInput}`; + for await (const chunk of context.llm.streamChat( messages, new AbortController().signal, + context.completionOptions, )) { yield renderChatMessage(chunk); } diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index d6fedcafb..b53c8d3a9 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -2,8 +2,7 @@ import ignore from "ignore"; import type { FileType, IDE, SlashCommand } from "../.."; import { - defaultIgnoreDir, - defaultIgnoreFile, + DEFAULT_IGNORE, getGlobalContinueIgArray, gitIgArrayFromFile, } from "../../indexing/ignore"; @@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = { }; async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { - const ig = ignore() - .add(defaultIgnoreDir) - .add(defaultIgnoreFile) - .add(getGlobalContinueIgArray()); + const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray()); const entries = await ide.listDir(dir); const ignoreUri = joinPathsToUri(dir, ".gitignore"); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index b9a0f0896..ddff9bd40 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,5 +1,3 @@ -import * as fs from "node:fs"; - import { ConfigResult, FullSlug } from "@continuedev/config-yaml"; import { @@ -17,9 +15,8 @@ import { } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; -import { localPathToUri } from "../util/pathToUri.js"; +import { getAllAssistantFiles } from "./loadLocalAssistants.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, LOCAL_ONBOARDING_PROVIDER_TITLE, @@ -53,6 +50,7 @@ export class ConfigHandler { private ideSettingsPromise: Promise, private readonly writeLog: (text: string) => Promise, sessionInfoPromise: Promise, + private readonly didSelectOrganization?: (orgId: string | null) => void, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; @@ -86,6 +84,25 @@ export class ConfigHandler { }); } + /** + * Users can define as many local assistants as they want in a `.continue/assistants` folder + */ + private async getLocalAssistantProfiles() { + const assistantFiles = await getAllAssistantFiles(this.ide); + const profiles = assistantFiles.map((assistant) => { + return new LocalProfileLoader( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.writeLog, + assistant, + ); + }); + return profiles.map( + (profile) => new ProfileLifecycleManager(profile, this.ide), + ); + } + /** * Retrieves the titles of additional context providers that are of type "submenu". * @@ -103,8 +120,9 @@ export class ConfigHandler { } 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.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } + try { const configResult = await this.loadConfig(); this.notifyConfigListeners(configResult); @@ -135,14 +153,12 @@ export class ConfigHandler { async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; - if (openProfileId === "local") { + const profile = this.profiles?.find( + (p) => p.profileDescription.id === openProfileId, + ); + if (profile?.profileDescription.profileType === "local") { const ideInfo = await this.ide.getIdeInfo(); - const configYamlPath = getConfigYamlPath(ideInfo.ideType); - if (fs.existsSync(configYamlPath)) { - await this.ide.openFile(localPathToUri(configYamlPath)); - } else { - await this.ide.openFile(localPathToUri(getConfigJsonPath())); - } + await this.ide.openFile(profile.profileDescription.uri); } else { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); @@ -161,35 +177,40 @@ export class ConfigHandler { let profiles: ProfileLifecycleManager[] | null = null; if (!userId) { // Not logged in - profiles = [this.localProfileManager]; + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...allLocalProfiles]; } else { // Logged in const assistants = await this.controlPlaneClient.listAssistants(selectedOrgId); - const hubProfiles = assistants.map((assistant) => { - const profileLoader = new PlatformProfileLoader( - { - ...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), - ); + 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); - }); + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); if (selectedOrgId === null) { // Personal - profiles = [...hubProfiles, this.localProfileManager]; + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...hubProfiles, ...allLocalProfiles]; } else { // Organization profiles = hubProfiles; @@ -199,6 +220,16 @@ export class ConfigHandler { 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; @@ -278,7 +309,7 @@ export class ConfigHandler { } else { try { const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = [this.localProfileManager]; + const profiles = await this.getAllLocalProfiles(); workspaces.forEach((workspace) => { const profileLoader = new ControlPlaneProfileLoader( workspace.id, @@ -296,7 +327,7 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } catch (e: any) { console.error("Failed to load profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } } } @@ -311,7 +342,8 @@ export class ConfigHandler { async getSelectedOrgId(): Promise { const selectedOrgs = this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - return selectedOrgs[await this.getWorkspaceId()] ?? null; + const workspaceId = await this.getWorkspaceId(); + return selectedOrgs[workspaceId] ?? null; } async setSelectedOrgId(orgId: string | null) { @@ -319,6 +351,7 @@ export class ConfigHandler { this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; selectedOrgs[await this.getWorkspaceId()] = orgId; this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); + this.didSelectOrganization?.(orgId); } async setSelectedProfile(profileId: string | null) { @@ -353,9 +386,20 @@ export class ConfigHandler { Promise.resolve(sessionInfo), this.ideSettingsPromise, ); + + // After login, default to the first org as the selected org + try { + const orgs = await this.controlPlaneClient.listOrganizations(); + if (orgs.length) { + await this.setSelectedOrgId(orgs[0].id); + } + } catch (e) { + console.error("Failed to fetch control plane profiles: ", e); + } + this.fetchControlPlaneProfiles().catch(async (e) => { console.error("Failed to fetch control plane profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); await this.reloadConfig(); }); } diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index deaf5f40e..9d4bd2842 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -21,6 +21,8 @@ export interface ProfileDescription { id: string; iconUrl: string; errors: ConfigValidationError[] | undefined; + uri: string; + rawYaml?: string; } export interface OrganizationDescription { @@ -77,14 +79,18 @@ export class ProfileLifecycleManager { // Set pending config promise this.pendingConfigPromise = new Promise(async (resolve, reject) => { let result: ConfigResult; + // This try catch is expected to catch high-level errors that aren't block-specific + // Like invalid json, invalid yaml, file read errors, etc. + // NOT block-specific loading errors try { result = await this.profileLoader.doLoadConfig(); - } catch (e: any) { + } catch (e) { + const message = e instanceof Error ? e.message : "Error loading config"; result = { errors: [ { fatal: true, - message: e.message, + message, }, ], config: undefined, @@ -99,7 +105,6 @@ export class ProfileLifecycleManager { ).concat(additionalContextProviders); } - this.savedConfigResult = result; resolve(result); }); diff --git a/core/config/load.ts b/core/config/load.ts index 873577d8c..a198f37bf 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -28,6 +28,7 @@ import { IdeType, ILLM, LLMOptions, + MCPOptions, ModelDescription, RerankerDescription, SerializedContinueConfig, @@ -272,7 +273,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: `${llm.title} - ${modelName}`, + title: modelName, }, ide.readFile.bind(ide), uniqueId, @@ -505,7 +506,11 @@ async function intermediateToFinalConfig( model: "rerank-2", ...params, }; - return new rerankerClass(llmOptions); + return new rerankerClass(llmOptions, (url: string | URL, init: any) => + fetchwithRequestOptions(url, init, { + ...params?.requestOptions, + }), + ); } return null; } @@ -538,37 +543,46 @@ async function intermediateToFinalConfig( // Apply MCP if specified const mcpManager = MCPManagerSingleton.getInstance(); + function getMcpId(options: MCPOptions) { + return JSON.stringify(options); + } if (config.experimental?.modelContextProtocolServers) { - await Promise.all( + await mcpManager.removeUnusedConnections( + config.experimental.modelContextProtocolServers.map(getMcpId), + ); + } + + if (config.experimental?.modelContextProtocolServers) { + const abortController = new AbortController(); + const mcpConnectionTimeout = setTimeout( + () => abortController.abort(), + 5000, + ); + + await Promise.allSettled( config.experimental.modelContextProtocolServers?.map( async (server, index) => { - const mcpId = index.toString(); - const mcpConnection = mcpManager.createConnection(mcpId, server); - if (!mcpConnection) { - return; - } - - const abortController = new AbortController(); - try { - const mcpError = await mcpConnection.modifyConfig( + const mcpId = getMcpId(server); + const mcpConnection = mcpManager.createConnection(mcpId, server); + await mcpConnection.modifyConfig( continueConfig, mcpId, abortController.signal, "MCP Server", server.faviconUrl, ); - if (mcpError) { - errors.push(mcpError); + } catch (e) { + let errorMessage = "Failed to load MCP server"; + if (e instanceof Error) { + errorMessage += ": " + e.message; } - } catch (e: any) { errors.push({ fatal: false, - message: `Failed to load MCP server: ${e.message}`, + message: errorMessage, }); - if (e.name !== "AbortError") { - throw e; - } + } finally { + clearTimeout(mcpConnectionTimeout); } }, ) || [], @@ -664,6 +678,7 @@ async function finalToBrowserConfig( userToken: final.userToken, ui: final.ui, experimental: final.experimental, + rules: final.rules, docs: final.docs, tools: final.tools, tabAutocompleteOptions: final.tabAutocompleteOptions, diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts new file mode 100644 index 000000000..7faa87d5e --- /dev/null +++ b/core/config/loadLocalAssistants.ts @@ -0,0 +1,79 @@ +import ignore from "ignore"; +import { IDE } from ".."; +import { + DEFAULT_IGNORE_DIRS, + DEFAULT_IGNORE_FILETYPES, +} from "../indexing/ignore"; +import { walkDir } from "../indexing/walkDir"; +import { getGlobalAssistantsPath } from "../util/paths"; +import { localPathToUri } from "../util/pathToUri"; +import { joinPathsToUri } from "../util/uri"; + +export const ASSISTANTS_FOLDER = ".continue/assistants"; + +export function isLocalAssistantFile(uri: string): boolean { + if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) { + return false; + } + + const normalizedUri = uri.replace(/\\/g, "/"); + return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); +} + +export async function getAssistantFilesFromDir( + ide: IDE, + dir: string, +): Promise<{ path: string; content: string }[]> { + try { + const exists = await ide.fileExists(dir); + + if (!exists) { + return []; + } + + const overrideDefaultIgnores = ignore() + .add(DEFAULT_IGNORE_FILETYPES.filter((t) => t !== "config.yaml")) + .add(DEFAULT_IGNORE_DIRS); + + const uris = await walkDir(dir, ide, { + overrideDefaultIgnores, + source: "get assistant files", + }); + const assistantFilePaths = uris.filter( + (p) => p.endsWith(".yaml") || p.endsWith(".yml"), + ); + const results = assistantFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; + }); + return Promise.all(results); + } catch (e) { + console.error(e); + return []; + } +} + +export async function getAllAssistantFiles( + ide: IDE, +): Promise<{ path: string; content: string }[]> { + const workspaceDirs = await ide.getWorkspaceDirs(); + let assistantFiles: { path: string; content: string }[] = []; + + let dirsToCheck = [ASSISTANTS_FOLDER]; + const fullDirs = workspaceDirs + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) + .flat(); + + fullDirs.push(localPathToUri(getGlobalAssistantsPath())); + + assistantFiles = ( + await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) + ).flat(); + + return await Promise.all( + assistantFiles.map(async (file) => { + const content = await ide.readFile(file.path); + return { path: file.path, content }; + }), + ); +} diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 6df837cf4..8d12e771f 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -10,6 +10,7 @@ import { } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { PRODUCTION_ENV } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -40,6 +41,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { }, title: workspaceTitle, errors: undefined, + uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`, }; setInterval(async () => { @@ -59,7 +61,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { )) as any); const serializedConfig: SerializedContinueConfig = settings; - const results = await doLoadConfig( + return await doLoadConfig( this.ide, this.ideSettingsPromise, this.controlPlaneClient, @@ -68,12 +70,8 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { undefined, undefined, this.workspaceId, + undefined, ); - - return { - ...results, - errors: [], // Don't do config validation here, it happens in admin panel - }; } setIsActive(isActive: boolean): void {} diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 9ccf5c812..46245a7f0 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,33 +1,58 @@ -import { ConfigResult } from "@continuedev/config-yaml"; +import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getPrimaryConfigFilePath } from "../../util/paths.js"; +import { localPathToUri } from "../../util/pathToUri.js"; +import { getUriPathBasename } from "../../util/uri.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; - description: ProfileDescription = { - id: LocalProfileLoader.ID, - profileType: "local", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - iconUrl: "", - title: "Local Config", - errors: undefined, - }; constructor( private ide: IDE, private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, private writeLog: (message: string) => Promise, - ) {} + private overrideAssistantFile?: + | { path: string; content: string } + | undefined, + ) { + const description: ProfileDescription = { + id: overrideAssistantFile?.path ?? LocalProfileLoader.ID, + profileType: "local", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + iconUrl: "", + title: overrideAssistantFile?.path + ? getUriPathBasename(overrideAssistantFile.path) + : "Local Assistant", + errors: undefined, + uri: + overrideAssistantFile?.path ?? + localPathToUri(getPrimaryConfigFilePath()), + rawYaml: undefined, + }; + this.description = description; + if (overrideAssistantFile?.content) { + try { + const parsedAssistant = parseConfigYaml( + overrideAssistantFile?.content ?? "", + ); + this.description.title = parsedAssistant.name; + } catch (e) { + console.error("Failed to parse assistant file: ", e); + } + } + } + description: ProfileDescription; async doLoadConfig(): Promise> { const result = await doLoadConfig( @@ -39,6 +64,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, this.description.id, + this.overrideAssistantFile?.path, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index c0fa4c5cc..49fd2d0c1 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -5,6 +5,7 @@ import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -21,21 +22,36 @@ export interface PlatformConfigMetadata { export default class PlatformProfileLoader implements IProfileLoader { static RELOAD_INTERVAL = 1000 * 5; // 5 seconds - description: ProfileDescription; - - constructor( + private constructor( private configResult: ConfigResult, private readonly ownerSlug: string, private readonly packageSlug: string, private readonly iconUrl: string, - versionSlug: string, + private readonly versionSlug: string, private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, private writeLog: (message: string) => Promise, private readonly onReload: () => void, - ) { - this.description = { + readonly description: ProfileDescription, + ) {} + + static async create( + configResult: ConfigResult, + ownerSlug: string, + packageSlug: string, + iconUrl: string, + versionSlug: string, + controlPlaneClient: ControlPlaneClient, + ide: IDE, + ideSettingsPromise: Promise, + writeLog: (message: string) => Promise, + onReload: () => void, + rawYaml: string, + ): Promise { + const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); + + const description: ProfileDescription = { id: `${ownerSlug}/${packageSlug}`, profileType: "platform", fullSlug: { @@ -45,12 +61,28 @@ export default class PlatformProfileLoader implements IProfileLoader { }, title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`, errors: configResult.errors, - iconUrl: this.iconUrl, + iconUrl: iconUrl, + uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`, + rawYaml, }; + + return new PlatformProfileLoader( + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + writeLog, + onReload, + description, + ); } async doLoadConfig(): Promise> { - if (this.configResult.errors?.length) { + if (this.configResult.errors?.find((e) => e.fatal)) { return { config: undefined, errors: this.configResult.errors, @@ -70,11 +102,13 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug: this.packageSlug, }, this.description.id, + undefined, ); return { - ...results, - errors: [], // Don't do config validation here, it happens in admin panel + config: results.config, + errors: [...(this.configResult.errors ?? []), ...(results.errors ?? [])], + configLoadInterrupted: results.configLoadInterrupted, }; } diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 0ec9b4137..224b7b64e 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -19,13 +19,14 @@ import { getControlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; +import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; +import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; -import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; export default async function doLoadConfig( ide: IDE, @@ -36,6 +37,7 @@ export default async function doLoadConfig( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, + overrideConfigYamlByPath: string | undefined, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -50,7 +52,9 @@ export default async function doLoadConfig( migrateJsonSharedConfig(configJsonPath, ide); } - const configYamlPath = getConfigYamlPath(ideInfo.ideType); + const configYamlPath = localPathOrUriToPath( + overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType), + ); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; @@ -68,6 +72,7 @@ export default async function doLoadConfig( overrideConfigYaml, platformConfigMetadata, controlPlaneClient, + configYamlPath, ); newConfig = result.config; errors = result.errors; diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts index fdf73606f..072dc79de 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -1,4 +1,4 @@ -import { ModelConfig, AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { SerializedContinueConfig } from "../.."; @@ -6,8 +6,9 @@ export function convertConfigJsonToConfigYaml( configJson: SerializedContinueConfig, ): AssistantUnrolled { return { - name: "Local Config", + name: "Local Assistant", version: "1.0.0", + schema: "v1", models: [ ...configJson.models.map( (model): ModelConfig => ({ diff --git a/core/config/yaml/default.ts b/core/config/yaml/default.ts index c9ca4dc8e..1903e3038 100644 --- a/core/config/yaml/default.ts +++ b/core/config/yaml/default.ts @@ -4,13 +4,15 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; export const defaultConfigYaml: AssistantUnrolled = { models: [], context: [], - name: "Local Config", + name: "Local Assistant", version: "1.0.0", + schema: "v1", }; export const defaultConfigYamlJetBrains: AssistantUnrolled = { models: [], context: [], - name: "Local Config", + name: "Local Assistant", version: "1.0.0", + schema: "v1", }; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index b008092e9..d946b4754 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -4,8 +4,12 @@ import { AssistantUnrolled, ConfigResult, ConfigValidationError, + FQSN, ModelRole, - parseAssistantUnrolled, + PlatformClient, + RegistryClient, + SecretResult, + unrollAssistantFromContent, validateConfigYaml, } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; @@ -16,7 +20,6 @@ import { IDE, IdeInfo, IdeSettings, - SlashCommand, } from "../.."; import { slashFromCustomCommand } from "../../commands"; import { AllRerankers } from "../../context/allRerankers"; @@ -41,6 +44,14 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { llmsFromModelConfig } from "./models"; +export class LocalPlatformClient implements PlatformClient { + async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { + return fqsns.map((fqsn) => { + return undefined; + }); + } +} + async function loadConfigYaml( workspaceConfigs: string[], rawYaml: string, @@ -48,14 +59,25 @@ async function loadConfigYaml( ide: IDE, controlPlaneClient: ControlPlaneClient, ): Promise> { - // const ideSettings = await ide.getIdeSettings(); let config = overrideConfigYaml ?? - // (ideSettings.continueTestEnvironment === "production" - // ? await clientRenderHelper(rawYaml, ide, controlPlaneClient) - // : - parseAssistantUnrolled(rawYaml); - // ); + // This is how we allow use of blocks locally + (await unrollAssistantFromContent( + { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + rawYaml, + new RegistryClient(), + { + currentUserSlug: "", + onPremProxyUrl: null, + orgScopeId: null, + platformClient: new LocalPlatformClient(), + renderSecrets: true, + }, + )); const errors = validateConfigYaml(config); if (errors?.some((error) => error.fatal)) { @@ -69,31 +91,11 @@ async function loadConfigYaml( // Set defaults if undefined (this lets us keep config.json uncluttered for new users) return { config, - errors: errors.map((error) => ({ - message: error.message, - fatal: error.fatal, - })), + errors, configLoadInterrupted: false, }; } -async function slashCommandsFromV1PromptFiles( - ide: IDE, -): Promise { - const slashCommands: SlashCommand[] = []; - - const promptFiles = await getAllPromptFiles(ide, undefined, true); - - for (const file of promptFiles) { - const slashCommand = slashCommandFromPromptFileV1(file.path, file.content); - if (slashCommand) { - slashCommands.push(slashCommand); - } - } - - return slashCommands; -} - async function configYamlToContinueConfig( config: AssistantUnrolled, ide: IDE, @@ -105,12 +107,9 @@ async function configYamlToContinueConfig( platformConfigMetadata: PlatformConfigMetadata | undefined, allowFreeTrial: boolean = true, ): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { - const errors: ConfigValidationError[] = []; + const localErrors: ConfigValidationError[] = []; const continueConfig: ContinueConfig = { - slashCommands: [ - ...(await slashCommandsFromV1PromptFiles(ide)), - ...(config.prompts?.map(slashFromCustomCommand) ?? []), - ], + slashCommands: [], models: [], tools: allTools, systemMessage: config.rules?.join("\n"), @@ -130,6 +129,7 @@ async function configYamlToContinueConfig( rootUrl: doc.rootUrl, faviconUrl: doc.faviconUrl, })), + rules: config.rules, contextProviders: [], modelsByRole: { chat: [], @@ -152,89 +152,137 @@ async function configYamlToContinueConfig( data: config.data, }; + // Prompt files - + try { + const promptFiles = await getAllPromptFiles(ide, undefined, true); + + for (const file of promptFiles) { + try { + const slashCommand = slashCommandFromPromptFileV1( + file.path, + file.content, + ); + if (slashCommand) { + continueConfig.slashCommands?.push(slashCommand); + } + } catch (e) { + localErrors.push({ + fatal: false, + message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`, + }); + } + } + } catch (e) { + localErrors.push({ + fatal: false, + message: `Error loading local prompt files: ${e instanceof Error ? e.message : e}`, + }); + } + + config.prompts?.forEach((prompt) => { + try { + const slashCommand = slashFromCustomCommand(prompt); + continueConfig.slashCommands?.push(slashCommand); + } catch (e) { + localErrors.push({ + message: `Error loading prompt ${prompt.name}: ${e instanceof Error ? e.message : e}`, + fatal: false, + }); + } + }); + // Models const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; for (const model of config.models ?? []) { model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified - const llms = await llmsFromModelConfig( - model, - ide, - uniqueId, - ideSettings, - writeLog, - platformConfigMetadata, - continueConfig.systemMessage, - ); + try { + const llms = await llmsFromModelConfig( + model, + ide, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + continueConfig.systemMessage, + ); - // - if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { - continueConfig.models.push(...llms); - } + // + if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { + continueConfig.models.push(...llms); + } - if (model.roles?.includes("chat")) { - continueConfig.modelsByRole.chat.push(...llms); - } + if (model.roles?.includes("chat")) { + continueConfig.modelsByRole.chat.push(...llms); + } - if (model.roles?.includes("summarize")) { - continueConfig.modelsByRole.summarize.push(...llms); - } + if (model.roles?.includes("summarize")) { + continueConfig.modelsByRole.summarize.push(...llms); + } - if (model.roles?.includes("apply")) { - continueConfig.modelsByRole.apply.push(...llms); - } + if (model.roles?.includes("apply")) { + continueConfig.modelsByRole.apply.push(...llms); + } - if (model.roles?.includes("edit")) { - continueConfig.modelsByRole.edit.push(...llms); - } + if (model.roles?.includes("edit")) { + continueConfig.modelsByRole.edit.push(...llms); + } - if (model.roles?.includes("autocomplete")) { - continueConfig.modelsByRole.autocomplete.push(...llms); - } + if (model.roles?.includes("autocomplete")) { + continueConfig.modelsByRole.autocomplete.push(...llms); + } - if (model.roles?.includes("embed")) { - const { provider, ...options } = model; - const embeddingsProviderClass = allEmbeddingsProviders[provider]; - if (embeddingsProviderClass) { - if ( - embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" - ) { - continueConfig.modelsByRole.embed.push(new embeddingsProviderClass()); + if (model.roles?.includes("embed")) { + const { provider, ...options } = model; + const embeddingsProviderClass = allEmbeddingsProviders[provider]; + if (embeddingsProviderClass) { + if ( + embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" + ) { + continueConfig.modelsByRole.embed.push( + new embeddingsProviderClass(), + ); + } else { + continueConfig.modelsByRole.embed.push( + new embeddingsProviderClass( + options, + (url: string | URL, init: any) => + fetchwithRequestOptions(url, init, { + ...options.requestOptions, + }), + ), + ); + } } else { - continueConfig.modelsByRole.embed.push( - new embeddingsProviderClass( - options, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), + localErrors.push({ + fatal: false, + message: `Unsupported embeddings model provider found: ${provider}`, + }); + } + } + + if (model.roles?.includes("rerank")) { + const { provider, ...options } = model; + const rerankerClass = AllRerankers[provider]; + if (rerankerClass) { + continueConfig.modelsByRole.rerank.push( + new rerankerClass(options, (url: string | URL, init: any) => + fetchwithRequestOptions(url, init, { + ...options.requestOptions, + }), ), ); + } else { + localErrors.push({ + fatal: false, + message: `Unsupported reranking model provider found: ${provider}`, + }); } - } else { - errors.push({ - fatal: false, - message: `Unsupported embeddings model provider found: ${provider}`, - }); - } - } - - if (model.roles?.includes("rerank")) { - const { provider, ...options } = model; - const rerankerClass = AllRerankers[provider]; - if (rerankerClass) { - continueConfig.modelsByRole.rerank.push( - new rerankerClass(options, (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...options.requestOptions, - }), - ), - ); - } else { - errors.push({ - fatal: false, - message: `Unsupported reranking model provider found: ${provider}`, - }); } + } catch (e) { + localErrors.push({ + fatal: false, + message: `Failed to load model:\nName: ${model.name}\nModel: ${model.model}\nProvider: ${model.provider}\n${e instanceof Error ? e.message : e}`, + }); } } @@ -256,9 +304,20 @@ async function configYamlToContinueConfig( (model) => model.providerName === "free-trial", ); if (freeTrialModels.length > 0) { - const ghAuthToken = await ide.getGitHubAuthToken({}); - for (const model of freeTrialModels) { - (model as FreeTrial).setupGhAuthToken(ghAuthToken); + try { + const ghAuthToken = await ide.getGitHubAuthToken({}); + for (const model of freeTrialModels) { + (model as FreeTrial).setupGhAuthToken(ghAuthToken); + } + } catch (e) { + localErrors.push({ + fatal: false, + message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`, + }); + // Remove free trial models + continueConfig.models = continueConfig.models.filter( + (model) => model.providerName !== "free-trial", + ); } } } else { @@ -287,7 +346,10 @@ async function configYamlToContinueConfig( const cls = contextProviderClassFromName(context.provider) as any; if (!cls) { if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) { - console.warn(`Unknown context provider ${context.provider}`); + localErrors.push({ + fatal: false, + message: `Unknown context provider ${context.provider}`, + }); } return undefined; } @@ -308,20 +370,14 @@ async function configYamlToContinueConfig( // Apply MCP if specified const mcpManager = MCPManagerSingleton.getInstance(); - await Promise.all( - config.mcpServers?.map(async (server) => { - const mcpId = server.name; - const mcpConnection = mcpManager.createConnection(mcpId, { - transport: { - type: "stdio", - args: [], - ...server, - }, - }); - if (!mcpConnection) { - return; - } + if (config.mcpServers) { + await mcpManager.removeUnusedConnections( + config.mcpServers.map((s) => s.name), + ); + } + await Promise.allSettled( + config.mcpServers?.map(async (server) => { const abortController = new AbortController(); const mcpConnectionTimeout = setTimeout( () => abortController.abort(), @@ -329,30 +385,38 @@ async function configYamlToContinueConfig( ); try { - const mcpError = await mcpConnection.modifyConfig( + const mcpId = server.name; + const mcpConnection = mcpManager.createConnection(mcpId, { + transport: { + type: "stdio", + args: [], + ...server, + }, + }); + + await mcpConnection.modifyConfig( continueConfig, mcpId, abortController.signal, server.name, server.faviconUrl, ); - if (mcpError) { - errors.push(mcpError); + } catch (e) { + let errorMessage = `Failed to load MCP server ${server.name}`; + if (e instanceof Error) { + errorMessage += ": " + e.message; } - } catch (e: any) { - errors.push({ + localErrors.push({ fatal: false, - message: `Failed to load MCP server: ${e.message}`, + message: errorMessage, }); - if (e.name !== "AbortError") { - throw e; - } + } finally { + clearTimeout(mcpConnectionTimeout); } - clearTimeout(mcpConnectionTimeout); }) ?? [], ); - return { config: continueConfig, errors }; + return { config: continueConfig, errors: localErrors }; } export async function loadContinueConfigFromYaml( @@ -366,10 +430,14 @@ export async function loadContinueConfigFromYaml( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, controlPlaneClient: ControlPlaneClient, + configYamlPath: string | undefined, ): Promise> { const rawYaml = overrideConfigYaml === undefined - ? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8") + ? fs.readFileSync( + configYamlPath ?? getConfigYamlPath(ideInfo.ideType), + "utf-8", + ) : ""; const configYamlResult = await loadConfigYaml( @@ -388,28 +456,37 @@ export async function loadContinueConfigFromYaml( }; } - const { config: continueConfig, errors } = await configYamlToContinueConfig( - configYamlResult.config, - ide, - ideSettings, - ideInfo, - uniqueId, - writeLog, - workOsAccessToken, - platformConfigMetadata, - ); + const { config: continueConfig, errors: localErrors } = + await configYamlToContinueConfig( + configYamlResult.config, + ide, + ideSettings, + ideInfo, + uniqueId, + writeLog, + workOsAccessToken, + platformConfigMetadata, + ); - const systemPromptDotFile = await getSystemPromptDotFile(ide); - if (systemPromptDotFile) { - if (continueConfig.systemMessage) { - continueConfig.systemMessage += "\n\n" + systemPromptDotFile; - } else { - continueConfig.systemMessage = systemPromptDotFile; + try { + const systemPromptDotFile = await getSystemPromptDotFile(ide); + if (systemPromptDotFile) { + if (continueConfig.systemMessage) { + continueConfig.systemMessage += "\n\n" + systemPromptDotFile; + } else { + continueConfig.systemMessage = systemPromptDotFile; + } } + } catch (e) { + localErrors.push({ + fatal: false, + message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`, + }); } // Apply shared config // TODO: override several of these values with user/org shared config + // Don't try catch this - has security implications and failure should be fatal const sharedConfig = new GlobalContext().getSharedConfig(); const withShared = modifyAnyConfigWithSharedConfig( continueConfig, @@ -421,7 +498,7 @@ export async function loadContinueConfigFromYaml( return { config: withShared, - errors: [...(configYamlResult.errors ?? []), ...errors], + errors: [...(configYamlResult.errors ?? []), ...localErrors], configLoadInterrupted: false, }; } diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index c6916b010..57caf324a 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -35,8 +35,11 @@ async function modelConfigToBaseLLM( return undefined; } + const { capabilities, ...rest } = model; + let options: LLMOptions = { - ...model, + ...rest, + // contextLength: model.defaultCompletionOptions?.contextLength ?? undefined, completionOptions: { ...(model.defaultCompletionOptions ?? {}), model: model.model, @@ -49,8 +52,28 @@ async function modelConfigToBaseLLM( title: model.name, systemMessage, promptTemplates: model.promptTemplates, + capabilities: { + tools: model.capabilities?.includes("tool_use"), + uploadImage: model.capabilities?.includes("image_input"), + }, }; + // Model capabilities - need to be undefined if not found + // To fallback to our autodetection + if (capabilities?.find((c) => c === "tool_use")) { + options.capabilities = { + ...options.capabilities, + tools: true, + }; + } + + if (capabilities?.find((c) => c === "image_input")) { + options.capabilities = { + ...options.capabilities, + uploadImage: true, + }; + } + if (model.embedOptions?.maxBatchSize) { options.maxEmbeddingBatchSize = model.embedOptions.maxBatchSize; } @@ -127,7 +150,7 @@ async function autodetectModels( { ...model, model: modelName, - name: `${llm.title} - ${modelName}`, + name: modelName, }, uniqueId, ideSettings, diff --git a/core/context/allRerankers.ts b/core/context/allRerankers.ts index 56aa13474..944a77dbc 100644 --- a/core/context/allRerankers.ts +++ b/core/context/allRerankers.ts @@ -5,12 +5,14 @@ import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI"; import { LLMReranker } from "../llm/llms/llm"; import ContinueProxy from "../llm/llms/stubs/ContinueProxy"; import Voyage from "../llm/llms/Voyage"; +import WatsonX from "../llm/llms/WatsonX"; export const AllRerankers: { [key: string]: any } = { cohere: Cohere, bedrock: Bedrock, llm: LLMReranker, voyage: Voyage, + watsonx: WatsonX, "free-trial": FreeTrial, "huggingface-tei": HuggingFaceTEI, "continue-proxy": ContinueProxy, diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 19de5434a..ec6d3903a 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -4,7 +4,6 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { ConfigValidationError } from "@continuedev/config-yaml"; import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../.."; import { constructMcpSlashCommand } from "../../commands/slash/mcp"; import { encodeMCPToolUri } from "../../tools/callTool"; @@ -24,13 +23,13 @@ export class MCPManagerSingleton { return MCPManagerSingleton.instance; } - createConnection(id: string, options: MCPOptions): MCPConnection | undefined { + createConnection(id: string, options: MCPOptions): MCPConnection { if (!this.connections.has(id)) { const connection = new MCPConnection(options); this.connections.set(id, connection); return connection; } else { - return this.connections.get(id); + return this.connections.get(id)!; } } @@ -46,6 +45,13 @@ export class MCPManagerSingleton { this.connections.delete(id); } + + async removeUnusedConnections(keepIds: string[]) { + const toRemove = Array.from(this.connections.keys()).filter( + (k) => !keepIds.includes(k), + ); + await Promise.all(toRemove.map((id) => this.removeConnection(id))); + } } class MCPConnection { @@ -123,25 +129,32 @@ class MCPConnection { signal: AbortSignal, name: string, faviconUrl: string | undefined, - ): Promise { + ) { try { await Promise.race([ this.connectClient(), new Promise((_, reject) => { signal.addEventListener("abort", () => - reject(new Error("Connection aborted")), + reject(new Error("Connection timed out")), ); }), ]); - } catch (error: any) { - if (signal.aborted) { - throw new Error("Operation aborted"); - } - if (!error.message.startsWith("StdioClientTransport already started")) { - return { - fatal: false, - message: `Failed to connect to MCP: ${error.message}`, - }; + } catch (error) { + if (error instanceof Error) { + const msg = error.message.toLowerCase(); + if (msg.includes("spawn") && msg.includes("enoent")) { + const command = msg.split(" ")[1]; + throw new Error( + `command "${command}" not found. To use this MCP server, install the ${command} CLI.`, + ); + } else if ( + !error.message.startsWith("StdioClientTransport already started") + ) { + // don't throw error if it's just a "server already running" case + throw error; + } + } else { + throw error; } } diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index f4b816f33..3b9fa0cf4 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -5,6 +5,7 @@ import { ContextProviderDescription, ContextProviderExtras, ContextSubmenuItem, + IDE, LoadSubmenuItemsArgs, } from "../.."; import DocsService from "../../indexing/docs/DocsService"; @@ -36,6 +37,7 @@ class DocsContextProvider extends BaseContextProvider { chunks: Chunk[], reranker: NonNullable, fullInput: ContextProviderExtras["fullInput"], + ide: IDE, ) { let chunksCopy = [...chunks]; @@ -51,7 +53,7 @@ class DocsContextProvider extends BaseContextProvider { this.options?.nFinal ?? DocsContextProvider.nFinal, ); } catch (e) { - console.warn(`Failed to rerank docs results: ${e}`); + void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`); chunksCopy = chunksCopy.splice( 0, @@ -116,6 +118,7 @@ class DocsContextProvider extends BaseContextProvider { chunks, extras.reranker, extras.fullInput, + extras.ide, ); } diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts index 4953f5bdc..5f7861b83 100644 --- a/core/context/providers/FileContextProvider.ts +++ b/core/context/providers/FileContextProvider.ts @@ -8,9 +8,9 @@ import { } from "../../"; import { walkDirs } from "../../indexing/walkDir"; import { - getUriPathBasename, getShortestUniqueRelativeUriPaths, getUriDescription, + getUriPathBasename, } from "../../util/uri"; const MAX_SUBMENU_ITEMS = 10_000; @@ -53,7 +53,13 @@ class FileContextProvider extends BaseContextProvider { args: LoadSubmenuItemsArgs, ): Promise { const workspaceDirs = await args.ide.getWorkspaceDirs(); - const results = await walkDirs(args.ide, undefined, workspaceDirs); + const results = await walkDirs( + args.ide, + { + source: "load submenu items - file", + }, + workspaceDirs, + ); const files = results.flat().slice(-MAX_SUBMENU_ITEMS); const withUniquePaths = getShortestUniqueRelativeUriPaths( files, diff --git a/core/context/providers/FileTreeContextProvider.ts b/core/context/providers/FileTreeContextProvider.ts index 3b98dd6cb..29721cb5c 100644 --- a/core/context/providers/FileTreeContextProvider.ts +++ b/core/context/providers/FileTreeContextProvider.ts @@ -50,7 +50,9 @@ class FileTreeContextProvider extends BaseContextProvider { directories: [], }; - const uris = await walkDir(workspaceDir, extras.ide); + const uris = await walkDir(workspaceDir, extras.ide, { + source: "get context items - file tree", + }); const relativePaths = uris.map( (uri) => findUriInDirs(uri, [workspaceDir]).relativePathOrBasename, ); diff --git a/core/context/providers/FolderContextProvider.ts b/core/context/providers/FolderContextProvider.ts index dc5257568..42df6ab34 100644 --- a/core/context/providers/FolderContextProvider.ts +++ b/core/context/providers/FolderContextProvider.ts @@ -36,6 +36,7 @@ class FolderContextProvider extends BaseContextProvider { args.ide, { onlyDirs: true, + source: "load submenu items - folder", }, workspaceDirs, ); diff --git a/core/context/providers/GitLabMergeRequestContextProvider.ts b/core/context/providers/GitLabMergeRequestContextProvider.ts index 3e8f77a67..b4d3fe2ed 100644 --- a/core/context/providers/GitLabMergeRequestContextProvider.ts +++ b/core/context/providers/GitLabMergeRequestContextProvider.ts @@ -94,7 +94,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { }); } - private async getRemoteBranchName( + private async getRemoteBranchInfo( extras: ContextProviderExtras, ): Promise { const subprocess = await getSubprocess(extras); @@ -121,9 +121,16 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`); - const urlMatches = /:(?.*).git/.exec(remoteUrl); + let urlMatches: RegExpExecArray | null; + if (/https?.*/.test(remoteUrl)) { + const pathname = new URL(remoteUrl).pathname; + urlMatches = /\/(?.*?)(?:(?=\.git)|$)/.exec(pathname) + } else { + // ssh + urlMatches = /:(?.*).git/.exec(remoteUrl) + } - const project = urlMatches?.groups?.project ?? null; + const project = urlMatches?.groups?.projectPath ?? null; return { branch: remoteBranch, @@ -135,7 +142,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const { branch, project } = await this.getRemoteBranchName(extras); + const { branch, project } = await this.getRemoteBranchInfo(extras); const api = await this.getApi(); diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index 7b7228eee..067035806 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -36,6 +36,7 @@ class HttpContextProvider extends BaseContextProvider { method: "POST", headers: { "Content-Type": "application/json", + ...(this.options.headers || {}), }, body: JSON.stringify({ query: query || "", diff --git a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts index 9a83d279d..966fa47f5 100644 --- a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts +++ b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts @@ -9,6 +9,7 @@ interface JiraClientOptions { password: string; issueQuery?: string; apiVersion?: string; + maxResults?: string; requestOptions?: RequestOptions; } @@ -73,6 +74,7 @@ export class JiraClient { "assignee = currentUser() AND resolution = Unresolved order by updated DESC", apiVersion: "3", requestOptions: {}, + maxResults: "50", ...options, }; this.baseUrl = `https://${this.options.domain}/rest/api/${this.options.apiVersion}`; @@ -146,7 +148,7 @@ export class JiraClient { `/search?fields=summary&jql=${ this.options.issueQuery ?? "assignee = currentUser() AND resolution = Unresolved order by updated DESC" - }`, + }&maxResults=${this.options.maxResults ?? "50"}`, ), { method: "GET", diff --git a/core/context/providers/JiraIssuesContextProvider/index.ts b/core/context/providers/JiraIssuesContextProvider/index.ts index d13022140..35a14aba4 100644 --- a/core/context/providers/JiraIssuesContextProvider/index.ts +++ b/core/context/providers/JiraIssuesContextProvider/index.ts @@ -25,6 +25,7 @@ class JiraIssuesContextProvider extends BaseContextProvider { issueQuery: this.options.issueQuery, apiVersion: this.options.apiVersion, requestOptions: this.options.requestOptions, + maxResults: this.options.maxResults }); } @@ -32,8 +33,6 @@ class JiraIssuesContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const issueId = query; - const api = this.getApi(); const issue = await api.issue(query, extras.fetch); diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index deabfe590..6a2db46fa 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -55,6 +55,7 @@ class RepoMapContextProvider extends BaseContextProvider { args.ide, { onlyDirs: true, + source: "load submenu items - repo map", }, workspaceDirs, ); diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index d91931327..a3dcc0f7e 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -80,24 +80,19 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { args: RetrievalPipelineRunArguments, n: number, ): Promise { - try { - if (args.query.trim() === "") { - return []; - } - - const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); - const tokens = this.escapeFtsQueryString(tokensRaw); - - return await this.ftsIndex.retrieve({ - n, - text: tokens, - tags: args.tags, - directory: args.filterDirectory, - }); - } catch (e) { - console.warn("Error retrieving from FTS:", e); + if (args.query.trim() === "") { return []; } + + const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); + const tokens = this.escapeFtsQueryString(tokensRaw); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); } protected async retrieveAndChunkRecentlyEditedFiles( diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index 889005414..f35809fed 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -19,22 +19,42 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, ftsNFinal); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, ftsNFinal); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, embeddingsNFinal) - : []; + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, embeddingsNFinal) + : []; + } catch (error) { + console.error("Error retrieving embeddings:", error); + } - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + } catch (error) { + console.error("Error retrieving recently edited files:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 5fc4f240b..e73edf118 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -16,20 +16,42 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, nRetrieve); - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, nRetrieve) - : []; - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, nRetrieve); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, nRetrieve) + : []; + } catch (error) { + console.error("Error retrieving embeddings chunks:", error); + } + + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + } catch (error) { + console.error("Error retrieving recently edited files chunks:", error); + } + + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, @@ -41,7 +63,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { if (filterDirectory) { // Backup if the individual retrieval methods don't listen retrievalResults = retrievalResults.filter( - (chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, + (chunk) => + !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, ); } @@ -59,29 +82,37 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { // remove empty chunks -- some APIs fail on that chunks = chunks.filter((chunk) => chunk.content); - let scores: number[] = - await this.options.config.selectedModelByRole.rerank.rerank( - input, - chunks, + try { + let scores: number[] = + await this.options.config.selectedModelByRole.rerank.rerank( + input, + chunks, + ); + + // Filter out low-scoring results + let results = chunks; + // let results = chunks.filter( + // (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, + // ); + // scores = scores.filter( + // (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, + // ); + + const chunkIndexMap = new Map(); + chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); + + results.sort( + (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], ); - - // Filter out low-scoring results - let results = chunks; - // let results = chunks.filter( - // (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, - // ); - // scores = scores.filter( - // (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, - // ); - - const chunkIndexMap = new Map(); - chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); - - results.sort( - (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], - ); - results = results.slice(-this.options.nFinal); - return results; + results = results.slice(-this.options.nFinal); + return results; + } catch (e) { + void this.options.ide.showToast( + "warning", + `Failed to rerank retrieval results\n${e}`, + ); + return chunks.slice(-this.options.nFinal); + } } private async _expandWithEmbeddings(chunks: Chunk[]): Promise { diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 5637019ad..094c25b27 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,6 +1,7 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; import generateRepoMap from "../../util/generateRepoMap"; +import { resolveRelativePathInDir } from "../../util/ideUtils"; import { renderChatMessage } from "../../util/messageContent"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ @@ -48,14 +49,14 @@ export async function requestFilesFromRepoMap( const repoMap = await generateRepoMap(llm, ide, { dirUris: filterDirUri ? [filterDirUri] : undefined, includeSignatures: false, - outputRelativeUriPaths: false, + outputRelativeUriPaths: true, }); const prompt = `${repoMap} Given the above repo map, your task is to decide which files are most likely to be relevant in answering a question. Before giving your answer, you should write your reasoning about which files/folders are most important. This thinking should start with a tag, followed by a paragraph explaining your reasoning, and then a closing tag on the last line. -After this, your response should begin with a tag, followed by a list of each file, one per line, and then a closing tag on the last line. You should select between 5 and 10 files. The names that you list should be the full path from the root of the repo, not just the basename of the file. +After this, your response should begin with a tag, followed by a list of each file, one per line, and then a closing tag on the last line. You should select between 5 and 10 files. The names that you list should be the exact relative path that you saw in the repo map, not just the basename of the file. This is the question that you should select relevant files for: "${input}"`; @@ -72,15 +73,19 @@ This is the question that you should select relevant files for: "${input}"`; return []; } - const fileUris = content + const filepaths = content .split("")[1] ?.split("")[0] ?.split("\n") .filter(Boolean) - .map((uri) => uri.trim()); + .map((filepath) => filepath.trim()); const chunks = await Promise.all( - fileUris.map(async (uri) => { + filepaths.map(async (filepath) => { + const uri = await resolveRelativePathInDir(filepath, ide); + if (!uri) { + return undefined; + } const content = await ide.readFile(uri); const lineCount = content.split("\n").length; const chunk: Chunk = { @@ -95,7 +100,7 @@ This is the question that you should select relevant files for: "${input}"`; }), ); - return chunks; + return chunks.filter((c) => c !== undefined) as Chunk[]; } catch (e) { console.debug("Error requesting files from repo map", e); return []; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 9dcf40b6d..dee4d7ef4 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -113,6 +113,7 @@ export class ControlPlaneClient { ownerSlug: string; packageSlug: string; iconUrl: string; + rawYaml: string; }[] > { const userId = await this.userId; diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 288901cab..7d3ae9eb0 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -1,6 +1,9 @@ import * as fs from "node:fs"; import { IdeSettings } from ".."; -import { getStagingEnvironmentDotFilePath } from "../util/paths"; +import { + getLocalEnvironmentDotFilePath, + getStagingEnvironmentDotFilePath, +} from "../util/paths"; export interface ControlPlaneEnv { DEFAULT_CONTROL_PLANE_PROXY_URL: string; @@ -18,7 +21,7 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; const WORKOS_ENV_ID_PRODUCTION = "continue"; const WORKOS_ENV_ID_STAGING = "continue-staging"; -const PRODUCTION_ENV: ControlPlaneEnv = { +export const PRODUCTION_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", CONTROL_PLANE_URL: @@ -78,6 +81,11 @@ export function getControlPlaneEnvSync( ideTestEnvironment: IdeSettings["continueTestEnvironment"], enableControlServerBeta: IdeSettings["enableControlServerBeta"], ): ControlPlaneEnv { + // Note .local overrides .staging + if (fs.existsSync(getLocalEnvironmentDotFilePath())) { + return LOCAL_ENV; + } + if (fs.existsSync(getStagingEnvironmentDotFilePath())) { return STAGING_ENV; } diff --git a/core/control-plane/schema.ts b/core/control-plane/schema.ts index 9fcdd2219..d29316d5e 100644 --- a/core/control-plane/schema.ts +++ b/core/control-plane/schema.ts @@ -19,6 +19,7 @@ const modelDescriptionSchema = z.object({ "nebius", "siliconflow", "scaleway", + "watsonx" ]), model: z.string(), apiKey: z.string().optional(), @@ -88,6 +89,7 @@ const embeddingsProviderSchema = z.object({ "nebius", "siliconflow", "scaleway", + "watsonx" ]), apiBase: z.string().optional(), apiKey: z.string().optional(), @@ -109,7 +111,7 @@ const embeddingsProviderSchema = z.object({ }); const rerankerSchema = z.object({ - name: z.enum(["cohere", "voyage", "llm"]), + name: z.enum(["cohere", "voyage", "llm", "watsonx"]), params: z.record(z.any()).optional(), }); diff --git a/core/core.ts b/core/core.ts index 180ce8642..629aa84ca 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,7 +1,4 @@ -import path from "path"; - import { fetchwithRequestOptions } from "@continuedev/fetch"; -import ignore from "ignore"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; @@ -26,7 +23,6 @@ import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; -import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -34,25 +30,22 @@ import { ChatDescriber } from "./util/chatDescriber"; import { clipboardCache } from "./util/clipboardCache"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; -import { - editConfigJson, - getConfigJsonPath, - migrateV1DevDataFiles, -} from "./util/paths"; -import { localPathToUri } from "./util/pathToUri"; +import { editConfigJson, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import { - ChatMessage, DiffLine, - PromptLog, type ContextItemId, type IDE, type IndexingProgressUpdate, } from "."; +import { isLocalAssistantFile } from "./config/loadLocalAssistants"; +import { shouldIgnore } from "./indexing/shouldIgnore"; +import { walkDirCache } from "./indexing/walkDir"; +import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -114,6 +107,11 @@ export class Core { ideSettingsPromise, this.onWrite, sessionInfoPromise, + (orgId: string | null) => { + void messenger.request("didSelectOrganization", { + orgId, + }); + }, ); this.docsService = DocsService.createSingleton( @@ -302,8 +300,11 @@ export class Core { this.configHandler.updateIdeSettings(msg.data); }); - on("config/listProfiles", (msg) => { - return this.configHandler.listProfiles(); + 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) => { @@ -484,111 +485,14 @@ export class Core { } }); - async function* llmStreamChat( - configHandler: ConfigHandler, - abortedMessageIds: Set, - msg: Message, - ): AsyncGenerator { - const { config } = await configHandler.loadConfig(); - if (!config) { - throw new Error("Config not loaded"); - } - - // Stop TTS on new StreamChat - if (config.experimental?.readResponseTTS) { - void TTS.kill(); - } - - const model = await configHandler.llmFromTitle(msg.data.title); - - const gen = model.streamChat( - msg.data.messages, - new AbortController().signal, - msg.data.completionOptions, - ); - let next = await gen.next(); - while (!next.done) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - next = await gen.return({ - modelTitle: model.title ?? model.model, - completion: "", - prompt: "", - completionOptions: { - ...msg.data.completionOptions, - model: model.model, - }, - }); - break; - } - - const chunk = next.value; - - yield chunk; - next = await gen.next(); - } - - if (config.experimental?.readResponseTTS && "completion" in next.value) { - void TTS.read(next.value?.completion); - } - - void Telemetry.capture( - "chat", - { - model: model.model, - provider: model.providerName, - }, - true, - ); - - if (!next.done) { - throw new Error("Will never happen"); - } - - return next.value; - } - on("llm/streamChat", (msg) => - llmStreamChat(this.configHandler, this.abortedMessageIds, msg), - ); - - async function* llmStreamComplete( - configHandler: ConfigHandler, - abortedMessageIds: Set, - msg: Message, - ): AsyncGenerator { - const model = await configHandler.llmFromTitle(msg.data.title); - const gen = model.streamComplete( - msg.data.prompt, - new AbortController().signal, - msg.data.completionOptions, - ); - let next = await gen.next(); - while (!next.done) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - next = await gen.return({ - modelTitle: model.title ?? model.model, - completion: "", - prompt: "", - completionOptions: { - ...msg.data.completionOptions, - model: model.model, - }, - }); - break; - } - yield next.value; - next = await gen.next(); - } - if (!next.done) { - throw new Error("This will never happen"); - } - return next.value; - } - - on("llm/streamComplete", (msg) => - llmStreamComplete(this.configHandler, this.abortedMessageIds, msg), + llmStreamChat( + this.configHandler, + this.abortedMessageIds, + msg, + ide, + this.messenger, + ), ); on("llm/complete", async (msg) => { @@ -641,96 +545,6 @@ export class Core { return await ChatDescriber.describe(currentModel, {}, msg.data.text); }); - async function* runNodeJsSlashCommand( - configHandler: ConfigHandler, - abortedMessageIds: Set, - msg: Message, - messenger: IMessenger, - ): AsyncGenerator { - const { - input, - history, - modelTitle, - slashCommandName, - contextItems, - params, - historyIndex, - selectedCode, - completionOptions, - } = msg.data; - - const { config } = await configHandler.loadConfig(); - if (!config) { - throw new Error("Config not loaded"); - } - - const llm = await configHandler.llmFromTitle(modelTitle); - const slashCommand = config.slashCommands?.find( - (sc) => sc.name === slashCommandName, - ); - if (!slashCommand) { - throw new Error(`Unknown slash command ${slashCommandName}`); - } - - void Telemetry.capture( - "useSlashCommand", - { - name: slashCommandName, - }, - true, - ); - - const checkActiveInterval = setInterval(() => { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - clearInterval(checkActiveInterval); - } - }, 100); - - try { - for await (const content of slashCommand.run({ - input, - history, - llm, - contextItems, - params, - ide, - addContextItem: (item) => { - void messenger.request("addContextItem", { - item, - historyIndex, - }); - }, - selectedCode, - config, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - completionOptions, - })) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - clearInterval(checkActiveInterval); - break; - } - if (content) { - yield content; - } - } - } catch (e) { - throw e; - } finally { - clearInterval(checkActiveInterval); - } - } - on("command/run", (msg) => - runNodeJsSlashCommand( - this.configHandler, - this.abortedMessageIds, - msg, - this.messenger, - ), - ); - // Autocomplete on("autocomplete/complete", async (msg) => { const outcome = @@ -829,6 +643,11 @@ export class Core { // Codebase indexing on("index/forceReIndex", async ({ data }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config || config.disableIndexing) { + return; // TODO silent in case of commands? + } + walkDirCache.invalidate(); if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; await codebaseIndexer.clearIndexes(); @@ -856,10 +675,12 @@ export class Core { // TODO - remove remaining logic for these from IDEs where possible on("files/changed", async ({ data }) => { if (data?.uris?.length) { + walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes for (const uri of data.uris) { - // Listen for file changes in the workspace - // URI TODO is this equality statement valid? - if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) { + const currentProfileUri = + this.configHandler.currentProfile?.profileDescription.uri ?? ""; + + if (URI.equal(uri, currentProfileUri)) { // Trigger a toast notification to provide UI feedback that config has been updated const showToast = this.globalContext.get("showConfigUpdateToast") ?? true; @@ -873,6 +694,8 @@ export class Core { this.globalContext.update("showConfigUpdateToast", false); } } + await this.configHandler.reloadConfig(); + continue; } if ( @@ -886,32 +709,71 @@ export class Core { uri.endsWith(".gitignore") ) { // Reindex the workspaces - this.invoke("index/forceReIndex", undefined); + this.invoke("index/forceReIndex", { + shouldClearIndexes: true, + }); } else { - // Reindex the file - await this.refreshCodebaseIndexFiles([uri]); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + // Reindex the file + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } + } } } } }); - on("files/created", async ({ data }) => { - if (data?.uris?.length) { + const refreshIfNotIgnored = async (uris: string[]) => { + const toRefresh: string[] = []; + for (const uri of uris) { + const ignore = await shouldIgnore(uri, ide); + if (!ignore) { + toRefresh.push(uri); + } + } + if (toRefresh.length > 0) { this.messenger.send("refreshSubmenuItems", { providers: ["file"], }); - await this.refreshCodebaseIndexFiles(data.uris); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + await this.refreshCodebaseIndexFiles(toRefresh); + } + } + }; + + on("files/created", async ({ data }) => { + if (data?.uris?.length) { + walkDirCache.invalidate(); + 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 + for (const uri of data.uris) { + if (isLocalAssistantFile(uri)) { + await this.configHandler.loadAssistantsForSelectedOrg(); + } + } } }); on("files/deleted", async ({ data }) => { if (data?.uris?.length) { - this.messenger.send("refreshSubmenuItems", { - providers: ["file"], - }); - await this.refreshCodebaseIndexFiles(data.uris); + walkDirCache.invalidate(); + void refreshIfNotIgnored(data.uris); } }); + + on("files/closed", async ({ data }) => { + if (data.uris) { + this.messenger.send("didCloseFiles", { + uris: data.uris, + }); + } + }); + on("files/opened", async ({ data }) => { if (data?.uris?.length) { // Do something on files opened @@ -950,15 +812,21 @@ export class Core { }); // - on("didChangeSelectedProfile", (msg) => { - void this.configHandler.setSelectedProfile(msg.data.id); - void this.configHandler.reloadConfig(); + on("didChangeSelectedProfile", async (msg) => { + await this.configHandler.setSelectedProfile(msg.data.id); + await this.configHandler.reloadConfig(); }); - on("didChangeSelectedOrg", (msg) => { - void this.configHandler.setSelectedOrgId(msg.data.id); - void this.configHandler.reloadConfig(); - void this.configHandler.loadAssistantsForSelectedOrg(); + 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(); + } }); on("didChangeControlPlaneSessionInfo", async (msg) => { @@ -975,19 +843,15 @@ export class Core { }); on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - const ignoreInstance = ignore().add(defaultIgnoreFile); - let rootDirectory = await this.ide.getWorkspaceDirs(); - const relativeFilePath = path.relative(rootDirectory[0], filepath); try { - if (!ignoreInstance.ignores(relativeFilePath)) { + const ignore = shouldIgnore(filepath, this.ide); + if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); } } catch (e) { - if (e instanceof RangeError) { - // do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json` - } else { - console.debug("unhandled ignores error", relativeFilePath, e); - } + console.error( + `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, + ); } }); diff --git a/core/data/log.ts b/core/data/log.ts index 1b810d851..4470eba72 100644 --- a/core/data/log.ts +++ b/core/data/log.ts @@ -46,7 +46,7 @@ export class DataLogger { if ("eventName" in zodSchema.shape) { newBody.eventName = eventName; } - if ("timestamp" in zodSchema.shape) { + if (!newBody.timestamp && "timestamp" in zodSchema.shape) { newBody.timestamp = new Date().toISOString(); } if ("schema" in zodSchema.shape) { diff --git a/core/diff/myers.test.ts b/core/diff/myers.test.ts index 2b47fa548..4148424a6 100644 --- a/core/diff/myers.test.ts +++ b/core/diff/myers.test.ts @@ -29,4 +29,16 @@ describe("Test myers diff function", () => { { type: "same", line: "E" }, ]); }); + + test("should ignore newline differences at end", () => { + const linesA = "A\nB\nC\n"; + const linesB = "A\nB\nC"; + + const diffLines = myersDiff(linesA, linesB); + expect(diffLines).toEqual([ + { type: "same", line: "A" }, + { type: "same", line: "B" }, + { type: "same", line: "C" }, + ]); + }); }); diff --git a/core/diff/myers.ts b/core/diff/myers.ts index 22a2fc4e3..7dcb1f67c 100644 --- a/core/diff/myers.ts +++ b/core/diff/myers.ts @@ -10,7 +10,7 @@ export function convertMyersChangeToDiffLines(change: Change): DiffLine[] { : "same"; const lines = change.value.split("\n"); - // `diff` package is always adding an extra new line at the end of the array + // Ignore the \n at the end of the final line, if there is one if (lines[lines.length - 1] === "") { lines.pop(); } @@ -18,9 +18,27 @@ export function convertMyersChangeToDiffLines(change: Change): DiffLine[] { return lines.map((line) => ({ type, line })); } +// The interpretation of lines in oldContent and newContent is the same as jsdiff +// Lines are separated by \n, with the exception that a trailing \n does *not* +// represent an empty line. +// +// The default for jsdiff is that "foo" and "foo\n" are *different* single-line +// contents, but we can't represent that: to avoid a diff +// [ { type: "old", line: "foo" }, { type: "new", line: "foo" } ], we +// pass ignoreNewlineAtEof: true. export function myersDiff(oldContent: string, newContent: string): DiffLine[] { - const theirFormat = diffLines(oldContent, newContent); + const theirFormat = diffLines(oldContent, newContent, { + ignoreNewlineAtEof: true, + }); const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines); + while ( + ourFormat.length > 0 && + ourFormat[ourFormat.length - 1].type === "old" && + ourFormat[ourFormat.length - 1].line === "" + ) { + ourFormat.pop(); + } + return ourFormat; } diff --git a/core/diff/streamDiff.test.ts b/core/diff/streamDiff.test.ts index fa7db52ac..560d2e13d 100644 --- a/core/diff/streamDiff.test.ts +++ b/core/diff/streamDiff.test.ts @@ -223,6 +223,109 @@ describe("streamDiff(", () => { await expectDiff("fastapi-tabs-vs-spaces.py"); }); + test("trailing whitespaces should match ", async () => { + const oldLines = ["first item ", "second arg ", "third param "]; + + const newLines = ["first item", "second arg", "third param "]; + + const { streamDiffs } = await collectDiffs(oldLines, newLines); + + expect(streamDiffs).toEqual([ + { type: "same", line: "first item " }, + { type: "same", line: "second arg " }, + { type: "same", line: "third param " }, + ]); + }); + + //indentation and whitespace handling + test.each([false, true])( + "ignores indentation changes for sufficiently long lines (trailingWhitespace: %s)", + async (trailingWhitespace) => { + let oldLines = [ + " short", + " middle", + " a long enough line", + " short2", + "indented line", + "final line", + ]; + + let newLines = [ + "short", + "middle", + "a long enough line", + "short2", + " indented line", + "final line", + ]; + + if (trailingWhitespace) { + oldLines = oldLines.map((line) => line + " "); + } + + const { streamDiffs } = await collectDiffs(oldLines, newLines); + const expected = trailingWhitespace + ? [ + { type: "old", line: " short " }, + { type: "new", line: "short" }, + { type: "old", line: " middle " }, + { type: "new", line: "middle" }, + { type: "same", line: " a long enough line " }, + { type: "same", line: " short2 " }, + { type: "same", line: "indented line " }, + { type: "same", line: "final line " }, + ] + : [ + { type: "old", line: " short" }, + { type: "new", line: "short" }, + { type: "old", line: " middle" }, + { type: "new", line: "middle" }, + { type: "same", line: " a long enough line" }, + { type: "same", line: " short2" }, + { type: "same", line: "indented line" }, + { type: "same", line: "final line" }, + ]; + + expect(streamDiffs).toEqual(expected); + }, + ); + + test("preserves original lines for minor reindentation in simple block", async () => { + const oldLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"]; + const newLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"]; + + const { streamDiffs } = await collectDiffs(oldLines, newLines); + + expect(streamDiffs).toEqual([ + { type: "same", line: "if (checkValueOf(x)) {" }, + { type: "same", line: " doSomethingWith(x);" }, + { type: "same", line: "}" }, + ]); + }); + + test("uses new lines for nested reindentation changes", async () => { + const oldLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"]; + const newLines = [ + "if (checkValueOf(x)) {", + " if (reallyCheckValueOf(x)) {", + " doSomethingElseWith(x);", + " }", + "}", + ]; + + const { streamDiffs } = await collectDiffs(oldLines, newLines); + + expect(streamDiffs).toEqual([ + { type: "same", line: "if (checkValueOf(x)) {" }, + { type: "new", line: " if (reallyCheckValueOf(x)) {" }, + { type: "old", line: " doSomethingWith(x);" }, + { type: "new", line: " doSomethingElseWith(x);" }, + { type: "old", line: "}" }, + { type: "new", line: " }" }, + { type: "new", line: "}" }, + ]); + }); + test("FastAPI example", async () => { await expectDiff("fastapi.py"); }); diff --git a/core/diff/streamDiff.ts b/core/diff/streamDiff.ts index 4daa30804..436da1c09 100644 --- a/core/diff/streamDiff.ts +++ b/core/diff/streamDiff.ts @@ -35,7 +35,6 @@ export async function* streamDiff( let type: DiffLineType; - let isLineRemoval = false; const isNewLine = matchIndex === -1; if (isNewLine) { @@ -45,7 +44,6 @@ export async function* streamDiff( for (let i = 0; i < matchIndex; i++) { yield { type: "old", line: oldLinesCopy.shift()! }; } - type = isPerfectMatch ? "same" : "old"; } @@ -60,22 +58,13 @@ export async function* streamDiff( case "old": yield { type, line: oldLinesCopy.shift()! }; - - if (oldLinesCopy[0] !== newLine) { - yield { type: "new", line: newLine }; - } else { - isLineRemoval = true; - } - + yield { type: "new", line: newLine }; break; default: console.error(`Error streaming diff, unrecognized diff type: ${type}`); } - - if (!isLineRemoval) { - newLineResult = await newLines.next(); - } + newLineResult = await newLines.next(); } // Once at the edge, only one choice diff --git a/core/diff/util.ts b/core/diff/util.ts index c56e88504..571ede7b9 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -62,18 +62,23 @@ export function matchLine( const isEndBracket = END_BRACKETS.includes(newLine.trim()); for (let i = 0; i < oldLines.length; i++) { + // trims trailing whitespaces from the lines before comparison + //this ensures trailing spaces don't affect matching. + const oldLineTrimmed = oldLines[i].trimEnd(); + const newLineTrimmed = newLine.trimEnd(); + // Don't match end bracket lines if too far away if (i > 4 && isEndBracket) { return { matchIndex: -1, isPerfectMatch: false, newLine }; } - if (linesMatchPerfectly(newLine, oldLines[i])) { + if (linesMatchPerfectly(newLineTrimmed, oldLineTrimmed)) { return { matchIndex: i, isPerfectMatch: true, newLine }; } - if (linesMatch(newLine, oldLines[i], i)) { + if (linesMatch(newLineTrimmed, oldLineTrimmed, i)) { // This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines if ( - newLine.trimStart() === oldLines[i].trimStart() && + newLineTrimmed.trimStart() === oldLineTrimmed.trimStart() && (permissiveAboutIndentation || newLine.trim().length > 8) ) { return { diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index 424d4e831..f30751d70 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -5,6 +5,7 @@ import { getUriFileExtension } from "../../util/uri"; import { deterministicApplyLazyEdit } from "./deterministic"; import { streamLazyApply } from "./streamLazyApply"; +import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply"; function canUseInstantApply(filename: string) { const fileExtension = getUriFileExtension(filename); @@ -33,5 +34,16 @@ export async function applyCodeBlock( } } + // If the code block is a diff + if (isUnifiedDiffFormat(newFile)) { + try { + const diffLines = applyUnifiedDiff(oldFile, newFile); + const diffGenerator = generateLines(diffLines!); + return [true, diffGenerator]; + } catch (e) { + console.error("Failed to apply unified diff", e); + } + } + return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)]; } diff --git a/core/edit/lazy/unifiedDiffApply.test.ts b/core/edit/lazy/unifiedDiffApply.test.ts new file mode 100644 index 000000000..f0eae9b64 --- /dev/null +++ b/core/edit/lazy/unifiedDiffApply.test.ts @@ -0,0 +1,415 @@ +import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply"; + +describe("isUnifiedDiffFormat", () => { + it("should return true for valid unified diff format", () => { + const validDiff = `--- original.txt ++++ modified.txt +@@ -1,3 +1,4 @@ + line1 +-line2 ++newline2 ++newline3 + line3`; + expect(isUnifiedDiffFormat(validDiff)).toBe(true); + }); + + it("should return false for empty diff", () => { + expect(isUnifiedDiffFormat("")).toBe(false); + }); + + it("should return false for diff without hunk header", () => { + const invalidDiff = `--- original.txt ++++ modified.txt ++line1 +-line2 ++line3`; + expect(isUnifiedDiffFormat(invalidDiff)).toBe(false); + }); + + it("should return false for diff without valid content", () => { + const invalidDiff = `--- original.txt ++++ modified.txt +@@ -1,3 +1,4 @@`; + expect(isUnifiedDiffFormat(invalidDiff)).toBe(false); + }); + + it("should return true even without file headers if hunk headers exist", () => { + const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@ + line1 +-line2 ++newline2 ++newline3 + line3`; + expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true); + }); + + it("should return true in case of empty lines", () => { + const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@ + line1 + +-line2 ++newline2 + + line3`; + expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true); + }); +}); + +describe("applyUnifiedDiff", () => { + it("should correctly apply a add line of unified diff", () => { + const sourceCode = `func main() { + scanner := bufio.NewScanner(os.Stdin) + fmt.Println("Calculator started! Available operations:") + fmt.Println(" + : Addition") + fmt.Println(" - : Subtraction") + fmt.Println(" * : Multiplication") + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") +} +// End of file`; + + const diffText = `--- original.go ++++ updated.go +@@ -30,6 +30,7 @@ + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") ++ fmt.Println(" log: Logarithm (use 'log base number')") + }`; + + const result = applyUnifiedDiff(sourceCode, diffText); + + const expected = [ + { type: "same", line: "func main() {" }, + { type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" }, + { type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" }, + { type: "same", line: " fmt.Println(\" + : Addition\")" }, + { type: "same", line: " fmt.Println(\" - : Subtraction\")" }, + { type: "same", line: " fmt.Println(\" * : Multiplication\")" }, + { type: "same", line: " fmt.Println(\" / : Division\")" }, + { type: "same", line: " fmt.Println(\" ^ : Power\")" }, + { type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" }, + { type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" }, + { type: "same", line: "}" }, + { type: "same", line: "// End of file" } + ]; + + expect(result).toEqual(expected); + }); + + it("should correctly apply multiple insertions and deletions", () => { + const sourceCode = `package main + +import "fmt" + +func main() { + fmt.Println("Hello") + fmt.Println("World") +}`; + + const diffText = `--- original.go ++++ updated.go +@@ -1,8 +1,11 @@ + package main + +-import "fmt" ++import ( ++ "fmt" ++ "time" ++) + + func main() { +- fmt.Println("Hello") ++ fmt.Printf("The time is: %v\\n", time.Now()) +- fmt.Println("World") ++ fmt.Println("Goodbye!") + }`; + const result = applyUnifiedDiff(sourceCode, diffText); + + const expected = [ + { type: "same", line: "package main" }, + { type: "same", line: "" }, + { type: "old", line: "import \"fmt\"" }, + { type: "new", line: "import (" }, + { type: "new", line: " \"fmt\"" }, + { type: "new", line: " \"time\"" }, + { type: "new", line: ")" }, + { type: "same", line: "" }, + { type: "same", line: "func main() {" }, + { type: "old", line: " fmt.Println(\"Hello\")" }, + { type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" }, + { type: "old", line: " fmt.Println(\"World\")" }, + { type: "new", line: " fmt.Println(\"Goodbye!\")" }, + { type: "same", line: "}" } + ]; + + expect(result).toEqual(expected); + }); + + it("should correctly apply multiple diff blocks", () => { + const sourceCode = `package main +import ( + "bufio" + "fmt" + "math" + "os" + "strconv" + "strings" + "testing" +) +func main() { + scanner := bufio.NewScanner(os.Stdin) + fmt.Println("Calculator started! Available operations:") + fmt.Println(" + : Addition") + fmt.Println(" - : Subtraction") + fmt.Println(" * : Multiplication") + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") + for { + fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ") + scanner.Scan() + input := scanner.Text() + if strings.ToLower(input) == "q" { + fmt.Println("Goodbye!") + break + } + result, err := calculate(input) + if err != nil { + fmt.Printf("Error: %v\n", err) + continue + } + fmt.Printf("Result: %v\n", result) + } +} +func calculate(input string) (float64, error) { + parts := strings.Fields(input) + if len(parts) < 2 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number' or '√ number'") + } + if parts[0] == "√" { + if len(parts) != 2 { + return 0, fmt.Errorf("square root operation requires exactly one number") + } + num, err := strconv.ParseFloat(parts[1], 64) + if err != nil { + return 0, fmt.Errorf("invalid number for square root: %v", err) + } + if num < 0 { + return 0, fmt.Errorf("cannot calculate square root of a negative number") + } + return math.Sqrt(num), nil + } + if len(parts) != 3 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number'") + } + num1, err := strconv.ParseFloat(parts[0], 64) + if err != nil { + return 0, fmt.Errorf("invalid first number: %v", err) + } + operator := parts[1] + num2, err := strconv.ParseFloat(parts[2], 64) + if err != nil { + return 0, fmt.Errorf("invalid second number: %v", err) + } + switch operator { + case "+": + return num1 + num2, nil + case "-": + return num1 - num2, nil + case "*": + return num1 * num2, nil + case "/": + if num2 == 0 { + return 0, fmt.Errorf("division by zero is not allowed") + } + return num1 / num2, nil + case "^": + return math.Pow(num1, num2), nil + default: + return 0, fmt.Errorf("invalid operator: must be +, -, *, /, ^, or √") + } +} +func TestCalculate(t *testing.T) { + tests := []struct { + input string + expected float64 + hasError bool + }{ + {"2 + 3", 5, false}, + {"10 - 5", 5, false}, + {"4 * 3", 12, false}, + {"15 / 3", 5, false}, + {"2 ^ 3", 8, false}, + {"√ 16", 4, false}, + {"2 + a", 0, true}, + {"15 / 0", 0, true}, + {"√ -4", 0, true}, + {"3 $ 4", 0, true}, + {"", 0, true}, + {"1", 0, true}, + {"1 +", 0, true}, + {"+ 1", 0, true}, + {"√ 2 3", 0, true}, + } + for _, test := range tests { + result, err := calculate(test.input) + if test.hasError && err == nil { + t.Errorf("Expected error for input '%s', but got none", test.input) + continue + } + if !test.hasError && err != nil { + t.Errorf("Unexpected error for input '%s': %v", test.input, err) + continue + } + if !test.hasError && result != test.expected { + t.Errorf("For input '%s': expected %f, but got %f", test.input, test.expected, result) + } + } +} +func TestSpecialCases(t *testing.T) { + result, err := calculate("2.5 + 2.5") + if err != nil { + t.Errorf("Unexpected error for floating point addition: %v", err) + } + if result != 5.0 { + t.Errorf("Floating point addition failed: expected 5.0, got %f", result) + } + result, err = calculate("2.5 ^ 2") + if err != nil { + t.Errorf("Unexpected error for power operation: %v", err) + } + expected := 6.25 + if math.Abs(result-expected) > 0.0001 { + t.Errorf("Power operation failed: expected %f, got %f", expected, result) + } + result, err = calculate("√ 2") + if err != nil { + t.Errorf("Unexpected error for square root: %v", err) + } + expected = math.Sqrt(2) + if math.Abs(result-expected) > 0.0001 { + t.Errorf("Square root operation failed: expected %f, got %f", expected, result) + } +} +func TestLargeNumbers(t *testing.T) { + result, err := calculate("1000000000 + 1000000000") + if err != nil { + t.Errorf("Unexpected error for adding large numbers: %v", err) + } + if result != 2000000000 { + t.Errorf("Adding large numbers failed: expected 2000000000, got %f", result) + } + result, err = calculate("1000000 * 1000000") + if err != nil { + t.Errorf("Unexpected error for multiplying large numbers: %v", err) + } + if result != 1000000000000 { + t.Errorf("Multiplying large numbers failed: expected 1000000000000, got %f", result) + } + result, err = calculate("2 ^ 30") + if err != nil { + t.Errorf("Unexpected error for large exponent operation: %v", err) + } + expected := math.Pow(2, 30) + if result != expected { + t.Errorf("Power operation with large exponent failed: expected %f, got %f", expected, result) + } + result, err = calculate("1000000000000 / 1000000") + if err != nil { + t.Errorf("Unexpected error for dividing large numbers: %v", err) + } + if result != 1000000 { + t.Errorf("Dividing large numbers failed: expected 1000000, got %f", result) + } +}`; + + const diffText = `--- original.go ++++ updated.go +@@ -30,6 +30,7 @@ + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") ++ fmt.Println(" log: Logarithm (use 'log base number')") ++ fmt.Println(" Base must be > 0 and != 1, number must be > 0") + for { + fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ") +@@ -73,6 +74,8 @@ + } + return math.Sqrt(num), nil + } ++ ++ // Handle logarithmic operations ++ if parts[0] == "log" { ++ if len(parts) != 3 { ++ return 0, fmt.Errorf("logarithm operation requires exactly two arguments: 'log base number'") ++ } ++ base, err := strconv.ParseFloat(parts[1], 64) ++ if err != nil || base <= 0 || base == 1 { ++ return 0, fmt.Errorf("invalid base for logarithm: must be > 0 and != 1") ++ } ++ num, err := strconv.ParseFloat(parts[2], 64) ++ if err != nil || num <= 0 { ++ return 0, fmt.Errorf("invalid number for logarithm: must be > 0") ++ } ++ return math.Log(num) / math.Log(base), nil ++ } ++ + if len(parts) != 3 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number'") +@@ -155,6 +158,15 @@ + } + } + } ++ ++func TestLogarithmicCases(t *testing.T) { ++ tests := []struct { ++ input string ++ expected float64 ++ hasError bool ++ }{ ++ {"log 2 8", 3, false}, ++ {"log 10 100", 2, false}, ++ {"log 10 -5", 0, true}, ++ {"log 1 100", 0, true}, ++ {"log 0.5 0.25", 2, false}, ++ }`; + const result = applyUnifiedDiff(sourceCode, diffText); + + expect(result[0].line).toEqual("package main"); + // 1st block + expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")"); + expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")"); + expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")"); + // 2nd block + expect(result[56]).toEqual({type: "same", line: "\t}"}); + expect(result[57]).toEqual({type: "new", line: "\t"}); + expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"}); + expect(result[73]).toEqual({type: "new", line: ""}); + expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"}); + // 3rd block + expect(result[140]).toEqual({type: "same", line: "}"}); + expect(result[141]).toEqual({type: "new", line: ""}); + expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"}); + expect(result[153]).toEqual({type: "new", line: "\t}"}); + expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"}); + }); + + it("should throw error when hunk cannot be matched to source", () => { + const sourceCode = `line1 +line2 +line3`; + + const diffText = `--- a.txt ++++ b.txt +@@ -1,3 +1,4 @@ +missing1 +-missing2 ++newline2 +missing3`; + + expect(() => applyUnifiedDiff(sourceCode, diffText)) + .toThrow("Hunk could not be applied cleanly to source code."); + }); +}); diff --git a/core/edit/lazy/unifiedDiffApply.ts b/core/edit/lazy/unifiedDiffApply.ts new file mode 100644 index 000000000..c5768f1d4 --- /dev/null +++ b/core/edit/lazy/unifiedDiffApply.ts @@ -0,0 +1,152 @@ +import { DiffLine } from "../../index"; + +/** + * Checks if a string matches unified diff format by validating: + * 1. Has at least one hunk header (@@ -n,m +n,m @@) + * 2. Contains valid diff content lines (starting with +, -, or space) which are not header lines + */ +export function isUnifiedDiffFormat(diff: string): boolean { + const lines = diff.trim().split("\n"); + + if (lines.length < 3) {return false;} + + let hasHunkHeader = false; + let hasValidContent = false; + + for (const line of lines) { + if (line.startsWith("---") || line.startsWith("+++")) { + // ignore file headers - they are not required or useful + } else if (line.match(/^@@ -\d+,?\d* \+\d+,?\d* @@/)) { + hasHunkHeader = true; + } else if (line.match(/^[+ -]/) || line === "") { + hasValidContent = true; + } + } + + return hasHunkHeader && hasValidContent; +} + +function extractBeforeLines(hunkLines: string[]): string[] { + return hunkLines + .filter((line) => line.startsWith("-") || !line.startsWith("+")) + .map((line) => line.substring(1)); +} + +/** + * Applies a unified diff to source code and returns an array of DiffLine objects. + * Each DiffLine contains a type ("same", "new", or "old") and the line content. + * + * @throws Error if the diff cannot be cleanly applied to the source + */ +export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] { + const sourceLines = sourceCode.split(/\r?\n/); + const hunks = parseUnifiedDiff(unifiedDiffText); + const diffResult: DiffLine[] = []; + let currentPos = 0; // pointer in sourceLines + + for (const hunk of hunks) { + const hunkBeforeLines = extractBeforeLines(hunk.lines); + const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos); + if (hunkStart === -1) { + // All hunks must be found in the source code. If not, throw an error. + throw new Error("Hunk could not be applied cleanly to source code."); + } + + // Emit any unchanged lines that come before this hunk. + for (let i = currentPos; i < hunkStart; i++) { + diffResult.push({ type: "same", line: sourceLines[i] }); + } + let hunkSourcePos = hunkStart; + + for (const dline of hunk.lines) { + const srcLine = sourceLines[hunkSourcePos]; + if (dline.startsWith("+")) { + // Insertion: output new line (strip the '+' marker) + diffResult.push({ type: "new", line: dline.substring(1) }); + } else if (dline.startsWith("-")) { + // Removal: output the removed (old) line and advance the pointer. + diffResult.push({ type: "old", line: srcLine }); + hunkSourcePos++; + } else { + // Context line: use the source line (in case the diff’s context has a minor whitespace error) + // and advance the pointer. + diffResult.push({ type: "same", line: srcLine }); + hunkSourcePos++; + } + } + currentPos = hunkSourcePos; + } + + for (let i = currentPos; i < sourceLines.length; i++) { + diffResult.push({ type: "same", line: sourceLines[i] }); + } + return diffResult; +} + +interface Hunk { + lines: string[]; +} + +/** + * Parses a unified diff string into an array of hunks. + * It skips the file header lines (starting with "---" or "+++") and hunk header lines (starting with "@@"), + * then collects the remaining lines (which may start with '+' or '-' or have no prefix). + */ +function parseUnifiedDiff(diffText: string): Hunk[] { + const lines = diffText.split(/\r?\n/); + const hunks: Hunk[] = []; + let currentHunk: Hunk | null = null; + + for (const line of lines) { + if (line.startsWith("---") || line.startsWith("+++")) { + // Skip file header lines. + continue; + } + if (line.startsWith("@@")) { + if (currentHunk) { + hunks.push(currentHunk); + } + currentHunk = { lines: [] }; + continue; + } + currentHunk?.lines.push(line); + } + if (currentHunk) { + hunks.push(currentHunk); + } + return hunks; +} + +/** + * Searches for an occurrence of the block of lines (the “before” block) in sourceLines, + * starting at startIndex. Comparison is done by checking if the lines are exactly equal, + * or if their trimmed versions are equal. + * + * Returns the index in sourceLines where the block begins, or -1 if no match is found. + */ +function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number { + for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) { + let match = true; + for (let j = 0; j < hunkBeforeLines.length; j++) { + const sl = sourceLines[i + j]; + const hl = hunkBeforeLines[j]; + if (!linesMatch(sl, hl)) { + match = false; + break; + } + } + if (match) { + return i; + } + } + return -1; +} + +/** + * Returns true if the two lines are either exactly equal or equal after trimming whitespace and tabs. + */ +function linesMatch(a: string, b: string): boolean { + const trimmedA = a.replace(/^\s+/, ""); + const trimmedB = b.replace(/^\s+/, ""); + return trimmedA === trimmedB; +} diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index f7b54dff6..4f530cd60 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -78,9 +78,6 @@ export async function* streamDiffLines( oldLines = []; } - // Trim end of oldLines, otherwise we have trailing \r on every line for CRLF files - oldLines = oldLines.map((line) => line.trimEnd()); - const prompt = overridePrompt ?? constructPrompt(prefix, highlighted, suffix, llm, input, language); diff --git a/core/index.d.ts b/core/index.d.ts index c2a11dad8..d28968e85 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -43,13 +43,13 @@ export interface IndexingProgressUpdate { desc: string; shouldClearIndexes?: boolean; status: - | "loading" - | "indexing" - | "done" - | "failed" - | "paused" - | "disabled" - | "cancelled"; + | "loading" + | "indexing" + | "done" + | "failed" + | "paused" + | "disabled" + | "cancelled"; debugInfo?: string; } @@ -163,6 +163,14 @@ export interface ILLM extends LLMOptions { ): string | ChatMessage[]; } +export interface ModelInstaller { + installModel( + modelName: string, + signal: AbortSignal, + progressReporter?: (task: string, increment: number, total: number) => void, + ): Promise; +} + export type ContextProviderType = "normal" | "query" | "submenu"; export interface ContextProviderDescription { @@ -308,7 +316,7 @@ export interface CompletionOptions extends BaseCompletionOptions { model: string; } -export type ChatMessageRole = "user" | "assistant" | "system" | "tool"; +export type ChatMessageRole = "user" | "assistant" | "thinking" | "system" | "tool"; export type TextMessagePart = { type: "text"; @@ -353,6 +361,14 @@ export interface UserChatMessage { content: MessageContent; } +export interface ThinkingChatMessage { + role: "thinking"; + content: MessageContent; + signature?: string; + redactedThinking?: string; + toolCalls?: ToolCallDelta[]; +} + export interface AssistantChatMessage { role: "assistant"; content: MessageContent; @@ -367,6 +383,7 @@ export interface SystemChatMessage { export type ChatMessage = | UserChatMessage | AssistantChatMessage + | ThinkingChatMessage | SystemChatMessage | ToolResultChatMessage; @@ -543,7 +560,7 @@ export interface CustomLLMWithOptionals { signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, - ) => AsyncGenerator; + ) => AsyncGenerator; listModels?: ( fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => Promise; @@ -675,10 +692,10 @@ export interface IDE { getCurrentFile(): Promise< | undefined | { - isUntitled: boolean; - path: string; - contents: string; - } + isUntitled: boolean; + path: string; + contents: string; + } >; getLastFileSaveTimestamp?(): number; @@ -862,11 +879,11 @@ export interface CustomCommand { export interface Prediction { type: "content"; content: - | string - | { - type: "text"; - text: string; - }[]; + | string + | { + type: "text"; + text: string; + }[]; } export interface ToolExtras { @@ -917,6 +934,8 @@ export interface BaseCompletionOptions { prediction?: Prediction; tools?: Tool[]; toolChoice?: ToolChoice; + reasoning?: boolean; + reasoningBudgetTokens?: number; } export interface ModelCapability { @@ -1205,9 +1224,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | ILLM; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | CustomLLM + | ModelDescription + | (CustomLLM | ModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -1239,6 +1258,7 @@ export interface ContinueConfig { analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + rules?: string[]; modelsByRole: Record; selectedModelByRole: Record; data?: DataDestination[]; @@ -1260,6 +1280,7 @@ export interface BrowserSerializedContinueConfig { analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + rules?: string[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; modelsByRole: Record; @@ -1299,9 +1320,9 @@ export type PackageDetailsSuccess = PackageDetails & { export type PackageDocsResult = { packageInfo: ParsedPackageInfo; } & ( - | { error: string; details?: never } - | { details: PackageDetailsSuccess; error?: never } -); + | { error: string; details?: never } + | { details: PackageDetailsSuccess; error?: never } + ); export interface TerminalOptions { reuseTerminal?: boolean; diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index c0d386d07..bf733b5ce 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -7,12 +7,7 @@ import { getQueryForFile, } from "../util/treeSitter"; -import { - DatabaseConnection, - SqliteDb, - tagToString, - truncateSqliteLikePattern, -} from "./refreshIndex"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, @@ -398,18 +393,23 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { static async getPathsAndSignatures( workspaceDirs: string[], - offset: number = 0, - batchSize: number = 100, + uriOffset: number = 0, + uriBatchSize: number = 100, + snippetOffset: number = 0, + snippetBatchSize: number = 100, ): Promise<{ groupedByUri: { [path: string]: string[] }; - hasMore: boolean; + hasMoreSnippets: boolean; + hasMoreUris: boolean; }> { const db = await SqliteDb.get(); await CodeSnippetsCodebaseIndex._createTables(db); - const likePatterns = workspaceDirs.map((dir) => - truncateSqliteLikePattern(`${dir}%`), - ); + const endIndex = uriOffset + uriBatchSize; + const uriBatch = workspaceDirs.slice(uriOffset, endIndex); + + const likePatterns = uriBatch.map((dir) => `${dir}%`); + const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); const query = ` @@ -420,7 +420,11 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { LIMIT ? OFFSET ? `; - const rows = await db.all(query, [...likePatterns, batchSize, offset]); + const rows = await db.all(query, [ + ...likePatterns, + snippetBatchSize, + snippetOffset, + ]); const groupedByUri: { [path: string]: string[] } = {}; @@ -431,8 +435,9 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { groupedByUri[path].push(signature); } - const hasMore = rows.length === batchSize; + const hasMoreUris = endIndex < workspaceDirs.length; + const hasMoreSnippets = rows.length === snippetBatchSize; - return { groupedByUri, hasMore }; + return { groupedByUri, hasMoreUris, hasMoreSnippets }; } } diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 517298597..cdcd61006 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -14,12 +14,12 @@ import { } from "../test/testDir.js"; import { getIndexSqlitePath } from "../util/paths.js"; +import { localPathToUri } from "../util/pathToUri.js"; import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; import { CodebaseIndex } from "./types.js"; -import { walkDir } from "./walkDir.js"; -import { localPathToUri } from "../util/pathToUri.js"; +import { walkDir, walkDirCache } from "./walkDir.js"; jest.useFakeTimers(); @@ -87,6 +87,10 @@ describe("CodebaseIndexer", () => { tearDownTestDir(); }); + afterEach(() => { + walkDirCache.invalidate(); + }); + async function refreshIndex() { const abortController = new AbortController(); const abortSignal = abortController.signal; diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index d59f0ded8..f0f1cd4bb 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -97,7 +97,6 @@ export class CodebaseIndexer { const lanceDbIndex = await LanceDbIndex.create( embeddingsModel, this.ide.readFile.bind(this.ide), - this.continueServerClient, ); if (lanceDbIndex) { @@ -282,7 +281,9 @@ export class CodebaseIndexer { status: "indexing", }; const directoryFiles = []; - for await (const p of walkDirAsync(directory, this.ide)) { + for await (const p of walkDirAsync(directory, this.ide, { + source: "codebase indexing: refresh dirs", + })) { directoryFiles.push(p); if (abortSignal.aborted) { yield { diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index ac6ed3591..ad28b3456 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -9,7 +9,6 @@ import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { mockPathAndCacheKey, mockTag, - testContinueServerClient, updateIndexAndAwaitGenerator, } from "./test/indexing"; import { IndexResultType } from "./types"; @@ -37,7 +36,6 @@ describe.skip("ChunkCodebaseIndex", () => { index = (await LanceDbIndex.create( mockConfig.selectedModelByRole.embed, testIde.readFile.bind(testIde), - testContinueServerClient, ))!; sqliteDb = await SqliteDb.get(); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 168a4ff07..3bf9a645d 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -2,7 +2,6 @@ import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; import { isSupportedLanceDbCpuTargetForLinux } from "../config/util"; -import { IContinueServerClient } from "../continueServer/interface"; import { BranchAndDir, Chunk, @@ -13,8 +12,9 @@ import { import { getLanceDbPath, migrate } from "../util/paths"; import { getUriPathBasename } from "../util/uri"; -import { chunkDocument, shouldChunk } from "./chunk/chunk"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; +import { basicChunker } from "./chunk/basic.js"; +import { chunkDocument, shouldChunk } from "./chunk/chunk.js"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { CodebaseIndex, IndexResultType, @@ -57,7 +57,6 @@ export class LanceDbIndex implements CodebaseIndex { static async create( embeddingsProvider: ILLM, readFile: (filepath: string) => Promise, - continueServerClient?: IContinueServerClient, ): Promise { if (!isSupportedLanceDbCpuTargetForLinux()) { return null; @@ -65,11 +64,7 @@ export class LanceDbIndex implements CodebaseIndex { try { this.lance = await import("vectordb"); - return new LanceDbIndex( - embeddingsProvider, - readFile, - continueServerClient, - ); + return new LanceDbIndex(embeddingsProvider, readFile); } catch (err) { console.error("Failed to load LanceDB:", err); return null; @@ -79,7 +74,6 @@ export class LanceDbIndex implements CodebaseIndex { private constructor( private readonly embeddingsProvider: ILLM, private readonly readFile: (filepath: string) => Promise, - private readonly continueServerClient?: IContinueServerClient, ) { if (!LanceDbIndex.lance) { throw new Error("LanceDB not initialized"); @@ -278,60 +272,6 @@ export class LanceDbIndex implements CodebaseIndex { await markComplete(pathAndCacheKeys, IndexResultType.Compute); }; - if (this.continueServerClient?.connected) { - try { - const keys = results.compute.map(({ cacheKey }) => cacheKey); - const resp = await this.continueServerClient.getFromIndexCache( - keys, - "embeddings", - repoName, - ); - for (const [cacheKey, chunks] of Object.entries(resp.files)) { - const path = results.compute.find( - (item) => item.cacheKey === cacheKey, - )?.path; - if (!path) { - console.warn( - "Continue server sent a cacheKey that wasn't requested", - cacheKey, - ); - continue; - } - - const rows: LanceDbRow[] = []; - for (const chunk of chunks) { - const row = { - path, - cachekey: cacheKey, - uuid: uuidv4(), - vector: chunk.vector, - }; - rows.push(row); - - await sqliteDb.run( - "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - row.uuid, - row.cachekey, - row.path, - this.artifactId, - JSON.stringify(row.vector), - chunk.startLine, - chunk.endLine, - chunk.contents, - ); - } - - await addComputedLanceDbRows([{ cacheKey, path }], rows); - } - - results.compute = results.compute.filter( - (item) => !resp.files[item.cacheKey], - ); - } catch (e) { - console.log("Error checking remote cache: ", e); - } - } - yield { progress: 0, desc: `Computing embeddings for ${ @@ -469,7 +409,25 @@ export class LanceDbIndex implements CodebaseIndex { if (!this.embeddingsProvider) { return []; } - const [vector] = await this.embeddingsProvider.embed([query]); + + // Use just the first chunk of the user query in case it is too long + const chunks = []; + for await (const chunk of basicChunker( + query, + this.embeddingsProvider.maxEmbeddingChunkSize, + )) { + chunks.push(chunk); + } + let vector = null; + try { + [vector] = await this.embeddingsProvider.embed( + chunks.map((c) => c.content), + ); + } catch (err) { + // If we fail to chunk, we just use what was happening before. + [vector] = await this.embeddingsProvider.embed([query]); + } + const db = await lance.connect(getLanceDbPath()); let allResults = []; diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index 20a2a19b0..d51f368a2 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -1,7 +1,5 @@ import { Chunk, ChunkWithoutID } from "../../index.js"; import { countTokensAsync } from "../../llm/countTokens.js"; -import { extractMinimalStackTraceInfo } from "../../util/extractMinimalStackTraceInfo.js"; -import { Telemetry } from "../../util/posthog.js"; import { supportedLanguages } from "../../util/treeSitter.js"; import { getUriFileExtension, getUriPathBasename } from "../../util/uri.js"; @@ -31,10 +29,6 @@ async function* chunkDocumentWithoutId( } return; } catch (e: any) { - void Telemetry.capture("code_chunker_error", { - fileExtension: extension, - stack: extractMinimalStackTraceInfo(e.stack), - }); // falls back to basicChunker } } diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 6075bdb26..7f5e8a039 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -114,6 +114,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); export const DEFAULT_IGNORE = DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n"); +export const defaultIgnoreFileAndDir = ignore() + .add(defaultIgnoreFile) + .add(defaultIgnoreDir); + export function gitIgArrayFromFile(file: string) { return file .split(/\r?\n/) // Split on new line diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts new file mode 100644 index 000000000..c1935e7d9 --- /dev/null +++ b/core/indexing/shouldIgnore.test.ts @@ -0,0 +1,167 @@ +// Generated by continue + +import { testIde } from "../test/fixtures"; +import { + TEST_DIR, + addToTestDir, + setUpTestDir, + tearDownTestDir, +} from "../test/testDir"; + +import { shouldIgnore } from "./shouldIgnore"; + +// Test for the shouldIgnore function +describe("shouldIgnore", () => { + beforeEach(() => { + setUpTestDir(); + }); + + afterEach(() => { + tearDownTestDir(); + }); + + test("should return true if a file is ignored by .gitignore", async () => { + addToTestDir([ + ["ignored-file.txt", "content"], + [".gitignore", "ignored-file.txt"], + ]); + const result = await shouldIgnore(TEST_DIR + "/ignored-file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + test("should return true if a folder is ignored by .continueignore", async () => { + addToTestDir([ + ["ignored-folder/file.txt", "content"], + [".continueignore", "ignored-folder/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/ignored-folder/file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(true); + }); + test("should return false if a file is not ignored", async () => { + addToTestDir([["kept-file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept-file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + test("should return true if a file is ignored by .gitignore with spaces in file name", async () => { + addToTestDir([ + ["ignored file.txt", "content"], + [".gitignore", "ignored file.txt"], + ]); + const result = await shouldIgnore(TEST_DIR + "/ignored file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + + test("should return true if a .continueignore override ignores file", async () => { + addToTestDir([ + ["override-file.txt", "content"], + [".gitignore", "override-file.txt"], + [".continueignore", "!override-file.txt"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/override-file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(false); + }); + + test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => { + addToTestDir([ + ["level1/level2/level3/ignored-file.txt", "content"], + ["level1/.gitignore", "level2/"], + ["level1/level2/.continueignore", "level3/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/level1/level2/level3/ignored-file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(true); + }); + + test("should return false if a file with spaces is not ignored", async () => { + addToTestDir([["kept file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + + test("should handle multiple levels of directories with some files ignored", async () => { + addToTestDir([ + ["nested/dir1/.gitignore", "ignored.txt"], + ["nested/dir1/ignored.txt", "content"], + ["nested/dir2/kept.txt", "content"], + ]); + const ignoredResult = await shouldIgnore( + TEST_DIR + "/nested/dir1/ignored.txt", + testIde, + [TEST_DIR], + ); + expect(ignoredResult).toBe(true); + + const keptResult = await shouldIgnore( + TEST_DIR + "/nested/dir2/kept.txt", + testIde, + [TEST_DIR], + ); + expect(keptResult).toBe(false); + }); + + test("should respect default file and folder ignores top level", async () => { + addToTestDir([ + [".env", "contents"], + ["go.sum", "contents"], + ".idea/", + [".idea/test.xml", "contents"], + ]); + let result = await shouldIgnore(TEST_DIR + "/.env", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/go.sum", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/.idea", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/.idea/test.xml", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + + test("should respect default file and folder ignores at nested level", async () => { + addToTestDir([ + "nested/.idea/test.xml", + ["nested/.env", "contents"], + ["nested/go.sum", "contents"], + ]); + + let result = await shouldIgnore(TEST_DIR + "/nested/.idea", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/.idea/test.xml", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/.env", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/go.sum", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); +}); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts new file mode 100644 index 000000000..dd82a0457 --- /dev/null +++ b/core/indexing/shouldIgnore.ts @@ -0,0 +1,73 @@ +import ignore from "ignore"; +import type { FileType, IDE } from "../"; +import { findUriInDirs, getUriPathBasename } from "../util/uri"; +import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore"; +import { getIgnoreContext } from "./walkDir"; + +/* + Process: + 1. Check global/default ignores + 2. Walk UP tree from file, checking ignores at each level + + TODO there might be issues with symlinks here +*/ +export async function shouldIgnore( + fileUri: string, + ide: IDE, + rootDirCandidates?: string[], +): Promise { + const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs()); + const { foundInDir: rootDir, uri } = findUriInDirs(fileUri, rootDirUris); + + if (!rootDir) { + return true; + } + + const defaultAndGlobalIgnores = ignore() + .add(defaultIgnoreFileAndDir) + .add(getGlobalContinueIgArray()); + + let currentDir = uri; + let directParent = true; + let fileType = 1 as FileType.File as FileType; + while (currentDir !== rootDir) { + // Go to parent dir of file + const splitUri = currentDir.split("/"); + splitUri.pop(); + currentDir = splitUri.join("/"); + + // Get all files in the dir + const dirEntries = await ide.listDir(currentDir); + + // Check if the file is a symbolic link, ignore if so + if (directParent) { + directParent = false; + const baseName = getUriPathBasename(fileUri); + const entry = dirEntries.find(([name, _]) => name === baseName); + if (entry) { + fileType = entry[1]; + if (fileType === (64 as FileType.SymbolicLink)) { + return true; + } + } + } + + const ignoreContext = await getIgnoreContext( + currentDir, + dirEntries, + ide, + defaultAndGlobalIgnores, + ); + + let relativePath = uri.substring(currentDir.length + 1); + if (fileType === (2 as FileType.Directory)) { + relativePath += "/"; + } + + if (ignoreContext.ignores(relativePath)) { + return true; + } + } + + return false; +} diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 8a9d26e7e..399a24875 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -1,14 +1,19 @@ // Generated by continue -import { testIde } from "../test/fixtures"; -import { - setUpTestDir, - tearDownTestDir, - addToTestDir, - TEST_DIR_PATH, -} from "../test/testDir"; -import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir"; import fs from "fs"; import path from "path"; +import { + walkDir, + walkDirAsync, + walkDirCache, + walkDirs, +} from "../indexing/walkDir"; +import { testIde } from "../test/fixtures"; +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, + TEST_DIR_PATH, +} from "../test/testDir"; describe("walkDir functions", () => { beforeEach(async () => { @@ -17,8 +22,30 @@ describe("walkDir functions", () => { afterEach(async () => { tearDownTestDir(); + walkDirCache.invalidate(); }); + // describe.only("test speed", () => { + // it("should walk a simple directory structure", async () => { + // addToTestDir([ + // "src/", + // ["src/file1.ts", "content1"], + // ["src/file2.ts", "content2"], + // "src/nested/", + // ["src/nested/file3.ts", "content3"], + // ]); + + // const dir = await testIde.getWorkspaceDirs(); + + // const start = Date.now(); + // for (let i = 0; i < 10000; i++) { + // await walkDir(dir[0], testIde); + // } + // const passed = Date.now() - start; + // console.log(`Test took ${passed} ms`); + // }); + // }); + describe("walkDir", () => { it("should walk a simple directory structure", async () => { addToTestDir([ @@ -171,12 +198,7 @@ describe("walkDir functions", () => { it("should skip symlinks", async () => { const filePath = path.join(TEST_DIR_PATH, "real.ts"); addToTestDir([["real.ts", "content"]]); - fs.symlink( - filePath, - path.join(TEST_DIR_PATH, "symlink.ts"), - "file", - () => {}, - ); + fs.symlinkSync(filePath, path.join(TEST_DIR_PATH, "symlink.ts"), "file"); const files = await walkDirs(testIde); @@ -313,6 +335,9 @@ describe("walkDir functions", () => { ["node_modules/package/index.js", "content"], ["dist/bundle.js", "content"], ["coverage/lcov.env", "content"], + ["nested/node_modules/package/index.js", "content"], + ["nested/dist/bundle.js", "content"], + ["nested/coverage/lcov.env", "content"], ]); const files = await walkDir( @@ -327,6 +352,9 @@ describe("walkDir functions", () => { expect(files).not.toContain(".git/config"); expect(files).not.toContain("node_modules/package/index.js"); expect(files).not.toContain("coverage/lcov.info"); + expect(files).not.toContain("nested/node_modules/package/index.js"); + expect(files).not.toContain("nested/dist/bundle.js"); + expect(files).not.toContain("nested/coverage/lcov.env"); }); it("should handle directory-specific ignore patterns correctly", async () => { diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 4e97e01d4..2c70006a8 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -2,27 +2,28 @@ import ignore, { Ignore } from "ignore"; import type { FileType, IDE } from ".."; +import { joinPathsToUri } from "../util/uri"; import { - DEFAULT_IGNORE_DIRS, - DEFAULT_IGNORE_FILETYPES, - defaultIgnoreDir, - defaultIgnoreFile, + defaultIgnoreFileAndDir, getGlobalContinueIgArray, gitIgArrayFromFile, } from "./ignore"; -import { joinPathsToUri } from "../util/uri"; export interface WalkerOptions { - ignoreFiles?: string[]; onlyDirs?: boolean; returnRelativeUrisPaths?: boolean; - additionalIgnoreRules?: string[]; + source?: string; + overrideDefaultIgnores?: Ignore; } type Entry = [string, FileType]; +const LIST_DIR_CACHE_TIME = 30_000; // 30 seconds +const IGNORE_FILE_CACHE_TIME = 30_000; // 30 seconds + // helper struct used for the DFS walk type WalkableEntry = { + name: string; relativeUriPath: string; uri: string; type: FileType; @@ -40,144 +41,210 @@ type IgnoreContext = { dirname: string; }; -class DFSWalker { - private readonly ignoreFileNames: Set; +class WalkDirCache { + dirListCache: Map< + string, + { + time: number; + entries: Promise<[string, FileType][]>; + } + > = new Map(); + dirIgnoreCache: Map< + string, + { + time: number; + ignore: Promise; + } + > = new Map(); + // The super safe approach for now + invalidate() { + this.dirListCache.clear(); + this.dirIgnoreCache.clear(); + } + // invalidateIgnore(uri: string) { + // this.dirIgnoreCache.delete(uri); + // } + // invalidateParent(uri: string) { + // const splitUri = fileUri.split("/"); + // splitUri.pop(); + // const parent = splitUri.join("/"); + // this.dirListCache.delete(uri); + // } +} +export const walkDirCache = new WalkDirCache(); // TODO - singleton approach better? +class DFSWalker { constructor( private readonly uri: string, private readonly ide: IDE, private readonly options: WalkerOptions, - ) { - this.ignoreFileNames = new Set(options.ignoreFiles); - } + ) {} // walk is a depth-first search implementation public async *walk(): AsyncGenerator { - const root = this.newRootWalkContext(); - const stack = [root]; - for (let cur = stack.pop(); cur; cur = stack.pop()) { - const walkableEntries = await this.listDirForWalking(cur.walkableEntry); - const ignoreContexts = await this.getIgnoreToApplyInDir( - cur, - walkableEntries, - ); - for (const w of walkableEntries) { - if (!this.shouldInclude(w, ignoreContexts)) { - continue; - } - if (this.entryIsDirectory(w.entry)) { - stack.push({ - walkableEntry: w, - ignoreContexts: ignoreContexts, - }); - if (this.options.onlyDirs) { - // when onlyDirs is enabled the walker will only return directory names - if (this.options.returnRelativeUrisPaths) { - yield w.relativeUriPath; - } else { - yield w.uri; - } - } - } else { - // Note that shouldInclude handles skipping files if options.onlyDirs is true - if (this.options.returnRelativeUrisPaths) { - yield w.relativeUriPath; - } else { - yield w.uri; - } - } - } - } - } + const start = Date.now(); + let ignoreFileTime = 0; + let ignoreTime = 0; + let listDirTime = 0; + let dirs = 0; + let listDirCacheHits = 0; + let ignoreCacheHits = 0; - private newRootWalkContext(): WalkContext { - const globalIgnoreFile = getGlobalContinueIgArray(); - return { + let section = Date.now(); + const defaultAndGlobalIgnores = ignore() + .add(this.options.overrideDefaultIgnores ?? defaultIgnoreFileAndDir) + .add(getGlobalContinueIgArray()); + ignoreFileTime += Date.now() - section; + + const rootContext: WalkContext = { walkableEntry: { + name: "", relativeUriPath: "", uri: this.uri, type: 2 as FileType.Directory, entry: ["", 2 as FileType.Directory], }, - ignoreContexts: [ + ignoreContexts: [], + }; + const stack = [rootContext]; + + for (let cur = stack.pop(); cur; cur = stack.pop()) { + // Previous no caching approach: + // const entries = await this.ide.listDir(cur.walkableEntry.uri); + // const newIgnore = await getIgnoreContext( + // cur.walkableEntry.uri, + // entries, + // this.ide, + // defaultAndGlobalIgnores, + // ); + + // Only directories will be added to the stack + dirs++; + + section = Date.now(); + let entries: [string, FileType][] = []; + const cachedListdir = walkDirCache.dirListCache.get( + cur.walkableEntry.uri, + ); + if ( + cachedListdir && + cachedListdir.time > Date.now() - LIST_DIR_CACHE_TIME + ) { + entries = await cachedListdir.entries; + listDirCacheHits++; + } else { + const promise = this.ide.listDir(cur.walkableEntry.uri); + walkDirCache.dirListCache.set(cur.walkableEntry.uri, { + time: Date.now(), + entries: promise, + }); + entries = await promise; + } + listDirTime += Date.now() - section; + + section = Date.now(); + let newIgnore: Ignore; + const cachedIgnore = walkDirCache.dirIgnoreCache.get( + cur.walkableEntry.uri, + ); + if ( + cachedIgnore && + cachedIgnore.time > Date.now() - IGNORE_FILE_CACHE_TIME + ) { + newIgnore = await cachedIgnore.ignore; + ignoreCacheHits++; + } else { + const ignorePromise = getIgnoreContext( + cur.walkableEntry.uri, + entries, + this.ide, + defaultAndGlobalIgnores, + ); + walkDirCache.dirIgnoreCache.set(cur.walkableEntry.uri, { + time: Date.now(), + ignore: ignorePromise, + }); + newIgnore = await ignorePromise; + } + + const ignoreContexts = [ + ...cur.ignoreContexts, { - ignore: ignore() - .add(defaultIgnoreDir) - .add(defaultIgnoreFile) - .add(globalIgnoreFile), - dirname: "", + ignore: newIgnore, + dirname: cur.walkableEntry.relativeUriPath, }, - ], - }; - } + ]; + ignoreFileTime += Date.now() - section; - private async listDirForWalking( - walkableEntry: WalkableEntry, - ): Promise { - const entries = await this.ide.listDir(walkableEntry.uri); - return entries.map((e) => ({ - relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`, - uri: joinPathsToUri(walkableEntry.uri, e[0]), - type: e[1], - entry: e, - })); - } + for (const entry of entries) { + if (this.entryIsSymlink(entry)) { + // If called from the root, a symlink either links to a real file in this repository, + // and therefore will be walked OR it links to something outside of the repository and + // we do not want to index it + continue; + } + const walkableEntry = { + name: entry[0], + relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`, + uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]), + type: entry[1], + entry: entry, + }; - private async getIgnoreToApplyInDir( - curDir: WalkContext, - entriesInDir: WalkableEntry[], - ): Promise { - const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir); - if (ignoreFilesInDir.length === 0) { - return curDir.ignoreContexts; - } - const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat(); - const newIgnoreContext = { - ignore: ignore().add(patterns), - dirname: curDir.walkableEntry.relativeUriPath, - }; - return [...curDir.ignoreContexts, newIgnoreContext]; - } + let relPath = walkableEntry.relativeUriPath; + if (this.entryIsDirectory(entry)) { + relPath = `${relPath}/`; + } else { + if (this.options.onlyDirs) { + continue; + } + } + let shouldIgnore = false; + for (const ig of ignoreContexts) { + if (shouldIgnore) { + continue; + } + // remove the directory name and path separator from the match path, unless this an ignore file + // in the root directory + const prefixLength = + ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; + // The ignore library expects a path relative to the ignore file location + const matchPath = relPath.substring(prefixLength); + section = Date.now(); + if (ig.ignore.ignores(matchPath)) { + shouldIgnore = true; + } + ignoreTime += Date.now() - section; + } + if (shouldIgnore) { + continue; + } - private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { - const ignoreEntries = entries.filter((w) => - this.entryIsIgnoreFile(w.entry), - ); - const promises = ignoreEntries.map(async (w) => { - return await this.ide.readFile(w.uri); - }); - return Promise.all(promises); - } - - private shouldInclude( - walkableEntry: WalkableEntry, - ignoreContexts: IgnoreContext[], - ) { - if (this.entryIsSymlink(walkableEntry.entry)) { - // If called from the root, a symlink either links to a real file in this repository, - // and therefore will be walked OR it links to something outside of the repository and - // we do not want to index it - return false; - } - let relPath = walkableEntry.relativeUriPath; - if (this.entryIsDirectory(walkableEntry.entry)) { - relPath = `${relPath}/`; - } else { - if (this.options.onlyDirs) { - return false; + 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.returnRelativeUrisPaths) { + yield walkableEntry.relativeUriPath; + } else { + yield walkableEntry.uri; + } + } + } else { + if (this.options.returnRelativeUrisPaths) { + yield walkableEntry.relativeUriPath; + } else { + yield walkableEntry.uri; + } + } } } - for (const ig of ignoreContexts) { - // remove the directory name and path separator from the match path, unless this an ignore file - // in the root directory - const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; - // The ignore library expects a path relative to the ignore file location - const matchPath = relPath.substring(prefixLength); - if (ig.ignore.ignores(matchPath)) { - return false; - } - } - return true; + // console.log( + // `Walk Dir Result:\nSource: ${this.options.source ?? "unknown"}\nDir: ${this.uri}\nDuration: ${Date.now() - start}ms:\n\tList dir: ${listDirTime}ms (${listDirCacheHits}/${dirs} cache hits)\n\tIgnore files: ${ignoreFileTime}ms (${ignoreCacheHits}/${dirs} cache hits)\n\tIgnoring: ${ignoreTime}ms`, + // ); } private entryIsDirectory(entry: Entry) { @@ -187,25 +254,22 @@ class DFSWalker { private entryIsSymlink(entry: Entry) { return entry[1] === (64 as FileType.SymbolicLink); } - - private entryIsIgnoreFile(e: Entry): boolean { - if ( - e[1] === (2 as FileType.Directory) || - e[1] === (64 as FileType.SymbolicLink) - ) { - return false; - } - return this.ignoreFileNames.has(e[0]); - } } const defaultOptions: WalkerOptions = { - ignoreFiles: [".gitignore", ".continueignore"], - additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES], onlyDirs: false, returnRelativeUrisPaths: false, }; +export async function* walkDirAsync( + path: string, + ide: IDE, + _optionOverrides?: WalkerOptions, +): AsyncGenerator { + const options = { ...defaultOptions, ..._optionOverrides }; + yield* new DFSWalker(path, ide, options).walk(); +} + export async function walkDir( uri: string, ide: IDE, @@ -218,15 +282,6 @@ export async function walkDir( return urisOrRelativePaths; } -export async function* walkDirAsync( - path: string, - ide: IDE, - _optionOverrides?: WalkerOptions, -): AsyncGenerator { - const options = { ...defaultOptions, ..._optionOverrides }; - yield* new DFSWalker(path, ide, options).walk(); -} - export async function walkDirs( ide: IDE, _optionOverrides?: WalkerOptions, @@ -238,3 +293,53 @@ export async function walkDirs( ); return results.flat(); } + +export async function getIgnoreContext( + currentDir: string, + currentDirEntries: Entry[], + ide: IDE, + defaultAndGlobalIgnores: Ignore, +) { + const dirFiles = currentDirEntries + .filter(([_, entryType]) => entryType === (1 as FileType.File)) + .map(([name, _]) => name); + + // Find ignore files and get ignore arrays from their contexts + // These are done separately so that .continueignore can override .gitignore + const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore"); + const continueIgnoreFile = dirFiles.find( + (name) => name === ".continueignore", + ); + + const getGitIgnorePatterns = async () => { + if (gitIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.gitignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; + const getContinueIgnorePatterns = async () => { + if (continueIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.continueignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; + + const ignoreArrays = await Promise.all([ + getGitIgnorePatterns(), + getContinueIgnorePatterns(), + ]); + + if (ignoreArrays[0].length === 0 && ignoreArrays[1].length === 0) { + return defaultAndGlobalIgnores; + } + + // Note precedence here! + const ignoreContext = ignore() + .add(ignoreArrays[0]) // gitignore + .add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed + .add(ignoreArrays[1]); // local .continueignore + + return ignoreContext; +} diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 4fe864bfc..05c294f9d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -58,6 +58,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [ "vertexai", "watsonx", "nebius", + "relace", ]; const PROVIDER_SUPPORTS_IMAGES: string[] = [ diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 0e4533ceb..69425d33e 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,48 +1,23 @@ -import { - ChatHistoryItem, - ChatMessage, - MessagePart, - ModelDescription, -} from "../"; +import { ChatHistoryItem, ChatMessage, MessagePart } from "../"; import { normalizeToMessageParts } from "../util/messageContent"; -import { modelSupportsTools } from "./autodetect"; - -const TOOL_USE_RULES = `When using tools, follow the following guidelines: -- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`; - -function constructSystemPrompt( - modelDescription: ModelDescription, - useTools: boolean, -): string | null { - let systemMessage = - "Always include the language and file name in the info string when you write code blocks, for example '```python file.py'."; - if (useTools && modelSupportsTools(modelDescription)) { - systemMessage += "\n\n" + TOOL_USE_RULES; - } - return systemMessage; -} +const DEFAULT_SYSTEM_MESSAGE = ` + Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'. +`; const CANCELED_TOOL_CALL_MESSAGE = "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; -export function constructMessages( - history: ChatHistoryItem[], - modelDescription: ModelDescription, - useTools: boolean, -): ChatMessage[] { +export function constructMessages(history: ChatHistoryItem[]): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", ); const msgs: ChatMessage[] = []; - const systemMessage = constructSystemPrompt(modelDescription, useTools); - if (systemMessage) { - msgs.push({ - role: "system", - content: systemMessage, - }); - } + msgs.push({ + role: "system", + content: DEFAULT_SYSTEM_MESSAGE, + }); for (let i = 0; i < filteredHistory.length; i++) { const historyItem = filteredHistory[i]; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index dfbd2da5d..a05889c52 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -27,9 +27,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); @@ -366,6 +366,7 @@ function chatMessageIsEmpty(message: ChatMessage): boolean { message.content.trim() === "" && !message.toolCalls ); + case "thinking": case "tool": return false; } @@ -383,8 +384,8 @@ function compileChatMessages( ): 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); @@ -469,5 +470,6 @@ export { pruneLinesFromTop, pruneRawPromptFromTop, pruneStringFromBottom, - pruneStringFromTop, + pruneStringFromTop }; + diff --git a/core/llm/index.ts b/core/llm/index.ts index ccbad6699..dda2e7a87 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -19,6 +19,7 @@ import { LLMFullCompletionOptions, LLMOptions, ModelCapability, + ModelInstaller, PromptLog, PromptTemplate, RequestOptions, @@ -58,6 +59,19 @@ import { toFimBody, } from "./openaiTypeConverters.js"; +export class LLMError extends Error { + constructor( + message: string, + public llm: ILLM, + ) { + super(message); + } +} + +export function isModelInstaller(provider: any): provider is ModelInstaller { + return provider && typeof provider.installModel === "function"; +} + export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; @@ -181,11 +195,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; @@ -380,9 +394,11 @@ export abstract class BaseLLM implements ILLM { if (!resp.ok) { let text = await resp.text(); if (resp.status === 404 && !resp.url.includes("/v1")) { - if (text.includes("try pulling it first")) { - const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); + const error = JSON.parse(text)?.error?.replace(/"/g, "'"); + let model = error?.match(/model '(.*)' not found/)?.[1]; + if (model && resp.url.match("127.0.0.1:11434")) { text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + throw new LLMError(text, this); // No need to add HTTP status details } else if (text.includes("/api/chat")) { text = "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; @@ -442,6 +458,10 @@ 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); } }; @@ -762,7 +782,9 @@ export abstract class BaseLLM implements ILLM { } } + let thinking = ""; let completion = ""; + let citations: null | string[] = null; try { if (this.templateMessages) { @@ -800,8 +822,16 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of stream) { const result = fromChatCompletionChunk(chunk); if (result) { + completion += result.content; yield result; } + if ( + !citations && + (chunk as any).citations && + Array.isArray((chunk as any).citations) + ) { + citations = (chunk as any).citations; + } } } } else { @@ -810,8 +840,16 @@ export abstract class BaseLLM implements ILLM { signal, completionOptions, )) { - completion += chunk.content; - yield chunk; + + if (chunk.role === "assistant") { + completion += chunk.content; + yield chunk; + } + + if (chunk.role === "thinking") { + thinking += chunk.content; + yield chunk; + } } } } @@ -823,7 +861,25 @@ export abstract class BaseLLM implements ILLM { 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`, + ); + } } return { @@ -892,7 +948,7 @@ export abstract class BaseLLM implements ILLM { ); } - protected async *_streamComplete( + protected async * _streamComplete( prompt: string, signal: AbortSignal, options: CompletionOptions, @@ -900,7 +956,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 9912b862e..ff897d5a3 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -205,10 +205,11 @@ describe("LLM", () => { }); testLLM( new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }), - { skip: false, timeout: 20000 }, + { skip: false, timeout: 60000 }, ); testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), { skip: false, + timeout: 60000, }); testLLM( new Gemini({ diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index dcd13d38e..cd48ef41b 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -30,11 +30,15 @@ class Anthropic extends BaseLLM { description: tool.function.description, input_schema: tool.function.parameters, })), + thinking: options.reasoning ? { + type: "enabled", + budget_tokens: options.reasoningBudgetTokens, + } : undefined, tool_choice: options.toolChoice ? { - type: "tool", - name: options.toolChoice.function.name, - } + type: "tool", + name: options.toolChoice.function.name, + } : undefined, }; @@ -63,6 +67,23 @@ class Anthropic extends BaseLLM { input: JSON.parse(toolCall.function?.arguments || "{}"), })), }; + } else if (message.role === "thinking" && !message.redactedThinking) { + return { + role: "assistant", + content: [{ + type: "thinking", + thinking: message.content, + signature: message.signature + }] + }; + } else if (message.role === "thinking" && message.redactedThinking) { + return { + role: "assistant", + content: [{ + type: "redacted_thinking", + data: message.redactedThinking + }] + }; } if (typeof message.content === "string") { @@ -86,7 +107,7 @@ class Anthropic extends BaseLLM { const newpart = { ...part, // If multiple text parts, only add cache_control to the last one - ...(addCaching && contentIdx == message.content.length - 1 + ...(addCaching && contentIdx === message.content.length - 1 ? { cache_control: { type: "ephemeral" } } : {}), }; @@ -174,12 +195,12 @@ class Anthropic extends BaseLLM { messages: msgs, system: shouldCacheSystemMessage ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] : systemMessage, }), signal, @@ -216,6 +237,11 @@ class Anthropic extends BaseLLM { lastToolUseId = value.content_block.id; lastToolUseName = value.content_block.name; } + // handle redacted thinking + if (value.content_block.type === "redacted_thinking") { + console.log("redacted thinking", value.content_block.data); + yield { role: "thinking", content: "", redactedThinking: value.content_block.data }; + } break; case "content_block_delta": // https://docs.anthropic.com/en/api/messages-streaming#delta-types @@ -223,6 +249,12 @@ class Anthropic extends BaseLLM { case "text_delta": yield { role: "assistant", content: value.delta.text }; break; + case "thinking_delta": + yield { role: "thinking", content: value.delta.thinking }; + break; + case "signature_delta": + yield { role: "thinking", content: "", signature: value.delta.signature }; + break; case "input_json_delta": if (!lastToolUseId || !lastToolUseName) { throw new Error("No tool use found"); diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts index d39246fa5..49ea394c7 100644 --- a/core/llm/llms/Bedrock.test.ts +++ b/core/llm/llms/Bedrock.test.ts @@ -1,5 +1,5 @@ import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; -import { fromIni } from "@aws-sdk/credential-providers"; +import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; import Bedrock from "./Bedrock.js"; import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js"; @@ -15,7 +15,7 @@ jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ // Mock credential provider jest.mock("@aws-sdk/credential-providers", () => ({ - fromIni: jest.fn().mockImplementation(() => async () => ({ + fromNodeProviderChain: jest.fn().mockImplementation(() => async () => ({ accessKeyId: "test-access-key", secretAccessKey: "test-secret-key", sessionToken: "test-session-token", diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index aa15997ad..c6abbeb97 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -1,15 +1,17 @@ import { BedrockRuntimeClient, + ContentBlock, ConverseStreamCommand, InvokeModelCommand, + Message } from "@aws-sdk/client-bedrock-runtime"; -import { fromIni } from "@aws-sdk/credential-providers"; +import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; import { ChatMessage, Chunk, CompletionOptions, - LLMOptions, + LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; @@ -86,9 +88,9 @@ class Bedrock extends BaseLLM { }); let config_headers = - this.requestOptions && this.requestOptions.headers - ? this.requestOptions.headers - : {}; + this.requestOptions && this.requestOptions.headers + ? this.requestOptions.headers + : {}; // AWS SigV4 requires strict canonicalization of headers. // DO NOT USE "_" in your header name. It will return an error like below. // "The request signature we calculated does not match the signature you provided." @@ -113,6 +115,7 @@ class Bedrock extends BaseLLM { try { response = await client.send(command, { abortSignal: signal }); } catch (error: unknown) { + console.error(error); const message = error instanceof Error ? error.message : "Unknown error"; throw new Error(`Failed to communicate with Bedrock API: ${message}`); } @@ -124,16 +127,34 @@ class Bedrock extends BaseLLM { try { for await (const chunk of response.stream) { - console.log(chunk); - if (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 }; continue; } + // Handle text content + if ((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 }; + continue; + } + + // Handle redacted thinking + if (delta.redactedReasoning?.data) { + yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data }; + continue; + } + if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) { // Append the new input to the existing string if (this._currentToolResponse.input === undefined) { @@ -145,6 +166,12 @@ class Bedrock extends BaseLLM { } if (chunk.contentBlockStart?.start) { + const start: any = chunk.contentBlockStart.start + if (start.redactedReasoning) { + yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data }; + continue; + } + const toolUse = chunk.contentBlockStart.start.toolUse; if (toolUse?.toolUseId && toolUse?.name) { this._currentToolResponse = { @@ -186,6 +213,7 @@ class Bedrock extends BaseLLM { } throw new Error("Error processing Bedrock stream: Unknown error occurred"); } + } /** @@ -232,13 +260,19 @@ class Bedrock extends BaseLLM { ?.filter((stop) => stop.trim() !== "") .slice(0, 4), }, + additionalModelRequestFields: { + "thinking": options.reasoning ? { + "type": "enabled", + "budget_tokens": options.reasoningBudgetTokens + } : undefined, + } }; } - private _convertMessage(message: ChatMessage): any { + private _convertMessage(message: ChatMessage): Message | null { // Handle system messages explicitly if (message.role === "system") { - return; + return null; } // Tool response handling @@ -265,15 +299,43 @@ class Bedrock extends BaseLLM { return { role: "assistant", content: message.toolCalls.map((toolCall) => ({ - toolUse: { - toolUseId: toolCall.id, - name: toolCall.function?.name, - input: JSON.parse(toolCall.function?.arguments || "{}"), - } + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function?.name, + input: JSON.parse(toolCall.function?.arguments || "{}"), + } })) }; } + if (message.role === "thinking") { + if (message.redactedThinking) { + const content: ContentBlock.ReasoningContentMember = { + reasoningContent: { + redactedContent: new Uint8Array(Buffer.from(message.redactedThinking)) + } + }; + return { + role: "assistant", + content: [content] + }; + } else { + const content: ContentBlock.ReasoningContentMember = { + reasoningContent: { + reasoningText: { + text: (message.content as string) || "", + signature: message.signature + } + + } + }; + return { + role: "assistant", + content: [content] + }; + } + } + // Standard text message if (typeof message.content === "string") { return { @@ -309,12 +371,14 @@ class Bedrock extends BaseLLM { } return null; }).filter(Boolean) - }; + } as Message; } + return null; } private _convertMessages(messages: ChatMessage[]): any[] { - return messages + + const converted = messages .map((message) => { try { return this._convertMessage(message); @@ -324,11 +388,13 @@ class Bedrock extends BaseLLM { } }) .filter(Boolean); + return converted; + } private async _getCredentials() { try { - return await fromIni({ + return await fromNodeProviderChain({ profile: this.profile, ignoreCache: true, })(); @@ -336,7 +402,7 @@ class Bedrock extends BaseLLM { console.warn( `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, ); - return await fromIni()(); + return await fromNodeProviderChain()(); } } diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index 45ef554a6..e74fb5064 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -1,8 +1,8 @@ import { - BedrockRuntimeClient, - InvokeModelWithResponseStreamCommand, + BedrockRuntimeClient, + InvokeModelWithResponseStreamCommand, } from "@aws-sdk/client-bedrock-runtime"; -import { fromIni } from "@aws-sdk/credential-providers"; +import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; import { CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; @@ -77,7 +77,7 @@ class BedrockImport extends BaseLLM { private async _getCredentials() { try { - return await fromIni({ + return await fromNodeProviderChain({ profile: this.profile, ignoreCache: true, })(); @@ -85,7 +85,7 @@ class BedrockImport extends BaseLLM { console.warn( `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, ); - return await fromIni()(); + return await fromNodeProviderChain()(); } } } diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 1c895c2fe..86834cb74 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -117,7 +117,7 @@ class Cohere extends BaseLLM { } async rerank(query: string, chunks: Chunk[]): Promise { - const resp = await fetch(new URL("rerank", this.apiBase), { + const resp = await this.fetch(new URL("rerank", this.apiBase), { method: "POST", headers: { Authorization: `Bearer ${this.apiKey}`, diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index 062f141f6..e04ea0ab7 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -1,4 +1,5 @@ import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; class CustomLLMClass extends BaseLLM { @@ -18,7 +19,7 @@ class CustomLLMClass extends BaseLLM { signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, - ) => AsyncGenerator; + ) => AsyncGenerator; constructor(custom: CustomLLM) { super(custom.options || { model: "custom" }); @@ -38,7 +39,11 @@ class CustomLLMClass extends BaseLLM { options, (...args) => this.fetch(...args), )) { - yield { role: "assistant", content }; + if (typeof content === "string") { + yield { role: "assistant", content }; + } else { + yield content; + } } } else { for await (const update of super._streamChat(messages, signal, options)) { @@ -68,7 +73,11 @@ class CustomLLMClass extends BaseLLM { options, (...args) => this.fetch(...args), )) { - yield content; + if (typeof content === "string") { + yield content; + } else { + yield renderChatMessage(content); + } } } else { throw new Error( diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index ee24cc3e9..e6b1c5c70 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -134,21 +134,11 @@ class Gemini extends BaseLLM { }; } - private async *streamChatGemini( + public prepareBody( messages: ChatMessage[], - signal: AbortSignal, options: CompletionOptions, - ): AsyncGenerator { - const apiURL = new URL( - `models/${options.model}:streamGenerateContent?key=${this.apiKey}`, - this.apiBase, - ); - // This feels hacky to repeat code from above function but was the quickest - // way to ensure system message re-formatting isn't done if user has specified v1 - const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase - const isV1API = apiBase.includes("/v1/"); - - // Convert chat messages to contents + isV1API: boolean, + ): GeminiChatRequestBody { const body: GeminiChatRequestBody = { contents: messages .filter((msg) => !(msg.role === "system" && isV1API)) @@ -303,15 +293,14 @@ class Gemini extends BaseLLM { } } } + return body; + } - const response = await this.fetch(apiURL, { - method: "POST", - body: JSON.stringify(body), - signal, - }); - + public async *processGeminiResponse( + stream: AsyncIterable, + ): AsyncGenerator { let buffer = ""; - for await (const chunk of streamResponse(response)) { + for await (const chunk of stream) { buffer += chunk; if (buffer.startsWith("[")) { buffer = buffer.slice(1); @@ -425,6 +414,35 @@ class Gemini extends BaseLLM { } } } + + private async *streamChatGemini( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const apiURL = new URL( + `models/${options.model}:streamGenerateContent?key=${this.apiKey}`, + this.apiBase, + ); + // This feels hacky to repeat code from above function but was the quickest + // way to ensure system message re-formatting isn't done if user has specified v1 + const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase + const isV1API = apiBase.includes("/v1/"); + + // Convert chat messages to contents + const body = this.prepareBody(messages, options, isV1API); + + const response = await this.fetch(apiURL, { + method: "POST", + body: JSON.stringify(body), + signal, + }); + for await (const message of this.processGeminiResponse( + streamResponse(response), + )) { + yield message; + } + } private async *streamChatBison( messages: ChatMessage[], signal: AbortSignal, diff --git a/core/llm/llms/HuggingFaceTEI.ts b/core/llm/llms/HuggingFaceTEI.ts index 206bbd5e2..52580c187 100644 --- a/core/llm/llms/HuggingFaceTEI.ts +++ b/core/llm/llms/HuggingFaceTEI.ts @@ -1,5 +1,4 @@ import { Chunk, LLMOptions } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; import { BaseLLM } from "../index.js"; class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { @@ -36,17 +35,15 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { } async doEmbedRequest(batch: string[]): Promise { - const resp = await withExponentialBackoff(() => - this.fetch(new URL("embed", this.apiBase), { - method: "POST", - body: JSON.stringify({ - inputs: batch, - }), - headers: { - "Content-Type": "application/json", - }, + const resp = await this.fetch(new URL("embed", this.apiBase), { + method: "POST", + body: JSON.stringify({ + inputs: batch, }), - ); + headers: { + "Content-Type": "application/json", + }, + }); if (!resp.ok) { const text = await resp.text(); const embedError = JSON.parse(text) as TEIEmbedErrorResponse; @@ -59,11 +56,10 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { } async doInfoRequest(): Promise { - const resp = await withExponentialBackoff(() => - this.fetch(new URL("info", this.apiBase), { - method: "GET", - }), - ); + // TODO - need to use custom fetch for this request? + const resp = await this.fetch(new URL("info", this.apiBase), { + method: "GET", + }); if (!resp.ok) { throw new Error(await resp.text()); } @@ -79,7 +75,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { headers["Authorization"] = `Bearer ${this.apiKey}`; } - const resp = await fetch(new URL("rerank", this.apiBase), { + const resp = await this.fetch(new URL("rerank", this.apiBase), { method: "POST", headers, body: JSON.stringify({ diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index ee822eb27..173692de3 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,12 +1,19 @@ import { JSONSchema7, JSONSchema7Object } from "json-schema"; -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + ChatMessageRole, + CompletionOptions, + LLMOptions, + ModelInstaller, +} from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; +import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; type OllamaChatMessage = { - role: "tool" | "user" | "assistant" | "system"; + role: ChatMessageRole; content: string; images?: string[] | null; tool_calls?: { @@ -82,10 +89,10 @@ type OllamaBaseResponse = { model: string; created_at: string; } & ( - | { + | { done: false; } - | { + | { done: true; done_reason: string; total_duration: number; // Time spent generating the response in nanoseconds @@ -96,7 +103,7 @@ type OllamaBaseResponse = { eval_duration: number; // Time spent generating the response in nanoseconds context: number[]; // An encoding of the conversation used in this response; can be sent in the next request to keep conversational memory } -); + ); type OllamaErrorResponse = { error: string; @@ -105,14 +112,14 @@ type OllamaErrorResponse = { type OllamaRawResponse = | OllamaErrorResponse | (OllamaBaseResponse & { - response: string; // the generated response - }); + response: string; // the generated response + }); type OllamaChatResponse = | OllamaErrorResponse | (OllamaBaseResponse & { - message: OllamaChatMessage; - }); + message: OllamaChatMessage; + }); interface OllamaTool { type: "function"; @@ -123,7 +130,7 @@ interface OllamaTool { }; } -class Ollama extends BaseLLM { +class Ollama extends BaseLLM implements ModelInstaller { static providerName = "ollama"; static defaultOptions: Partial = { apiBase: "http://localhost:11434/", @@ -142,7 +149,7 @@ class Ollama extends BaseLLM { const headers: Record = { "Content-Type": "application/json", }; - + if (this.apiKey) { headers.Authorization = `Bearer ${this.apiKey}`; } @@ -331,7 +338,7 @@ class Ollama extends BaseLLM { const headers: Record = { "Content-Type": "application/json", }; - + if (this.apiKey) { headers.Authorization = `Bearer ${this.apiKey}`; } @@ -358,6 +365,7 @@ class Ollama extends BaseLLM { if ("error" in j) { throw new Error(j.error); } + j.response ??= '' yield j.response; } catch (e) { throw new Error(`Error parsing Ollama response: ${e} ${chunk}`); @@ -396,7 +404,7 @@ class Ollama extends BaseLLM { const headers: Record = { "Content-Type": "application/json", }; - + if (this.apiKey) { headers.Authorization = `Bearer ${this.apiKey}`; } @@ -482,7 +490,7 @@ class Ollama extends BaseLLM { const headers: Record = { "Content-Type": "application/json", }; - + if (this.apiKey) { headers.Authorization = `Bearer ${this.apiKey}`; } @@ -523,7 +531,7 @@ class Ollama extends BaseLLM { const headers: Record = { "Content-Type": "application/json", }; - + if (this.apiKey) { headers.Authorization = `Bearer ${this.apiKey}`; } @@ -549,7 +557,7 @@ class Ollama extends BaseLLM { const headers: Record = { "Content-Type": "application/json", }; - + if (this.apiKey) { headers.Authorization = `Bearer ${this.apiKey}`; } @@ -559,7 +567,7 @@ class Ollama extends BaseLLM { model: this.model, input: chunks, }), - headers: headers + headers: headers, }); if (!resp.ok) { @@ -574,6 +582,45 @@ class Ollama extends BaseLLM { } return embedding; } + + public async installModel( + modelName: string, + signal: AbortSignal, + progressReporter?: (task: string, increment: number, total: number) => void, + ): Promise { + const modelInfo = await getRemoteModelInfo(modelName, signal); + if (!modelInfo) { + throw new Error(`'${modelName}' not found in the Ollama registry!`); + } + const response = await fetch(this.getEndpoint("api/pull"), { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ name: modelName }), + signal, + }); + + const reader = response.body?.getReader(); + //TODO: generate proper progress based on modelInfo size + while (true) { + const { done, value } = (await reader?.read()) || { + done: true, + value: undefined, + }; + if (done) { + break; + } + + const chunk = new TextDecoder().decode(value); + const lines = chunk.split("\n").filter(Boolean); + for (const line of lines) { + const data = JSON.parse(line); + progressReporter?.(data.status, data.completed, data.total); + } + } + } } export default Ollama; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 92f0aca08..139d033ab 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -97,6 +97,10 @@ class OpenAI extends BaseLLM { return !!model && (model.startsWith("o1") || model.startsWith("o3")); } + private isFireworksAiModel(model?: string): boolean { + return !!model && model.startsWith("accounts/fireworks/models"); + } + protected supportsPrediction(model: string): boolean { const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"]; return SUPPORTED_MODELS.some((m) => model.includes(m)); @@ -274,7 +278,13 @@ class OpenAI extends BaseLLM { body.max_completion_tokens = undefined; } - if (body.tools?.length && !body.model?.startsWith("o3")) { + if (body.tools?.length) { + if (this.isFireworksAiModel(body.model)) { + // fireworks.ai does not support parallel tool calls, but their api expects this to be true anyway otherwise they return an error. + // tooling works with them as a inference provider once this is set to true. + // https://docs.fireworks.ai/guides/function-calling#openai-compatibility + body.parallel_tool_calls = true; + } // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' diff --git a/core/llm/llms/Relace.ts b/core/llm/llms/Relace.ts new file mode 100644 index 000000000..f7a27c9e3 --- /dev/null +++ b/core/llm/llms/Relace.ts @@ -0,0 +1,12 @@ +import { LLMOptions } from "../.."; +import { LlmApiRequestType } from "../openaiTypeConverters"; + +import OpenAI from "./OpenAI"; + +export class Relace extends OpenAI { + static providerName = "relace"; + static defaultOptions: Partial | undefined = { + apiBase: "https://instantapply.endpoint.relace.run/v1/", + }; + protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"]; +} diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index 1f11d41ea..c9d14533c 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -1,9 +1,9 @@ import { - InvokeEndpointCommand, - InvokeEndpointWithResponseStreamCommand, - SageMakerRuntimeClient, + InvokeEndpointCommand, + InvokeEndpointWithResponseStreamCommand, + SageMakerRuntimeClient, } from "@aws-sdk/client-sagemaker-runtime"; -import { fromIni } from "@aws-sdk/credential-providers"; +import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; // @ts-ignore import jinja from "jinja-js"; @@ -130,14 +130,14 @@ class SageMaker extends BaseLLM { private async _getCredentials() { try { - return await fromIni({ + return await fromNodeProviderChain({ profile: this.profile, })(); } catch (e) { console.warn( `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, ); - return await fromIni()(); + return await fromNodeProviderChain()(); } } diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 4d52e5c43..1b75cb690 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -16,7 +16,7 @@ class VertexAI extends BaseLLM { declare geminiInstance: Gemini; static defaultOptions: Partial | undefined = { - maxEmbeddingBatchSize: 5, + maxEmbeddingBatchSize: 250, region: "us-central1", }; @@ -35,6 +35,13 @@ class VertexAI extends BaseLLM { } constructor(_options: LLMOptions) { + if (_options.region !== "us-central1") { + // Any region outside of us-central1 has a max batch size of 5. + _options.maxEmbeddingBatchSize = Math.min( + _options.maxEmbeddingBatchSize ?? 5, + 5, + ); + } super(_options); this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); this.vertexProvider = @@ -87,9 +94,11 @@ class VertexAI extends BaseLLM { ): AsyncGenerator { const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = renderChatMessage( - messages.filter((m) => m.role === "system")[0], - ); + const filteredSystemMessages : ChatMessage[] = messages.filter((m) => m.role === "system"); + let systemMessage: string = ""; + if(filteredSystemMessages.length > 0) { + systemMessage = renderChatMessage(filteredSystemMessages[0]); + } const apiURL = new URL( `publishers/anthropic/models/${options.model}:streamRawPredict`, this.apiBase, @@ -143,97 +152,16 @@ class VertexAI extends BaseLLM { `publishers/google/models/${options.model}:streamGenerateContent`, this.apiBase, ); - // This feels hacky to repeat code from above function but was the quickest - // way to ensure system message re-formatting isn't done if user has specified v1 - const isV1API = this.apiBase.includes("/v1/"); - const contents = messages - .map((msg) => { - if (msg.role === "system" && !isV1API) { - return null; // Don't include system message in contents - } - if (msg.role === "tool") { - return null; - } - - return { - role: msg.role === "assistant" ? "model" : "user", - parts: - typeof msg.content === "string" - ? [{ text: msg.content }] - : msg.content.map(this.geminiInstance.continuePartToGeminiPart), - }; - }) - .filter((c) => c !== null); - - const body = { - ...this.geminiInstance.convertArgs(options), - contents, - // if this.systemMessage is defined, reformat it for Gemini API - ...(this.systemMessage && - !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, - }), - }; + const body = this.geminiInstance.prepareBody(messages, options, false); const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), }); - - let buffer = ""; - for await (const chunk of streamResponse(response)) { - buffer += chunk; - if (buffer.startsWith("[")) { - buffer = buffer.slice(1); - } - if (buffer.endsWith("]")) { - buffer = buffer.slice(0, -1); - } - if (buffer.startsWith(",")) { - buffer = buffer.slice(1); - } - - const parts = buffer.split("\n,"); - - let foundIncomplete = false; - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - let data; - try { - data = JSON.parse(part); - } catch (e) { - foundIncomplete = true; - continue; // yo! - } - if (data.error) { - throw new Error(data.error.message); - } - // Check for existence of each level before accessing the final 'text' property - if (data?.candidates?.[0]?.content?.parts?.[0]?.text) { - // Incrementally stream the content to make it smoother - const content = data.candidates[0].content.parts[0].text; - const words = content.split(/(\s+)/); - const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1); - while (words.length > 0) { - const wordsToYield = Math.min(3, words.length); - yield { - role: "assistant", - content: words.splice(0, wordsToYield).join(""), - }; - await delay(delaySeconds); - } - } else { - // Handle the case where the expected data structure is not found - if (data?.candidates?.[0]?.finishReason !== "STOP") { - console.warn("Unexpected response format:", data); - } - } - } - if (foundIncomplete) { - buffer = parts[parts.length - 1]; - } else { - buffer = ""; - } + for await (const message of this.geminiInstance.processGeminiResponse( + streamResponse(response), + )) { + yield message; } } @@ -337,7 +265,9 @@ class VertexAI extends BaseLLM { }); for await (const chunk of streamSse(response)) { - yield chunk.choices[0].delta.content; + if (chunk.choices?.[0].delta) { + yield chunk.choices[0].delta.content; + } } } @@ -432,7 +362,9 @@ class VertexAI extends BaseLLM { } supportsFim(): boolean { - return ["code-gecko", "codestral-latest"].includes(this.model); + return ( + this.model.includes("code-gecko") || this.model.includes("codestral") + ); } protected async _embed(chunks: string[]): Promise { diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts index c9308d771..7273a67f6 100644 --- a/core/llm/llms/Vllm.ts +++ b/core/llm/llms/Vllm.ts @@ -6,7 +6,10 @@ class Vllm extends OpenAI { static providerName = "vllm"; constructor(options: LLMOptions) { super(options); - this._setupCompletionOptions(); + + if (options.model === "AUTODETECT") { + this._setupCompletionOptions(); + } } private _setupCompletionOptions() { @@ -22,7 +25,7 @@ class Vllm extends OpenAI { return; } const json = await response.json(); - const data = json.data; + const data = json.data[0]; this.model = data.id; this.contextLength = Number.parseInt(data.max_model_len); }); diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 27db04e17..fe08d8b1d 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -14,7 +14,7 @@ class Voyage extends OpenAI { return []; } const url = new URL("rerank", this.apiBase); - const resp = await fetch(url, { + const resp = await this.fetch(url, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 17c8b1d4b..561f4f2d9 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -1,4 +1,4 @@ -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { ChatMessage, Chunk, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -138,6 +138,26 @@ class WatsonX extends BaseLLM { }; } + protected async updateWatsonxToken() { + var now = new Date().getTime() / 1000; + if ( + watsonxToken === undefined || + now > watsonxToken.expiration || + watsonxToken.token === undefined + ) { + watsonxToken = await this.getBearerToken(); + } else { + console.log( + `Reusing token (expires in ${ + (watsonxToken.expiration - now) / 60 + } mins)`, + ); + } + if (watsonxToken.token === undefined) { + throw new Error("Something went wrong. Check your credentials, please."); + } + } + protected async _complete( prompt: string, signal: AbortSignal, @@ -174,23 +194,8 @@ class WatsonX extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - var now = new Date().getTime() / 1000; - if ( - watsonxToken === undefined || - now > watsonxToken.expiration || - watsonxToken.token === undefined - ) { - watsonxToken = await this.getBearerToken(); - } else { - console.log( - `Reusing token (expires in ${ - (watsonxToken.expiration - now) / 60 - } mins)`, - ); - } - if (watsonxToken.token === undefined) { - throw new Error("Something went wrong. Check your credentials, please."); - } + await this.updateWatsonxToken(); + const stopSequences = options.stop?.slice(0, 6) ?? (options.model?.includes("granite") ? ["Question:"] : []); @@ -267,20 +272,8 @@ class WatsonX extends BaseLLM { } protected async _embed(chunks: string[]): Promise { - var now = new Date().getTime() / 1000; - if ( - watsonxToken === undefined || - now > watsonxToken.expiration || - watsonxToken.token === undefined - ) { - watsonxToken = await this.getBearerToken(); - } else { - console.log( - `Reusing token (expires in ${ - (watsonxToken.expiration - now) / 60 - } mins)`, - ); - } + await this.updateWatsonxToken(); + const payload: any = { inputs: chunks, parameters: { @@ -318,6 +311,66 @@ class WatsonX extends BaseLLM { } return embeddings.map((e: any) => e.embedding); } + + + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + try { + await this.updateWatsonxToken(); + + const headers = { + "Content-Type": "application/json", + Authorization: `${ + watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, + }; + + const payload: any = { + inputs: chunks.map((chunk) => ({ text: chunk.content })), + query: query, + parameters: { + truncate_input_tokens: 500, + return_options: { + top_n: chunks.length + }, + }, + model_id: this.model, + project_id: this.projectId, + }; + + const resp = await this.fetch( + new URL( + `${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`, + ), + { + method: "POST", + headers: headers, + body: JSON.stringify(payload), + }, + ); + + if (!resp.ok) { + throw new Error(`Failed to rerank chunks: ${await resp.text()}`); + } + const data = await resp.json(); + const ranking = data.results; + + if (!ranking) { + throw new Error("Empty response received from Watsonx"); + } + + // Sort results by index to maintain original order + return ranking + .sort((a: any, b: any) => a.index - b.index) + .map((result: any) => result.score); + + } catch (error) { + console.error("Error in WatsonxReranker.rerank:", error); + throw error; + } + } } export default WatsonX; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 32cda4aec..e6a33a9a8 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -19,7 +19,6 @@ import Cohere from "./Cohere"; import DeepInfra from "./DeepInfra"; import Deepseek from "./Deepseek"; import Fireworks from "./Fireworks"; -import NCompass from "./NCompass"; import Flowise from "./Flowise"; import FreeTrial from "./FreeTrial"; import FunctionNetwork from "./FunctionNetwork"; @@ -35,11 +34,14 @@ import Mistral from "./Mistral"; import MockLLM from "./Mock"; import Moonshot from "./Moonshot"; import Msty from "./Msty"; +import NCompass from "./NCompass"; import Nebius from "./Nebius"; +import Novita from "./Novita"; import Nvidia from "./Nvidia"; import Ollama from "./Ollama"; import OpenAI from "./OpenAI"; import OpenRouter from "./OpenRouter"; +import { Relace } from "./Relace"; import Replicate from "./Replicate"; import SageMaker from "./SageMaker"; import SambaNova from "./SambaNova"; @@ -49,7 +51,6 @@ import ContinueProxy from "./stubs/ContinueProxy"; import TestLLM from "./Test"; import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; -import Novita from "./Novita"; import VertexAI from "./VertexAI"; import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; @@ -102,6 +103,7 @@ export const LLMClasses = [ xAI, SiliconFlow, Scaleway, + Relace, ]; export async function llmFromDescription( diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 00ec93dbc..01f62cd00 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -65,7 +65,7 @@ class ContinueProxy extends OpenAI { async rerank(query: string, chunks: Chunk[]): Promise { const url = new URL("rerank", this.apiBase); - const resp = await fetch(url, { + const resp = await this.fetch(url, { method: "POST", headers: { "Content-Type": "application/json", @@ -75,6 +75,7 @@ class ContinueProxy extends OpenAI { query, documents: chunks.map((chunk) => chunk.content), model: this.model, + ...this.extraBodyProperties(), }), }); const data: any = await resp.json(); diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts new file mode 100644 index 000000000..9b1ea87b3 --- /dev/null +++ b/core/llm/streamChat.ts @@ -0,0 +1,149 @@ +import { fetchwithRequestOptions } from "@continuedev/fetch"; +import { ChatMessage, IDE, PromptLog } from ".."; +import { ConfigHandler } from "../config/ConfigHandler"; +import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; +import { IMessenger, Message } from "../protocol/messenger"; +import { Telemetry } from "../util/posthog"; +import { TTS } from "../util/tts"; + +export async function* llmStreamChat( + configHandler: ConfigHandler, + abortedMessageIds: Set, + msg: Message, + ide: IDE, + messenger: IMessenger, +): AsyncGenerator { + const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + + // Stop TTS on new StreamChat + if (config.experimental?.readResponseTTS) { + void TTS.kill(); + } + + const { title, legacySlashCommandData, completionOptions, messages } = + msg.data; + + const model = await configHandler.llmFromTitle(title); + + // Log to return in case of error + const errorPromptLog = { + modelTitle: model.title ?? model.model, + completion: "", + prompt: "", + completionOptions: { + ...msg.data.completionOptions, + model: model.model, + }, + }; + + if (legacySlashCommandData) { + const { command, contextItems, historyIndex, input, selectedCode } = + legacySlashCommandData; + const slashCommand = config.slashCommands?.find( + (sc) => sc.name === command.name, + ); + if (!slashCommand) { + throw new Error(`Unknown slash command ${command.name}`); + } + void Telemetry.capture( + "useSlashCommand", + { + name: command.name, + }, + true, + ); + + const gen = slashCommand.run({ + input, + history: messages, + llm: model, + contextItems, + params: command.params, + ide, + addContextItem: (item) => { + void messenger.request("addContextItem", { + item, + historyIndex, + }); + }, + selectedCode, + config, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + completionOptions, + }); + const checkActiveInterval = setInterval(() => { + if (abortedMessageIds.has(msg.messageId)) { + abortedMessageIds.delete(msg.messageId); + clearInterval(checkActiveInterval); + } + }, 100); + try { + let next = await gen.next(); + while (!next.done) { + if (abortedMessageIds.has(msg.messageId)) { + abortedMessageIds.delete(msg.messageId); + next = await gen.return(errorPromptLog); + clearInterval(checkActiveInterval); + break; + } + if (next.value) { + yield { + role: "assistant", + content: next.value, + }; + } + next = await gen.next(); + } + if (!next.done) { + throw new Error("Will never happen"); + } + + return next.value; + } catch (e) { + throw e; + } finally { + clearInterval(checkActiveInterval); + } + } else { + const gen = model.streamChat( + messages, + new AbortController().signal, + completionOptions, + ); + let next = await gen.next(); + while (!next.done) { + if (abortedMessageIds.has(msg.messageId)) { + abortedMessageIds.delete(msg.messageId); + next = await gen.return(errorPromptLog); + break; + } + + const chunk = next.value; + + yield chunk; + next = await gen.next(); + } + if (config.experimental?.readResponseTTS && "completion" in next.value) { + void TTS.read(next.value?.completion); + } + + void Telemetry.capture( + "chat", + { + model: model.model, + provider: model.providerName, + }, + true, + ); + + if (!next.done) { + throw new Error("Will never happen"); + } + + return next.value; + } +} diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 1e23cbf3e..7f4975170 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -39,11 +39,28 @@ export const PROVIDER_TOOL_SUPPORT: Record< ) { return true; } + // firworks-ai https://docs.fireworks.ai/guides/function-calling + if (model.startsWith("accounts/fireworks/models/")) { + switch (model.substring(26)) { + case "llama-v3p1-405b-instruct": + case "llama-v3p1-70b-instruct": + case "qwen2p5-72b-instruct": + case "firefunction-v1": + case "firefunction-v2": + return true; + default: + return false; + } + } }, gemini: (model) => { // All gemini models support function calling return model.toLowerCase().includes("gemini"); }, + vertexai: (model) => { + // All gemini models except flash 2.0 lite support function calling + return model.toLowerCase().includes("gemini") && !model.toLowerCase().includes("lite");; + }, bedrock: (model) => { // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 if ( @@ -57,9 +74,18 @@ export const PROVIDER_TOOL_SUPPORT: Record< }, // https://ollama.com/search?c=tools ollama: (model) => { + let modelName = ""; + // Extract the model name after the last slash to support other registries + if(model.includes("/")) { + let parts = model.split('/'); + modelName = parts[parts.length - 1]; + } else { + modelName = model; + } + if ( ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( - (part) => model.toLowerCase().includes(part), + (part) => modelName.toLowerCase().includes(part), ) ) { return false; @@ -79,10 +105,11 @@ export const PROVIDER_TOOL_SUPPORT: Record< "nemotron", "llama3-groq", "granite3", + "granite-3", "aya-expanse", "firefunction-v2", "mistral", - ].some((part) => model.toLowerCase().startsWith(part)) + ].some((part) => modelName.toLowerCase().includes(part)) ) { return true; } diff --git a/core/package-lock.json b/core/package-lock.json index abe4271f8..dc398cd54 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -1,22 +1,22 @@ { "name": "@continuedev/core", - "version": "1.0.13", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/core", - "version": "1.0.13", + "version": "1.1.0", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.620.1", - "@aws-sdk/client-sagemaker-runtime": "^3.621.0", - "@aws-sdk/credential-providers": "^3.620.1", + "@aws-sdk/client-bedrock-runtime": "^3.758.0", + "@aws-sdk/client-sagemaker-runtime": "^3.758.0", + "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.63", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", - "@continuedev/openai-adapters": "^1.0.10", + "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -78,7 +78,7 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", - "@types/diff": "^5.2.2", + "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", @@ -288,631 +288,565 @@ } }, "node_modules/@aws-sdk/client-bedrock-runtime": { - "version": "3.706.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.706.0.tgz", - "integrity": "sha512-Wxzv0VgC1JFDFEnnmCCpKCXYpe+CfANY+ljY7HBSF2zJDasBHKpM4z28sN5nuffJgsBbkIDWltWbNnXKP/cONA==", + "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==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.699.0", - "@aws-sdk/client-sts": "3.699.0", - "@aws-sdk/core": "3.696.0", - "@aws-sdk/credential-provider-node": "3.699.0", - "@aws-sdk/middleware-host-header": "3.696.0", - "@aws-sdk/middleware-logger": "3.696.0", - "@aws-sdk/middleware-recursion-detection": "3.696.0", - "@aws-sdk/middleware-user-agent": "3.696.0", - "@aws-sdk/region-config-resolver": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@aws-sdk/util-endpoints": "3.696.0", - "@aws-sdk/util-user-agent-browser": "3.696.0", - "@aws-sdk/util-user-agent-node": "3.696.0", - "@smithy/config-resolver": "^3.0.12", - "@smithy/core": "^2.5.3", - "@smithy/eventstream-serde-browser": "^3.0.13", - "@smithy/eventstream-serde-config-resolver": "^3.0.10", - "@smithy/eventstream-serde-node": "^3.0.12", - "@smithy/fetch-http-handler": "^4.1.1", - "@smithy/hash-node": "^3.0.10", - "@smithy/invalid-dependency": "^3.0.10", - "@smithy/middleware-content-length": "^3.0.12", - "@smithy/middleware-endpoint": "^3.2.3", - "@smithy/middleware-retry": "^3.0.27", - "@smithy/middleware-serde": "^3.0.10", - "@smithy/middleware-stack": "^3.0.10", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/node-http-handler": "^3.3.1", - "@smithy/protocol-http": "^4.1.7", - "@smithy/smithy-client": "^3.4.4", - "@smithy/types": "^3.7.1", - "@smithy/url-parser": "^3.0.10", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.27", - "@smithy/util-defaults-mode-node": "^3.0.27", - "@smithy/util-endpoints": "^2.1.6", - "@smithy/util-middleware": "^3.0.10", - "@smithy/util-retry": "^3.0.10", - "@smithy/util-stream": "^3.3.1", - "@smithy/util-utf8": "^3.0.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", + "@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-utf8": "^4.0.0", "@types/uuid": "^9.0.1", "tslib": "^2.6.2", "uuid": "^9.0.1" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/client-cognito-identity": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.699.0.tgz", - "integrity": "sha512-9tFt+we6AIvj/f1+nrLHuCWcQmyfux5gcBSOy9d9+zIG56YxGEX7S9TaZnybogpVV8A0BYWml36WvIHS9QjIpA==", + "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==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.699.0", - "@aws-sdk/client-sts": "3.699.0", - "@aws-sdk/core": "3.696.0", - "@aws-sdk/credential-provider-node": "3.699.0", - "@aws-sdk/middleware-host-header": "3.696.0", - "@aws-sdk/middleware-logger": "3.696.0", - "@aws-sdk/middleware-recursion-detection": "3.696.0", - "@aws-sdk/middleware-user-agent": "3.696.0", - "@aws-sdk/region-config-resolver": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@aws-sdk/util-endpoints": "3.696.0", - "@aws-sdk/util-user-agent-browser": "3.696.0", - "@aws-sdk/util-user-agent-node": "3.696.0", - "@smithy/config-resolver": "^3.0.12", - "@smithy/core": "^2.5.3", - "@smithy/fetch-http-handler": "^4.1.1", - "@smithy/hash-node": "^3.0.10", - "@smithy/invalid-dependency": "^3.0.10", - "@smithy/middleware-content-length": "^3.0.12", - "@smithy/middleware-endpoint": "^3.2.3", - "@smithy/middleware-retry": "^3.0.27", - "@smithy/middleware-serde": "^3.0.10", - "@smithy/middleware-stack": "^3.0.10", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/node-http-handler": "^3.3.1", - "@smithy/protocol-http": "^4.1.7", - "@smithy/smithy-client": "^3.4.4", - "@smithy/types": "^3.7.1", - "@smithy/url-parser": "^3.0.10", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.27", - "@smithy/util-defaults-mode-node": "^3.0.27", - "@smithy/util-endpoints": "^2.1.6", - "@smithy/util-middleware": "^3.0.10", - "@smithy/util-retry": "^3.0.10", - "@smithy/util-utf8": "^3.0.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", + "@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-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/client-sagemaker-runtime": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sagemaker-runtime/-/client-sagemaker-runtime-3.699.0.tgz", - "integrity": "sha512-okWP5FcnOJlpIE+xoByhfh0N+93pXMNr6X5YXTiYnbChu7E86ST2CORkcmD/GDdvPpS8RV9qZCGI0QjS3pQlWA==", + "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==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.699.0", - "@aws-sdk/client-sts": "3.699.0", - "@aws-sdk/core": "3.696.0", - "@aws-sdk/credential-provider-node": "3.699.0", - "@aws-sdk/middleware-host-header": "3.696.0", - "@aws-sdk/middleware-logger": "3.696.0", - "@aws-sdk/middleware-recursion-detection": "3.696.0", - "@aws-sdk/middleware-user-agent": "3.696.0", - "@aws-sdk/region-config-resolver": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@aws-sdk/util-endpoints": "3.696.0", - "@aws-sdk/util-user-agent-browser": "3.696.0", - "@aws-sdk/util-user-agent-node": "3.696.0", - "@smithy/config-resolver": "^3.0.12", - "@smithy/core": "^2.5.3", - "@smithy/eventstream-serde-browser": "^3.0.13", - "@smithy/eventstream-serde-config-resolver": "^3.0.10", - "@smithy/eventstream-serde-node": "^3.0.12", - "@smithy/fetch-http-handler": "^4.1.1", - "@smithy/hash-node": "^3.0.10", - "@smithy/invalid-dependency": "^3.0.10", - "@smithy/middleware-content-length": "^3.0.12", - "@smithy/middleware-endpoint": "^3.2.3", - "@smithy/middleware-retry": "^3.0.27", - "@smithy/middleware-serde": "^3.0.10", - "@smithy/middleware-stack": "^3.0.10", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/node-http-handler": "^3.3.1", - "@smithy/protocol-http": "^4.1.7", - "@smithy/smithy-client": "^3.4.4", - "@smithy/types": "^3.7.1", - "@smithy/url-parser": "^3.0.10", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.27", - "@smithy/util-defaults-mode-node": "^3.0.27", - "@smithy/util-endpoints": "^2.1.6", - "@smithy/util-middleware": "^3.0.10", - "@smithy/util-retry": "^3.0.10", - "@smithy/util-stream": "^3.3.1", - "@smithy/util-utf8": "^3.0.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", + "@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-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/client-sso": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.696.0.tgz", - "integrity": "sha512-q5TTkd08JS0DOkHfUL853tuArf7NrPeqoS5UOvqJho8ibV9Ak/a/HO4kNvy9Nj3cib/toHYHsQIEtecUPSUUrQ==", + "version": "3.758.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.758.0.tgz", + "integrity": "sha512-BoGO6IIWrLyLxQG6txJw6RT2urmbtlwfggapNCrNPyYjlXpzTSJhBYjndg7TpDATFd0SXL0zm8y/tXsUXNkdYQ==", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.696.0", - "@aws-sdk/middleware-host-header": "3.696.0", - "@aws-sdk/middleware-logger": "3.696.0", - "@aws-sdk/middleware-recursion-detection": "3.696.0", - "@aws-sdk/middleware-user-agent": "3.696.0", - "@aws-sdk/region-config-resolver": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@aws-sdk/util-endpoints": "3.696.0", - "@aws-sdk/util-user-agent-browser": "3.696.0", - "@aws-sdk/util-user-agent-node": "3.696.0", - "@smithy/config-resolver": "^3.0.12", - "@smithy/core": "^2.5.3", - "@smithy/fetch-http-handler": "^4.1.1", - "@smithy/hash-node": "^3.0.10", - "@smithy/invalid-dependency": "^3.0.10", - "@smithy/middleware-content-length": "^3.0.12", - "@smithy/middleware-endpoint": "^3.2.3", - "@smithy/middleware-retry": "^3.0.27", - "@smithy/middleware-serde": "^3.0.10", - "@smithy/middleware-stack": "^3.0.10", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/node-http-handler": "^3.3.1", - "@smithy/protocol-http": "^4.1.7", - "@smithy/smithy-client": "^3.4.4", - "@smithy/types": "^3.7.1", - "@smithy/url-parser": "^3.0.10", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.27", - "@smithy/util-defaults-mode-node": "^3.0.27", - "@smithy/util-endpoints": "^2.1.6", - "@smithy/util-middleware": "^3.0.10", - "@smithy/util-retry": "^3.0.10", - "@smithy/util-utf8": "^3.0.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", + "@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-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-sdk/client-sso-oidc": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.699.0.tgz", - "integrity": "sha512-u8a1GorY5D1l+4FQAf4XBUC1T10/t7neuwT21r0ymrtMFSK2a9QqVHKMoLkvavAwyhJnARSBM9/UQC797PFOFw==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.696.0", - "@aws-sdk/credential-provider-node": "3.699.0", - "@aws-sdk/middleware-host-header": "3.696.0", - "@aws-sdk/middleware-logger": "3.696.0", - "@aws-sdk/middleware-recursion-detection": "3.696.0", - "@aws-sdk/middleware-user-agent": "3.696.0", - "@aws-sdk/region-config-resolver": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@aws-sdk/util-endpoints": "3.696.0", - "@aws-sdk/util-user-agent-browser": "3.696.0", - "@aws-sdk/util-user-agent-node": "3.696.0", - "@smithy/config-resolver": "^3.0.12", - "@smithy/core": "^2.5.3", - "@smithy/fetch-http-handler": "^4.1.1", - "@smithy/hash-node": "^3.0.10", - "@smithy/invalid-dependency": "^3.0.10", - "@smithy/middleware-content-length": "^3.0.12", - "@smithy/middleware-endpoint": "^3.2.3", - "@smithy/middleware-retry": "^3.0.27", - "@smithy/middleware-serde": "^3.0.10", - "@smithy/middleware-stack": "^3.0.10", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/node-http-handler": "^3.3.1", - "@smithy/protocol-http": "^4.1.7", - "@smithy/smithy-client": "^3.4.4", - "@smithy/types": "^3.7.1", - "@smithy/url-parser": "^3.0.10", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.27", - "@smithy/util-defaults-mode-node": "^3.0.27", - "@smithy/util-endpoints": "^2.1.6", - "@smithy/util-middleware": "^3.0.10", - "@smithy/util-retry": "^3.0.10", - "@smithy/util-utf8": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - }, - "peerDependencies": { - "@aws-sdk/client-sts": "^3.699.0" - } - }, - "node_modules/@aws-sdk/client-sts": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.699.0.tgz", - "integrity": "sha512-++lsn4x2YXsZPIzFVwv3fSUVM55ZT0WRFmPeNilYIhZClxHLmVAWKH4I55cY9ry60/aTKYjzOXkWwyBKGsGvQg==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/client-sso-oidc": "3.699.0", - "@aws-sdk/core": "3.696.0", - "@aws-sdk/credential-provider-node": "3.699.0", - "@aws-sdk/middleware-host-header": "3.696.0", - "@aws-sdk/middleware-logger": "3.696.0", - "@aws-sdk/middleware-recursion-detection": "3.696.0", - "@aws-sdk/middleware-user-agent": "3.696.0", - "@aws-sdk/region-config-resolver": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@aws-sdk/util-endpoints": "3.696.0", - "@aws-sdk/util-user-agent-browser": "3.696.0", - "@aws-sdk/util-user-agent-node": "3.696.0", - "@smithy/config-resolver": "^3.0.12", - "@smithy/core": "^2.5.3", - "@smithy/fetch-http-handler": "^4.1.1", - "@smithy/hash-node": "^3.0.10", - "@smithy/invalid-dependency": "^3.0.10", - "@smithy/middleware-content-length": "^3.0.12", - "@smithy/middleware-endpoint": "^3.2.3", - "@smithy/middleware-retry": "^3.0.27", - "@smithy/middleware-serde": "^3.0.10", - "@smithy/middleware-stack": "^3.0.10", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/node-http-handler": "^3.3.1", - "@smithy/protocol-http": "^4.1.7", - "@smithy/smithy-client": "^3.4.4", - "@smithy/types": "^3.7.1", - "@smithy/url-parser": "^3.0.10", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-body-length-node": "^3.0.0", - "@smithy/util-defaults-mode-browser": "^3.0.27", - "@smithy/util-defaults-mode-node": "^3.0.27", - "@smithy/util-endpoints": "^2.1.6", - "@smithy/util-middleware": "^3.0.10", - "@smithy/util-retry": "^3.0.10", - "@smithy/util-utf8": "^3.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/core": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.696.0.tgz", - "integrity": "sha512-3c9III1k03DgvRZWg8vhVmfIXPG6hAciN9MzQTzqGngzWAELZF/WONRTRQuDFixVtarQatmLHYVw/atGeA2Byw==", + "version": "3.758.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.758.0.tgz", + "integrity": "sha512-0RswbdR9jt/XKemaLNuxi2gGr4xGlHyGxkTdhSQzCyUe9A9OPCoLl3rIESRguQEech+oJnbHk/wuiwHqTuP9sg==", "dependencies": { - "@aws-sdk/types": "3.696.0", - "@smithy/core": "^2.5.3", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/property-provider": "^3.1.9", - "@smithy/protocol-http": "^4.1.7", - "@smithy/signature-v4": "^4.2.2", - "@smithy/smithy-client": "^3.4.4", - "@smithy/types": "^3.7.1", - "@smithy/util-middleware": "^3.0.10", + "@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", "fast-xml-parser": "4.4.1", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-cognito-identity": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.699.0.tgz", - "integrity": "sha512-iuaTnudaBfEET+o444sDwf71Awe6UiZfH+ipUPmswAi2jZDwdFF1nxMKDEKL8/LV5WpXsdKSfwgS0RQeupURew==", + "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==", "dependencies": { - "@aws-sdk/client-cognito-identity": "3.699.0", - "@aws-sdk/types": "3.696.0", - "@smithy/property-provider": "^3.1.9", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.696.0.tgz", - "integrity": "sha512-T9iMFnJL7YTlESLpVFT3fg1Lkb1lD+oiaIC8KMpepb01gDUBIpj9+Y+pA/cgRWW0yRxmkDXNazAE2qQTVFGJzA==", + "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==", "dependencies": { - "@aws-sdk/core": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@smithy/property-provider": "^3.1.9", - "@smithy/types": "^3.7.1", + "@aws-sdk/core": "3.758.0", + "@aws-sdk/types": "3.734.0", + "@smithy/property-provider": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.696.0.tgz", - "integrity": "sha512-GV6EbvPi2eq1+WgY/o2RFA3P7HGmnkIzCNmhwtALFlqMroLYWKE7PSeHw66Uh1dFQeVESn0/+hiUNhu1mB0emA==", + "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==", "dependencies": { - "@aws-sdk/core": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@smithy/fetch-http-handler": "^4.1.1", - "@smithy/node-http-handler": "^3.3.1", - "@smithy/property-provider": "^3.1.9", - "@smithy/protocol-http": "^4.1.7", - "@smithy/smithy-client": "^3.4.4", - "@smithy/types": "^3.7.1", - "@smithy/util-stream": "^3.3.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.699.0.tgz", - "integrity": "sha512-dXmCqjJnKmG37Q+nLjPVu22mNkrGHY8hYoOt3Jo9R2zr5MYV7s/NHsCHr+7E+BZ+tfZYLRPeB1wkpTeHiEcdRw==", + "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==", "dependencies": { - "@aws-sdk/core": "3.696.0", - "@aws-sdk/credential-provider-env": "3.696.0", - "@aws-sdk/credential-provider-http": "3.696.0", - "@aws-sdk/credential-provider-process": "3.696.0", - "@aws-sdk/credential-provider-sso": "3.699.0", - "@aws-sdk/credential-provider-web-identity": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@smithy/credential-provider-imds": "^3.2.6", - "@smithy/property-provider": "^3.1.9", - "@smithy/shared-ini-file-loader": "^3.1.10", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" - }, - "peerDependencies": { - "@aws-sdk/client-sts": "^3.699.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.699.0.tgz", - "integrity": "sha512-MmEmNDo1bBtTgRmdNfdQksXu4uXe66s0p1hi1YPrn1h59Q605eq/xiWbGL6/3KdkViH6eGUuABeV2ODld86ylg==", + "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==", "dependencies": { - "@aws-sdk/credential-provider-env": "3.696.0", - "@aws-sdk/credential-provider-http": "3.696.0", - "@aws-sdk/credential-provider-ini": "3.699.0", - "@aws-sdk/credential-provider-process": "3.696.0", - "@aws-sdk/credential-provider-sso": "3.699.0", - "@aws-sdk/credential-provider-web-identity": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@smithy/credential-provider-imds": "^3.2.6", - "@smithy/property-provider": "^3.1.9", - "@smithy/shared-ini-file-loader": "^3.1.10", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.696.0.tgz", - "integrity": "sha512-mL1RcFDe9sfmyU5K1nuFkO8UiJXXxLX4JO1gVaDIOvPqwStpUAwi3A1BoeZhWZZNQsiKI810RnYGo0E0WB/hUA==", + "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==", "dependencies": { - "@aws-sdk/core": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@smithy/property-provider": "^3.1.9", - "@smithy/shared-ini-file-loader": "^3.1.10", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.699.0.tgz", - "integrity": "sha512-Ekp2cZG4pl9D8+uKWm4qO1xcm8/MeiI8f+dnlZm8aQzizeC+aXYy9GyoclSf6daK8KfRPiRfM7ZHBBL5dAfdMA==", + "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==", "dependencies": { - "@aws-sdk/client-sso": "3.696.0", - "@aws-sdk/core": "3.696.0", - "@aws-sdk/token-providers": "3.699.0", - "@aws-sdk/types": "3.696.0", - "@smithy/property-provider": "^3.1.9", - "@smithy/shared-ini-file-loader": "^3.1.10", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.696.0.tgz", - "integrity": "sha512-XJ/CVlWChM0VCoc259vWguFUjJDn/QwDqHwbx+K9cg3v6yrqXfK5ai+p/6lx0nQpnk4JzPVeYYxWRpaTsGC9rg==", + "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==", "dependencies": { - "@aws-sdk/core": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@smithy/property-provider": "^3.1.9", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" - }, - "peerDependencies": { - "@aws-sdk/client-sts": "^3.696.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/credential-providers": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-providers/-/credential-providers-3.699.0.tgz", - "integrity": "sha512-jBjOntl9zN9Nvb0jmbMGRbiTzemDz64ij7W6BDavxBJRZpRoNeN0QCz6RolkCyXnyUJjo5mF2unY2wnv00A+LQ==", + "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==", "dependencies": { - "@aws-sdk/client-cognito-identity": "3.699.0", - "@aws-sdk/client-sso": "3.696.0", - "@aws-sdk/client-sts": "3.699.0", - "@aws-sdk/core": "3.696.0", - "@aws-sdk/credential-provider-cognito-identity": "3.699.0", - "@aws-sdk/credential-provider-env": "3.696.0", - "@aws-sdk/credential-provider-http": "3.696.0", - "@aws-sdk/credential-provider-ini": "3.699.0", - "@aws-sdk/credential-provider-node": "3.699.0", - "@aws-sdk/credential-provider-process": "3.696.0", - "@aws-sdk/credential-provider-sso": "3.699.0", - "@aws-sdk/credential-provider-web-identity": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@smithy/credential-provider-imds": "^3.2.6", - "@smithy/property-provider": "^3.1.9", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/middleware-host-header": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.696.0.tgz", - "integrity": "sha512-zELJp9Ta2zkX7ELggMN9qMCgekqZhFC5V2rOr4hJDEb/Tte7gpfKSObAnw/3AYiVqt36sjHKfdkoTsuwGdEoDg==", + "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==", "dependencies": { - "@aws-sdk/types": "3.696.0", - "@smithy/protocol-http": "^4.1.7", - "@smithy/types": "^3.7.1", + "@aws-sdk/types": "3.734.0", + "@smithy/protocol-http": "^5.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/middleware-logger": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.696.0.tgz", - "integrity": "sha512-KhkHt+8AjCxcR/5Zp3++YPJPpFQzxpr+jmONiT/Jw2yqnSngZ0Yspm5wGoRx2hS1HJbyZNuaOWEGuJoxLeBKfA==", + "version": "3.734.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.734.0.tgz", + "integrity": "sha512-mUMFITpJUW3LcKvFok176eI5zXAUomVtahb9IQBwLzkqFYOrMJvWAvoV4yuxrJ8TlQBG8gyEnkb9SnhZvjg67w==", "dependencies": { - "@aws-sdk/types": "3.696.0", - "@smithy/types": "^3.7.1", + "@aws-sdk/types": "3.734.0", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/middleware-recursion-detection": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.696.0.tgz", - "integrity": "sha512-si/maV3Z0hH7qa99f9ru2xpS5HlfSVcasRlNUXKSDm611i7jFMWwGNLUOXFAOLhXotPX5G3Z6BLwL34oDeBMug==", + "version": "3.734.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.734.0.tgz", + "integrity": "sha512-CUat2d9ITsFc2XsmeiRQO96iWpxSKYFjxvj27Hc7vo87YUHRnfMfnc8jw1EpxEwMcvBD7LsRa6vDNky6AjcrFA==", "dependencies": { - "@aws-sdk/types": "3.696.0", - "@smithy/protocol-http": "^4.1.7", - "@smithy/types": "^3.7.1", + "@aws-sdk/types": "3.734.0", + "@smithy/protocol-http": "^5.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.696.0.tgz", - "integrity": "sha512-Lvyj8CTyxrHI6GHd2YVZKIRI5Fmnugt3cpJo0VrKKEgK5zMySwEZ1n4dqPK6czYRWKd5+WnYHYAuU+Wdk6Jsjw==", + "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==", "dependencies": { - "@aws-sdk/core": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@aws-sdk/util-endpoints": "3.696.0", - "@smithy/core": "^2.5.3", - "@smithy/protocol-http": "^4.1.7", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" + } + }, + "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==", + "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", + "@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-utf8": "^4.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/region-config-resolver": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.696.0.tgz", - "integrity": "sha512-7EuH142lBXjI8yH6dVS/CZeiK/WZsmb/8zP6bQbVYpMrppSTgB3MzZZdxVZGzL5r8zPQOU10wLC4kIMy0qdBVQ==", + "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==", "dependencies": { - "@aws-sdk/types": "3.696.0", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/types": "^3.7.1", - "@smithy/util-config-provider": "^3.0.0", - "@smithy/util-middleware": "^3.0.10", + "@aws-sdk/types": "3.734.0", + "@smithy/node-config-provider": "^4.0.1", + "@smithy/types": "^4.1.0", + "@smithy/util-config-provider": "^4.0.0", + "@smithy/util-middleware": "^4.0.1", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/token-providers": { - "version": "3.699.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.699.0.tgz", - "integrity": "sha512-kuiEW9DWs7fNos/SM+y58HCPhcIzm1nEZLhe2/7/6+TvAYLuEWURYsbK48gzsxXlaJ2k/jGY3nIsA7RptbMOwA==", + "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==", "dependencies": { - "@aws-sdk/types": "3.696.0", - "@smithy/property-provider": "^3.1.9", - "@smithy/shared-ini-file-loader": "^3.1.10", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" - }, - "peerDependencies": { - "@aws-sdk/client-sso-oidc": "^3.699.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/types": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.696.0.tgz", - "integrity": "sha512-9rTvUJIAj5d3//U5FDPWGJ1nFJLuWb30vugGOrWk7aNZ6y9tuA3PI7Cc9dP8WEXKVyK1vuuk8rSFP2iqXnlgrw==", + "version": "3.734.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.734.0.tgz", + "integrity": "sha512-o11tSPTT70nAkGV1fN9wm/hAIiLPyWX6SuGf+9JyTp7S/rC2cFWhR26MvA69nplcjNaXVzB0f+QFrLXXjOqCrg==", "dependencies": { - "@smithy/types": "^3.7.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/util-endpoints": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.696.0.tgz", - "integrity": "sha512-T5s0IlBVX+gkb9g/I6CLt4yAZVzMSiGnbUqWihWsHvQR1WOoIcndQy/Oz/IJXT9T2ipoy7a80gzV6a5mglrioA==", + "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==", "dependencies": { - "@aws-sdk/types": "3.696.0", - "@smithy/types": "^3.7.1", - "@smithy/util-endpoints": "^2.1.6", + "@aws-sdk/types": "3.734.0", + "@smithy/types": "^4.1.0", + "@smithy/util-endpoints": "^3.0.1", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@aws-sdk/util-locate-window": { @@ -927,29 +861,29 @@ } }, "node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.696.0.tgz", - "integrity": "sha512-Z5rVNDdmPOe6ELoM5AhF/ja5tSjbe6ctSctDPb0JdDf4dT0v2MfwhJKzXju2RzX8Es/77Glh7MlaXLE0kCB9+Q==", + "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==", "dependencies": { - "@aws-sdk/types": "3.696.0", - "@smithy/types": "^3.7.1", + "@aws-sdk/types": "3.734.0", + "@smithy/types": "^4.1.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.696.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.696.0.tgz", - "integrity": "sha512-KhKqcfyXIB0SCCt+qsu4eJjsfiOrNzK5dCV7RAW2YIpp+msxGUUX0NdRE9rkzjiv+3EMktgJm3eEIS+yxtlVdQ==", + "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==", "dependencies": { - "@aws-sdk/middleware-user-agent": "3.696.0", - "@aws-sdk/types": "3.696.0", - "@smithy/node-config-provider": "^3.1.11", - "@smithy/types": "^3.7.1", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" }, "peerDependencies": { "aws-crt": ">=1.0.0" @@ -1226,6 +1160,7 @@ "version": "1.0.0-beta.13", "resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.13.tgz", "integrity": "sha512-oHE5ScnPTXALmyEBgqokZlYVT7F76EfrKjMWF+YcFJdUxk9Adhvht2iL5v+QpmlAIMdkih1q8DkTs/tApDjBpw==", + "deprecated": "The Azure OpenAI client library for JavaScript beta has been retired. Please migrate to the stable OpenAI SDK for JavaScript using the migration guide: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/openai/openai/MIGRATION.md.", "dependencies": { "@azure-rest/core-client": "^1.1.7", "@azure/core-auth": "^1.4.0", @@ -3038,9 +2973,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.52", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.52.tgz", - "integrity": "sha512-x0m4bcQpjHrrv95cq5tsen4Hb6yKCVGn+NeojyzNQYnRD0If/On+ATgX78uXtQtZxsdO4ip73HHCyQlA0O3ZyQ==", + "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==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -3065,16 +3000,18 @@ "integrity": "sha512-MyYmP4tbTzOnlT6hItC9tFkVZpYkaAg45AUXqdXzEfZhz8ZWpaiN8jZ789KLVmq+NKqhMUbKAHIZUUY1d39eRw==" }, "node_modules/@continuedev/openai-adapters": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.10.tgz", - "integrity": "sha512-hTiCxlXsek/jpVbtHDQCe4JnCmJ+jbye9ionXCDmg9oAKKEymW1UVVrX08xcdCkfKnxAP2ESgqFSMok314q+fg==", + "version": "1.0.18", + "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.18.tgz", + "integrity": "sha512-VkYNhW+XKVXnn5FTLCGoJkcejkDWSCUvvIS6WnYusmS1+W5MJBFZQ5q6O/WA17U0UF9Xou81RWfCltYs4fXnyQ==", "dependencies": { "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", + "@continuedev/config-yaml": "^1.0.51", "@continuedev/fetch": "^1.0.3", + "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", - "zod": "^3.23.8" + "zod": "^3.24.2" } }, "node_modules/@esbuild/android-arm": { @@ -4590,579 +4527,594 @@ } }, "node_modules/@smithy/abort-controller": { - "version": "3.1.9", - "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-3.1.9.tgz", - "integrity": "sha512-yiW0WI30zj8ZKoSYNx90no7ugVn3khlyH/z5W8qtKBtVE6awRALbhSG+2SAHA1r6bO/6M9utxYKVZ3PCJ1rWxw==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.0.1.tgz", + "integrity": "sha512-fiUIYgIgRjMWznk6iLJz35K2YxSLHzLBA/RC6lBrKfQ8fHbPfvk7Pk9UvpKoHgJjI18MnbPuEju53zcVy6KF1g==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/config-resolver": { - "version": "3.0.13", - "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-3.0.13.tgz", - "integrity": "sha512-Gr/qwzyPaTL1tZcq8WQyHhTZREER5R1Wytmz4WnVGL4onA3dNk6Btll55c8Vr58pLdvWZmtG8oZxJTw3t3q7Jg==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.0.1.tgz", + "integrity": "sha512-Igfg8lKu3dRVkTSEm98QpZUvKEOa71jDX4vKRcvJVyRc3UgN3j7vFMf0s7xLQhYmKa8kyJGQgUJDOV5V3neVlQ==", "dependencies": { - "@smithy/node-config-provider": "^3.1.12", - "@smithy/types": "^3.7.2", - "@smithy/util-config-provider": "^3.0.0", - "@smithy/util-middleware": "^3.0.11", + "@smithy/node-config-provider": "^4.0.1", + "@smithy/types": "^4.1.0", + "@smithy/util-config-provider": "^4.0.0", + "@smithy/util-middleware": "^4.0.1", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/core": { - "version": "2.5.5", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-2.5.5.tgz", - "integrity": "sha512-G8G/sDDhXA7o0bOvkc7bgai6POuSld/+XhNnWAbpQTpLv2OZPvyqQ58tLPPlz0bSNsXktldDDREIv1LczFeNEw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.1.5.tgz", + "integrity": "sha512-HLclGWPkCsekQgsyzxLhCQLa8THWXtB5PxyYN+2O6nkyLt550KQKTlbV2D1/j5dNIQapAZM1+qFnpBFxZQkgCA==", "dependencies": { - "@smithy/middleware-serde": "^3.0.11", - "@smithy/protocol-http": "^4.1.8", - "@smithy/types": "^3.7.2", - "@smithy/util-body-length-browser": "^3.0.0", - "@smithy/util-middleware": "^3.0.11", - "@smithy/util-stream": "^3.3.2", - "@smithy/util-utf8": "^3.0.0", + "@smithy/middleware-serde": "^4.0.2", + "@smithy/protocol-http": "^5.0.1", + "@smithy/types": "^4.1.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-middleware": "^4.0.1", + "@smithy/util-stream": "^4.1.2", + "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/credential-provider-imds": { - "version": "3.2.8", - "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-3.2.8.tgz", - "integrity": "sha512-ZCY2yD0BY+K9iMXkkbnjo+08T2h8/34oHd0Jmh6BZUSZwaaGlGCyBT/3wnS7u7Xl33/EEfN4B6nQr3Gx5bYxgw==", + "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==", "dependencies": { - "@smithy/node-config-provider": "^3.1.12", - "@smithy/property-provider": "^3.1.11", - "@smithy/types": "^3.7.2", - "@smithy/url-parser": "^3.0.11", + "@smithy/node-config-provider": "^4.0.1", + "@smithy/property-provider": "^4.0.1", + "@smithy/types": "^4.1.0", + "@smithy/url-parser": "^4.0.1", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/eventstream-codec": { - "version": "3.1.10", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-3.1.10.tgz", - "integrity": "sha512-323B8YckSbUH0nMIpXn7HZsAVKHYHFUODa8gG9cHo0ySvA1fr5iWaNT+iIL0UCqUzG6QPHA3BSsBtRQou4mMqQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-4.0.1.tgz", + "integrity": "sha512-Q2bCAAR6zXNVtJgifsU16ZjKGqdw/DyecKNgIgi7dlqw04fqDu0mnq+JmGphqheypVc64CYq3azSuCpAdFk2+A==", "dependencies": { "@aws-crypto/crc32": "5.2.0", - "@smithy/types": "^3.7.2", - "@smithy/util-hex-encoding": "^3.0.0", + "@smithy/types": "^4.1.0", + "@smithy/util-hex-encoding": "^4.0.0", "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" } }, "node_modules/@smithy/eventstream-serde-browser": { - "version": "3.0.14", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-3.0.14.tgz", - "integrity": "sha512-kbrt0vjOIihW3V7Cqj1SXQvAI5BR8SnyQYsandva0AOR307cXAc+IhPngxIPslxTLfxwDpNu0HzCAq6g42kCPg==", + "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==", "dependencies": { - "@smithy/eventstream-serde-universal": "^3.0.13", - "@smithy/types": "^3.7.2", + "@smithy/eventstream-serde-universal": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/eventstream-serde-config-resolver": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-3.0.11.tgz", - "integrity": "sha512-P2pnEp4n75O+QHjyO7cbw/vsw5l93K/8EWyjNCAAybYwUmj3M+hjSQZ9P5TVdUgEG08ueMAP5R4FkuSkElZ5tQ==", + "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==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/eventstream-serde-node": { - "version": "3.0.13", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-3.0.13.tgz", - "integrity": "sha512-zqy/9iwbj8Wysmvi7Lq7XFLeDgjRpTbCfwBhJa8WbrylTAHiAu6oQTwdY7iu2lxigbc9YYr9vPv5SzYny5tCXQ==", + "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==", "dependencies": { - "@smithy/eventstream-serde-universal": "^3.0.13", - "@smithy/types": "^3.7.2", + "@smithy/eventstream-serde-universal": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/eventstream-serde-universal": { - "version": "3.0.13", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-3.0.13.tgz", - "integrity": "sha512-L1Ib66+gg9uTnqp/18Gz4MDpJPKRE44geOjOQ2SVc0eiaO5l255ADziATZgjQjqumC7yPtp1XnjHlF1srcwjKw==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-4.0.1.tgz", + "integrity": "sha512-Z94uZp0tGJuxds3iEAZBqGU2QiaBHP4YytLUjwZWx+oUeohCsLyUm33yp4MMBmhkuPqSbQCXq5hDet6JGUgHWA==", "dependencies": { - "@smithy/eventstream-codec": "^3.1.10", - "@smithy/types": "^3.7.2", + "@smithy/eventstream-codec": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/fetch-http-handler": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-4.1.2.tgz", - "integrity": "sha512-R7rU7Ae3ItU4rC0c5mB2sP5mJNbCfoDc8I5XlYjIZnquyUwec7fEo78F6DA3SmgJgkU1qTMcZJuGblxZsl10ZA==", + "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==", "dependencies": { - "@smithy/protocol-http": "^4.1.8", - "@smithy/querystring-builder": "^3.0.11", - "@smithy/types": "^3.7.2", - "@smithy/util-base64": "^3.0.0", + "@smithy/protocol-http": "^5.0.1", + "@smithy/querystring-builder": "^4.0.1", + "@smithy/types": "^4.1.0", + "@smithy/util-base64": "^4.0.0", "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" } }, "node_modules/@smithy/hash-node": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-3.0.11.tgz", - "integrity": "sha512-emP23rwYyZhQBvklqTtwetkQlqbNYirDiEEwXl2v0GYWMnCzxst7ZaRAnWuy28njp5kAH54lvkdG37MblZzaHA==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.0.1.tgz", + "integrity": "sha512-TJ6oZS+3r2Xu4emVse1YPB3Dq3d8RkZDKcPr71Nj/lJsdAP1c7oFzYqEn1IBc915TsgLl2xIJNuxCz+gLbLE0w==", "dependencies": { - "@smithy/types": "^3.7.2", - "@smithy/util-buffer-from": "^3.0.0", - "@smithy/util-utf8": "^3.0.0", + "@smithy/types": "^4.1.0", + "@smithy/util-buffer-from": "^4.0.0", + "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/invalid-dependency": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-3.0.11.tgz", - "integrity": "sha512-NuQmVPEJjUX6c+UELyVz8kUx8Q539EDeNwbRyu4IIF8MeV7hUtq1FB3SHVyki2u++5XLMFqngeMKk7ccspnNyQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.0.1.tgz", + "integrity": "sha512-gdudFPf4QRQ5pzj7HEnu6FhKRi61BfH/Gk5Yf6O0KiSbr1LlVhgjThcvjdu658VE6Nve8vaIWB8/fodmS1rBPQ==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" } }, "node_modules/@smithy/is-array-buffer": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-3.0.0.tgz", - "integrity": "sha512-+Fsu6Q6C4RSJiy81Y8eApjEB5gVtM+oFKTffg+jSuwtvomJJrhUJBu2zS8wjXSgH/g1MKEWrzyChTBe6clb5FQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.0.0.tgz", + "integrity": "sha512-saYhF8ZZNoJDTvJBEWgeBccCg+yvp1CX+ed12yORU3NilJScfc6gfch2oVb4QgxZrGUx3/ZJlb+c/dJbyupxlw==", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/middleware-content-length": { - "version": "3.0.13", - "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-3.0.13.tgz", - "integrity": "sha512-zfMhzojhFpIX3P5ug7jxTjfUcIPcGjcQYzB9t+rv0g1TX7B0QdwONW+ATouaLoD7h7LOw/ZlXfkq4xJ/g2TrIw==", + "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==", "dependencies": { - "@smithy/protocol-http": "^4.1.8", - "@smithy/types": "^3.7.2", + "@smithy/protocol-http": "^5.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/middleware-endpoint": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-3.2.5.tgz", - "integrity": "sha512-VhJNs/s/lyx4weiZdXSloBgoLoS8osV0dKIain8nGmx7of3QFKu5BSdEuk1z/U8x9iwes1i+XCiNusEvuK1ijg==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.0.6.tgz", + "integrity": "sha512-ftpmkTHIFqgaFugcjzLZv3kzPEFsBFSnq1JsIkr2mwFzCraZVhQk2gqN51OOeRxqhbPTkRFj39Qd2V91E/mQxg==", "dependencies": { - "@smithy/core": "^2.5.5", - "@smithy/middleware-serde": "^3.0.11", - "@smithy/node-config-provider": "^3.1.12", - "@smithy/shared-ini-file-loader": "^3.1.12", - "@smithy/types": "^3.7.2", - "@smithy/url-parser": "^3.0.11", - "@smithy/util-middleware": "^3.0.11", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/middleware-retry": { - "version": "3.0.30", - "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-3.0.30.tgz", - "integrity": "sha512-6323RL2BvAR3VQpTjHpa52kH/iSHyxd/G9ohb2MkBk2Ucu+oMtRXT8yi7KTSIS9nb58aupG6nO0OlXnQOAcvmQ==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.0.7.tgz", + "integrity": "sha512-58j9XbUPLkqAcV1kHzVX/kAR16GT+j7DUZJqwzsxh1jtz7G82caZiGyyFgUvogVfNTg3TeAOIJepGc8TXF4AVQ==", "dependencies": { - "@smithy/node-config-provider": "^3.1.12", - "@smithy/protocol-http": "^4.1.8", - "@smithy/service-error-classification": "^3.0.11", - "@smithy/smithy-client": "^3.5.0", - "@smithy/types": "^3.7.2", - "@smithy/util-middleware": "^3.0.11", - "@smithy/util-retry": "^3.0.11", + "@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", "tslib": "^2.6.2", "uuid": "^9.0.1" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/middleware-serde": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-3.0.11.tgz", - "integrity": "sha512-KzPAeySp/fOoQA82TpnwItvX8BBURecpx6ZMu75EZDkAcnPtO6vf7q4aH5QHs/F1s3/snQaSFbbUMcFFZ086Mw==", + "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==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/middleware-stack": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-3.0.11.tgz", - "integrity": "sha512-1HGo9a6/ikgOMrTrWL/WiN9N8GSVYpuRQO5kjstAq4CvV59bjqnh7TbdXGQ4vxLD3xlSjfBjq5t1SOELePsLnA==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.0.1.tgz", + "integrity": "sha512-dHwDmrtR/ln8UTHpaIavRSzeIk5+YZTBtLnKwDW3G2t6nAupCiQUvNzNoHBpik63fwUaJPtlnMzXbQrNFWssIA==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/node-config-provider": { - "version": "3.1.12", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-3.1.12.tgz", - "integrity": "sha512-O9LVEu5J/u/FuNlZs+L7Ikn3lz7VB9hb0GtPT9MQeiBmtK8RSY3ULmsZgXhe6VAlgTw0YO+paQx4p8xdbs43vQ==", + "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==", "dependencies": { - "@smithy/property-provider": "^3.1.11", - "@smithy/shared-ini-file-loader": "^3.1.12", - "@smithy/types": "^3.7.2", + "@smithy/property-provider": "^4.0.1", + "@smithy/shared-ini-file-loader": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/node-http-handler": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-3.3.2.tgz", - "integrity": "sha512-t4ng1DAd527vlxvOfKFYEe6/QFBcsj7WpNlWTyjorwXXcKw3XlltBGbyHfSJ24QT84nF+agDha9tNYpzmSRZPA==", + "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==", "dependencies": { - "@smithy/abort-controller": "^3.1.9", - "@smithy/protocol-http": "^4.1.8", - "@smithy/querystring-builder": "^3.0.11", - "@smithy/types": "^3.7.2", + "@smithy/abort-controller": "^4.0.1", + "@smithy/protocol-http": "^5.0.1", + "@smithy/querystring-builder": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/property-provider": { - "version": "3.1.11", - "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-3.1.11.tgz", - "integrity": "sha512-I/+TMc4XTQ3QAjXfOcUWbSS073oOEAxgx4aZy8jHaf8JQnRkq2SZWw8+PfDtBvLUjcGMdxl+YwtzWe6i5uhL/A==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.0.1.tgz", + "integrity": "sha512-o+VRiwC2cgmk/WFV0jaETGOtX16VNPp2bSQEzu0whbReqE1BMqsP2ami2Vi3cbGVdKu1kq9gQkDAGKbt0WOHAQ==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/protocol-http": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-4.1.8.tgz", - "integrity": "sha512-hmgIAVyxw1LySOwkgMIUN0kjN8TG9Nc85LJeEmEE/cNEe2rkHDUWhnJf2gxcSRFLWsyqWsrZGw40ROjUogg+Iw==", + "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==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/querystring-builder": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-3.0.11.tgz", - "integrity": "sha512-u+5HV/9uJaeLj5XTb6+IEF/dokWWkEqJ0XiaRRogyREmKGUgZnNecLucADLdauWFKUNbQfulHFEZEdjwEBjXRg==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.0.1.tgz", + "integrity": "sha512-wU87iWZoCbcqrwszsOewEIuq+SU2mSoBE2CcsLwE0I19m0B2gOJr1MVjxWcDQYOzHbR1xCk7AcOBbGFUYOKvdg==", "dependencies": { - "@smithy/types": "^3.7.2", - "@smithy/util-uri-escape": "^3.0.0", + "@smithy/types": "^4.1.0", + "@smithy/util-uri-escape": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/querystring-parser": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-3.0.11.tgz", - "integrity": "sha512-Je3kFvCsFMnso1ilPwA7GtlbPaTixa3WwC+K21kmMZHsBEOZYQaqxcMqeFFoU7/slFjKDIpiiPydvdJm8Q/MCw==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.0.1.tgz", + "integrity": "sha512-Ma2XC7VS9aV77+clSFylVUnPZRindhB7BbmYiNOdr+CHt/kZNJoPP0cd3QxCnCFyPXC4eybmyE98phEHkqZ5Jw==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/service-error-classification": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-3.0.11.tgz", - "integrity": "sha512-QnYDPkyewrJzCyaeI2Rmp7pDwbUETe+hU8ADkXmgNusO1bgHBH7ovXJiYmba8t0fNfJx75fE8dlM6SEmZxheog==", + "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==", "dependencies": { - "@smithy/types": "^3.7.2" + "@smithy/types": "^4.1.0" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/shared-ini-file-loader": { - "version": "3.1.12", - "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-3.1.12.tgz", - "integrity": "sha512-1xKSGI+U9KKdbG2qDvIR9dGrw3CNx+baqJfyr0igKEpjbHL5stsqAesYBzHChYHlelWtb87VnLWlhvfCz13H8Q==", + "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==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/signature-v4": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-4.2.4.tgz", - "integrity": "sha512-5JWeMQYg81TgU4cG+OexAWdvDTs5JDdbEZx+Qr1iPbvo91QFGzjy0IkXAKaXUHqmKUJgSHK0ZxnCkgZpzkeNTA==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.0.1.tgz", + "integrity": "sha512-nCe6fQ+ppm1bQuw5iKoeJ0MJfz2os7Ic3GBjOkLOPtavbD1ONoyE3ygjBfz2ythFWm4YnRm6OxW+8p/m9uCoIA==", "dependencies": { - "@smithy/is-array-buffer": "^3.0.0", - "@smithy/protocol-http": "^4.1.8", - "@smithy/types": "^3.7.2", - "@smithy/util-hex-encoding": "^3.0.0", - "@smithy/util-middleware": "^3.0.11", - "@smithy/util-uri-escape": "^3.0.0", - "@smithy/util-utf8": "^3.0.0", + "@smithy/is-array-buffer": "^4.0.0", + "@smithy/protocol-http": "^5.0.1", + "@smithy/types": "^4.1.0", + "@smithy/util-hex-encoding": "^4.0.0", + "@smithy/util-middleware": "^4.0.1", + "@smithy/util-uri-escape": "^4.0.0", + "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/smithy-client": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-3.5.0.tgz", - "integrity": "sha512-Y8FeOa7gbDfCWf7njrkoRATPa5eNLUEjlJS5z5rXatYuGkCb80LbHcu8AQR8qgAZZaNHCLyo2N+pxPsV7l+ivg==", + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.1.6.tgz", + "integrity": "sha512-UYDolNg6h2O0L+cJjtgSyKKvEKCOa/8FHYJnBobyeoeWDmNpXjwOAtw16ezyeu1ETuuLEOZbrynK0ZY1Lx9Jbw==", "dependencies": { - "@smithy/core": "^2.5.5", - "@smithy/middleware-endpoint": "^3.2.5", - "@smithy/middleware-stack": "^3.0.11", - "@smithy/protocol-http": "^4.1.8", - "@smithy/types": "^3.7.2", - "@smithy/util-stream": "^3.3.2", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/types": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-3.7.2.tgz", - "integrity": "sha512-bNwBYYmN8Eh9RyjS1p2gW6MIhSO2rl7X9QeLM8iTdcGRP+eDiIWDt66c9IysCc22gefKszZv+ubV9qZc7hdESg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.1.0.tgz", + "integrity": "sha512-enhjdwp4D7CXmwLtD6zbcDMbo6/T6WtuuKCY49Xxc6OMOmUWlBEBDREsxxgV2LIdeQPW756+f97GzcgAwp3iLw==", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/url-parser": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-3.0.11.tgz", - "integrity": "sha512-TmlqXkSk8ZPhfc+SQutjmFr5FjC0av3GZP4B/10caK1SbRwe/v+Wzu/R6xEKxoNqL+8nY18s1byiy6HqPG37Aw==", + "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==", "dependencies": { - "@smithy/querystring-parser": "^3.0.11", - "@smithy/types": "^3.7.2", + "@smithy/querystring-parser": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" } }, "node_modules/@smithy/util-base64": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-3.0.0.tgz", - "integrity": "sha512-Kxvoh5Qtt0CDsfajiZOCpJxgtPHXOKwmM+Zy4waD43UoEMA+qPxxa98aE/7ZhdnBFZFXMOiBR5xbcaMhLtznQQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.0.0.tgz", + "integrity": "sha512-CvHfCmO2mchox9kjrtzoHkWHxjHZzaFojLc8quxXY7WAAMAg43nuxwv95tATVgQFNDwd4M9S1qFzj40Ul41Kmg==", "dependencies": { - "@smithy/util-buffer-from": "^3.0.0", - "@smithy/util-utf8": "^3.0.0", + "@smithy/util-buffer-from": "^4.0.0", + "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-body-length-browser": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-3.0.0.tgz", - "integrity": "sha512-cbjJs2A1mLYmqmyVl80uoLTJhAcfzMOyPgjwAYusWKMdLeNtzmMz9YxNl3/jRLoxSS3wkqkf0jwNdtXWtyEBaQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.0.0.tgz", + "integrity": "sha512-sNi3DL0/k64/LO3A256M+m3CDdG6V7WKWHdAiBBMUN8S3hK3aMPhwnPik2A/a2ONN+9doY9UxaLfgqsIRg69QA==", "dependencies": { "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" } }, "node_modules/@smithy/util-body-length-node": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-3.0.0.tgz", - "integrity": "sha512-Tj7pZ4bUloNUP6PzwhN7K386tmSmEET9QtQg0TgdNOnxhZvCssHji+oZTUIuzxECRfG8rdm2PMw2WCFs6eIYkA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.0.0.tgz", + "integrity": "sha512-q0iDP3VsZzqJyje8xJWEJCNIu3lktUGVoSy1KB0UWym2CL1siV3artm+u1DFYTLejpsrdGyCSWBdGNjJzfDPjg==", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-buffer-from": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-3.0.0.tgz", - "integrity": "sha512-aEOHCgq5RWFbP+UDPvPot26EJHjOC+bRgse5A8V3FSShqd5E5UN4qc7zkwsvJPPAVsf73QwYcHN1/gt/rtLwQA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.0.0.tgz", + "integrity": "sha512-9TOQ7781sZvddgO8nxueKi3+yGvkY35kotA0Y6BWRajAv8jjmigQ1sBwz0UX47pQMYXJPahSKEKYFgt+rXdcug==", "dependencies": { - "@smithy/is-array-buffer": "^3.0.0", + "@smithy/is-array-buffer": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-config-provider": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-3.0.0.tgz", - "integrity": "sha512-pbjk4s0fwq3Di/ANL+rCvJMKM5bzAQdE5S/6RL5NXgMExFAi6UgQMPOm5yPaIWPpr+EOXKXRonJ3FoxKf4mCJQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.0.0.tgz", + "integrity": "sha512-L1RBVzLyfE8OXH+1hsJ8p+acNUSirQnWQ6/EgpchV88G6zGBTDPdXiiExei6Z1wR2RxYvxY/XLw6AMNCCt8H3w==", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-defaults-mode-browser": { - "version": "3.0.30", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-3.0.30.tgz", - "integrity": "sha512-nLuGmgfcr0gzm64pqF2UT4SGWVG8UGviAdayDlVzJPNa6Z4lqvpDzdRXmLxtOdEjVlTOEdpZ9dd3ZMMu488mzg==", + "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==", "dependencies": { - "@smithy/property-provider": "^3.1.11", - "@smithy/smithy-client": "^3.5.0", - "@smithy/types": "^3.7.2", + "@smithy/property-provider": "^4.0.1", + "@smithy/smithy-client": "^4.1.6", + "@smithy/types": "^4.1.0", "bowser": "^2.11.0", "tslib": "^2.6.2" }, "engines": { - "node": ">= 10.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-defaults-mode-node": { - "version": "3.0.30", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-3.0.30.tgz", - "integrity": "sha512-OD63eWoH68vp75mYcfYyuVH+p7Li/mY4sYOROnauDrtObo1cS4uWfsy/zhOTW8F8ZPxQC1ZXZKVxoxvMGUv2Ow==", + "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==", "dependencies": { - "@smithy/config-resolver": "^3.0.13", - "@smithy/credential-provider-imds": "^3.2.8", - "@smithy/node-config-provider": "^3.1.12", - "@smithy/property-provider": "^3.1.11", - "@smithy/smithy-client": "^3.5.0", - "@smithy/types": "^3.7.2", + "@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", "tslib": "^2.6.2" }, "engines": { - "node": ">= 10.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-endpoints": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-2.1.7.tgz", - "integrity": "sha512-tSfcqKcN/Oo2STEYCABVuKgJ76nyyr6skGl9t15hs+YaiU06sgMkN7QYjo0BbVw+KT26zok3IzbdSOksQ4YzVw==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.0.1.tgz", + "integrity": "sha512-zVdUENQpdtn9jbpD9SCFK4+aSiavRb9BxEtw9ZGUR1TYo6bBHbIoi7VkrFQ0/RwZlzx0wRBaRmPclj8iAoJCLA==", "dependencies": { - "@smithy/node-config-provider": "^3.1.12", - "@smithy/types": "^3.7.2", + "@smithy/node-config-provider": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-hex-encoding": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-3.0.0.tgz", - "integrity": "sha512-eFndh1WEK5YMUYvy3lPlVmYY/fZcQE1D8oSf41Id2vCeIkKJXPcYDCZD+4+xViI6b1XSd7tE+s5AmXzz5ilabQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.0.0.tgz", + "integrity": "sha512-Yk5mLhHtfIgW2W2WQZWSg5kuMZCVbvhFmC7rV4IO2QqnZdbEFPmQnCcGMAX2z/8Qj3B9hYYNjZOhWym+RwhePw==", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-middleware": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-3.0.11.tgz", - "integrity": "sha512-dWpyc1e1R6VoXrwLoLDd57U1z6CwNSdkM69Ie4+6uYh2GC7Vg51Qtan7ITzczuVpqezdDTKJGJB95fFvvjU/ow==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.0.1.tgz", + "integrity": "sha512-HiLAvlcqhbzhuiOa0Lyct5IIlyIz0PQO5dnMlmQ/ubYM46dPInB+3yQGkfxsk6Q24Y0n3/JmcA1v5iEhmOF5mA==", "dependencies": { - "@smithy/types": "^3.7.2", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-retry": { - "version": "3.0.11", - "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-3.0.11.tgz", - "integrity": "sha512-hJUC6W7A3DQgaee3Hp9ZFcOxVDZzmBIRBPlUAk8/fSOEl7pE/aX7Dci0JycNOnm9Mfr0KV2XjIlUOcGWXQUdVQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.0.1.tgz", + "integrity": "sha512-WmRHqNVwn3kI3rKk1LsKcVgPBG6iLTBGC1iYOV3GQegwJ3E8yjzHytPt26VNzOWr1qu0xE03nK0Ug8S7T7oufw==", "dependencies": { - "@smithy/service-error-classification": "^3.0.11", - "@smithy/types": "^3.7.2", + "@smithy/service-error-classification": "^4.0.1", + "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-stream": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-3.3.2.tgz", - "integrity": "sha512-sInAqdiVeisUGYAv/FrXpmJ0b4WTFmciTRqzhb7wVuem9BHvhIG7tpiYHLDWrl2stOokNZpTTGqz3mzB2qFwXg==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.1.2.tgz", + "integrity": "sha512-44PKEqQ303d3rlQuiDpcCcu//hV8sn+u2JBo84dWCE0rvgeiVl0IlLMagbU++o0jCWhYCsHaAt9wZuZqNe05Hw==", "dependencies": { - "@smithy/fetch-http-handler": "^4.1.2", - "@smithy/node-http-handler": "^3.3.2", - "@smithy/types": "^3.7.2", - "@smithy/util-base64": "^3.0.0", - "@smithy/util-buffer-from": "^3.0.0", - "@smithy/util-hex-encoding": "^3.0.0", - "@smithy/util-utf8": "^3.0.0", + "@smithy/fetch-http-handler": "^5.0.1", + "@smithy/node-http-handler": "^4.0.3", + "@smithy/types": "^4.1.0", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-buffer-from": "^4.0.0", + "@smithy/util-hex-encoding": "^4.0.0", + "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-uri-escape": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-3.0.0.tgz", - "integrity": "sha512-LqR7qYLgZTD7nWLBecUi4aqolw8Mhza9ArpNEQ881MJJIU2sE5iHCK6TdyqqzcDLy0OPe10IY4T8ctVdtynubg==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.0.0.tgz", + "integrity": "sha512-77yfbCbQMtgtTylO9itEAdpPXSog3ZxMe09AEhm0dU0NLTalV70ghDZFR+Nfi1C60jnJoh/Re4090/DuZh2Omg==", "dependencies": { "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@smithy/util-utf8": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", - "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.0.0.tgz", + "integrity": "sha512-b+zebfKCfRdgNJDknHCob3O7FpeYQN6ZG6YLExMcasDHsCXlsXCEuiPZeLnJLpwa5dvPetGlnGCiMHuLwGvFow==", "dependencies": { - "@smithy/util-buffer-from": "^3.0.0", + "@smithy/util-buffer-from": "^4.0.0", "tslib": "^2.6.2" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" } }, "node_modules/@socket.io/component-emitter": { @@ -5249,10 +5201,11 @@ "peer": true }, "node_modules/@types/diff": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/diff/-/diff-5.2.3.tgz", - "integrity": "sha512-K0Oqlrq3kQMaO2RhfrNQX5trmt+XLyom88zS0u84nnIcLvFnRUMRRHmrGny5GSM+kNO9IZLARsdQHDzkhAgmrQ==", - "dev": true + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/@types/diff/-/diff-7.0.1.tgz", + "integrity": "sha512-R/BHQFripuhW6XPXy05hIvXJQdQ4540KnTvEFHSLjXfHYM41liOLKgIJEyYYiQe796xpaMHfe4Uj/p7Uvng2vA==", + "dev": true, + "license": "MIT" }, "node_modules/@types/follow-redirects": { "version": "1.14.4", @@ -6163,9 +6116,10 @@ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" }, "node_modules/axios": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", - "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz", + "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==", + "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", diff --git a/core/package.json b/core/package.json index a88bf0cf1..a60eda4ad 100644 --- a/core/package.json +++ b/core/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/core", - "version": "1.0.13", + "version": "1.1.0", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", @@ -17,7 +17,7 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", - "@types/diff": "^5.2.2", + "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", @@ -42,14 +42,14 @@ "ts-jest": "^29.1.1" }, "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.620.1", - "@aws-sdk/client-sagemaker-runtime": "^3.621.0", - "@aws-sdk/credential-providers": "^3.620.1", + "@aws-sdk/client-bedrock-runtime": "^3.758.0", + "@aws-sdk/client-sagemaker-runtime": "^3.758.0", + "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.63", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", - "@continuedev/openai-adapters": "^1.0.10", + "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index b0dc0f881..b6cbd05fb 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -79,6 +79,7 @@ export function slashCommandFromPromptFileV1( for await (const chunk of context.llm.streamChat( messages, new AbortController().signal, + context.completionOptions, )) { yield renderChatMessage(chunk); } diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index d991d140a..069fe1114 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -16,7 +16,9 @@ export async function getPromptFilesFromDir( return []; } - const uris = await walkDir(dir, ide, { ignoreFiles: [] }); + const uris = await walkDir(dir, ide, { + source: "get dir prompt files", + }); const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); const results = promptFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch diff --git a/core/protocol/core.ts b/core/protocol/core.ts index ac991622a..3ab9f1448 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -26,6 +26,7 @@ import type { Session, SessionMetadata, SiteIndexingConfig, + SlashCommandDescription, ToolCall, } from "../"; import { GlobalContextModelSelections } from "../util/GlobalContext"; @@ -68,7 +69,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/deleteModel": [{ title: string }, void]; "config/addContextProvider": [ContextProviderWithParams, void]; "config/reload": [undefined, ConfigResult]; - "config/listProfiles": [undefined, ProfileDescription[] | null]; + "config/listProfiles": [ + undefined, + { profiles: ProfileDescription[] | null; selectedProfileId: string | null }, + ]; "config/refreshProfiles": [undefined, void]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; @@ -98,20 +102,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { "context/indexDocs": [{ reIndex: boolean }, void]; "autocomplete/cancel": [undefined, void]; "autocomplete/accept": [{ completionId: string }, void]; - "command/run": [ - { - input: string; - history: ChatMessage[]; - modelTitle: string; - slashCommandName: string; - contextItems: ContextItemWithId[]; - params: any; - historyIndex: number; - selectedCode: RangeInFile[]; - completionOptions?: LLMFullCompletionOptions; - }, - AsyncGenerator, - ]; "llm/complete": [ { prompt: string; @@ -121,19 +111,18 @@ export type ToCoreFromIdeOrWebviewProtocol = { string, ]; "llm/listModels": [{ title: string }, string[] | undefined]; - "llm/streamComplete": [ - { - prompt: string; - completionOptions: LLMFullCompletionOptions; - title: string; - }, - AsyncGenerator, - ]; "llm/streamChat": [ { messages: ChatMessage[]; completionOptions: LLMFullCompletionOptions; title: string; + legacySlashCommandData?: { + command: SlashCommandDescription; + input: string; + contextItems: ContextItemWithId[]; + historyIndex: number; + selectedCode: RangeInFile[]; + }; }, AsyncGenerator, ]; @@ -184,6 +173,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "files/opened": [{ uris?: string[] }, void]; "files/created": [{ uris?: string[] }, void]; "files/deleted": [{ uris?: string[] }, void]; + "files/closed": [{ uris?: string[] }, void]; // Docs etc. Indexing. TODO move codebase to this "indexing/reindex": [{ type: string; id: string }, void]; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 67b5919a4..4dcf74ee5 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -5,11 +5,15 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { didChangeSelectedProfile: [{ id: string | null }, void]; - didChangeSelectedOrg: [{ 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]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index ef71c66a1..30cf5417c 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -35,10 +35,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "autocomplete/complete", "autocomplete/cancel", "autocomplete/accept", - "command/run", "tts/kill", "llm/complete", - "llm/streamComplete", "llm/streamChat", "llm/listModels", "streamDiffLines", @@ -72,7 +70,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", - "configError", "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. @@ -84,4 +81,6 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "getWebviewHistoryLength", "getCurrentSessionId", "docs/suggestions", + "didCloseFiles", + "didSelectOrganization", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 90df4bd0f..45c3fb424 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,4 +1,4 @@ -import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; +import { ConfigResult } from "@continuedev/config-yaml"; import type { BrowserSerializedContinueConfig, ContextItemWithId, @@ -16,8 +16,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; - configError: [ConfigValidationError[] | undefined, void]; - getDefaultModelTitle: [undefined, string]; + getDefaultModelTitle: [undefined, string | undefined]; indexProgress: [IndexingProgressUpdate, void]; // Codebase "indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc. refreshSubmenuItems: [ @@ -26,6 +25,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; + didCloseFiles: [{ uris: string[] }, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ { diff --git a/core/test/testDir.ts b/core/test/testDir.ts index 9b0473b46..0e34f509b 100644 --- a/core/test/testDir.ts +++ b/core/test/testDir.ts @@ -1,7 +1,7 @@ import fs from "fs"; import os from "os"; import path from "path"; -import { localPathToUri, localPathOrUriToPath } from "../util/pathToUri"; +import { localPathOrUriToPath, localPathToUri } from "../util/pathToUri"; // Want this outside of the git repository so we can change branches in tests export const TEST_DIR_PATH = path.join(os.tmpdir(), "testWorkspaceDir"); @@ -26,7 +26,7 @@ export function tearDownTestDir() { "index/index.ts" creates an empty index/index.ts ["index/index.ts", "hello"] creates index/index.ts with contents "hello" */ -export function addToTestDir(pathsOrUris: (string | string[])[]) { +export function addToTestDir(pathsOrUris: (string | [string, string])[]) { // Allow tests to use URIs or local paths const paths = pathsOrUris.map((val) => { if (Array.isArray(val)) { diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 959752af1..8d4b1f1b3 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -86,20 +86,44 @@ async function callToolFromUri( throw new Error(`Failed to call tool: ${toolName}`); } - return (response.content as any).map((item: any): ContextItem => { - if (item.type !== "text") { - throw new Error( - `Continue received item of type "${item.type}" from MCP tool, but currently only supports "text".`, - ); + const contextItems: ContextItem[] = []; + (response.content as any).forEach((item: any) => { + if (item.type === "text") { + contextItems.push({ + name: extras.tool.displayTitle, + description: "Tool output", + content: item.text, + icon: extras.tool.faviconUrl, + }); + } else if (item.type === "resource") { + // TODO resource change subscribers https://modelcontextprotocol.io/docs/concepts/resources + if (item.resource?.blob) { + contextItems.push({ + name: extras.tool.displayTitle, + description: "MCP Item Error", + content: + "Error: tool call received unsupported blob resource item", + icon: extras.tool.faviconUrl, + }); + } + // TODO account for mimetype? // const mimeType = item.resource.mimeType + // const uri = item.resource.uri; + contextItems.push({ + name: extras.tool.displayTitle, + description: "Tool output", + content: item.resource.text, + icon: extras.tool.faviconUrl, + }); + } else { + contextItems.push({ + name: extras.tool.displayTitle, + description: "MCP Item Error", + content: `Error: tool call received unsupported item of type "${item.type}"`, + icon: extras.tool.faviconUrl, + }); } - return { - name: extras.tool.displayTitle, - description: "Tool output", - content: item.text, - icon: extras.tool.faviconUrl, - }; }); - + return contextItems; default: throw new Error(`Unsupported protocol: ${parsedUri?.protocol}`); } diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index f0082891c..7af42d6a8 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -8,14 +8,16 @@ export const createNewFileTool: Tool = { readonly: false, function: { name: BuiltInToolNames.CreateNewFile, - description: "Create a new file", + description: + "Create a new file. Only use this when a file doesn't exist and should be created", parameters: { type: "object", required: ["filepath", "contents"], properties: { filepath: { type: "string", - description: "The path where the new file should be created", + description: + "The path where the new file should be created, relative to the root of the workspace", }, contents: { type: "string", diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 79497a158..5abc2edb1 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -9,7 +9,7 @@ export const readCurrentlyOpenFileTool: Tool = { function: { name: BuiltInToolNames.ReadCurrentlyOpenFile, description: - "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, this is probably it.", + "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, try using this", parameters: { type: "object", properties: {}, diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 00e16ba32..4f5366e23 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -9,7 +9,7 @@ export const readFileTool: Tool = { function: { name: BuiltInToolNames.ReadFile, description: - "Use this tool whenever you need to view the contents of a file.", + "Use this tool if you need to view the contents of an existing file.", parameters: { type: "object", required: ["filepath"], @@ -17,7 +17,7 @@ export const readFileTool: Tool = { filepath: { type: "string", description: - "The path of the file to read, relative to the root of the workspace.", + "The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)", }, }, }, diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index 82b2d342c..1b526009a 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -9,7 +9,7 @@ export const runTerminalCommandTool: Tool = { function: { name: BuiltInToolNames.RunTerminalCommand, description: - "Run a terminal command in the current directory. The shell is not stateful and will not remember any previous commands.", + "Run a terminal command in the current directory. The shell is not stateful and will not remember any previous commands. Do NOT perform actions requiring special/admin priveleges.", parameters: { type: "object", required: ["command"], @@ -17,7 +17,7 @@ export const runTerminalCommandTool: Tool = { command: { type: "string", description: - "The command to run. This will be passed directly into the shell.", + "The command to run. This will be passed directly into the IDE shell.", }, }, }, diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index c5868f3e0..dfbcb04f7 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -10,7 +10,7 @@ export const searchWebTool: Tool = { function: { name: BuiltInToolNames.SearchWeb, description: - "Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.", + "Performs a web search, returning top results. Use this tool sparingly - only for questions that require specialized, external, and/or up-to-date knowledege. Common programming questions do not require web search.", parameters: { type: "object", required: ["query"], diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index ccb79f290..9196cca2a 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -1,8 +1,8 @@ import childProcess from "node:child_process"; import util from "node:util"; -import { ToolImpl } from "."; import { fileURLToPath } from "node:url"; +import { ToolImpl } from "."; const asyncExec = util.promisify(childProcess.exec); @@ -26,7 +26,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { { name: "Terminal", description: "Terminal command output", - content: error.stderr ?? error.toString(), + content: error.stderr || error.stdout || error.toString(), }, ]; } diff --git a/core/util/generateRepoMap.test.ts b/core/util/generateRepoMap.test.ts index 536d3fcac..78f879f63 100644 --- a/core/util/generateRepoMap.test.ts +++ b/core/util/generateRepoMap.test.ts @@ -1,17 +1,17 @@ // Generated by continue -import generateRepoMap from "./generateRepoMap"; -import { testIde, testLLM } from "../test/fixtures"; -import { - setUpTestDir, - tearDownTestDir, - addToTestDir, - TEST_DIR, -} from "../test/testDir"; import fs from "fs"; import path from "path"; -import { getRepoMapFilePath } from "./paths"; import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; +import { testIde, testLLM } from "../test/fixtures"; +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, + TEST_DIR, +} from "../test/testDir"; +import generateRepoMap from "./generateRepoMap"; +import { getRepoMapFilePath } from "./paths"; describe.skip("generateRepoMap", () => { beforeEach(() => { @@ -49,7 +49,8 @@ describe.skip("generateRepoMap", () => { "def bar():", ], }, - hasMore: false, + hasMoreSnippets: false, + hasMoreUris: false, }; }); @@ -108,7 +109,8 @@ describe.skip("generateRepoMap", () => { [path.join(TEST_DIR, "file1.js")]: [], [path.join(TEST_DIR, "subdir/file2.py")]: [], }, - hasMore: false, + hasMoreSnippets: false, + hasMoreUris: false, }; }); @@ -161,7 +163,8 @@ describe.skip("generateRepoMap", () => { [path.join(TEST_DIR, "file1.js")]: ["function foo() {}"], [path.join(TEST_DIR, "subdir/file2.py")]: ["def foo():"], }, - hasMore: false, + hasMoreSnippets: false, + hasMoreUris: false, }; }); diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts index b0af8079a..c372f147b 100644 --- a/core/util/generateRepoMap.ts +++ b/core/util/generateRepoMap.ts @@ -24,7 +24,8 @@ class RepoMapGenerator { private allUris: string[] = []; private pathsInDirsWithSnippets: Set = new Set(); - private BATCH_SIZE = 100; + private SNIPPETS_BATCH_SIZE = 100; + private URI_BATCH_SIZE = 100; private REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; private PREAMBLE = "Below is a repository map. \n" + @@ -50,20 +51,29 @@ class RepoMapGenerator { async generate(): Promise { this.dirs = this.options.dirUris ?? (await this.ide.getWorkspaceDirs()); - this.allUris = await walkDirs(this.ide, undefined, this.dirs); + this.allUris = await walkDirs( + this.ide, + { + source: "generate repo map", + }, + this.dirs, + ); // Initialize await this.writeToStream(this.PREAMBLE); if (this.options.includeSignatures) { // Process uris and signatures - let offset = 0; + let snippetOffset = 0; + let uriOffset = 0; while (true) { - const { groupedByUri, hasMore } = + const { groupedByUri, hasMoreSnippets, hasMoreUris } = await CodeSnippetsCodebaseIndex.getPathsAndSignatures( this.allUris, - offset, - this.BATCH_SIZE, + uriOffset, + this.URI_BATCH_SIZE, + snippetOffset, + this.SNIPPETS_BATCH_SIZE, ); // process batch for (const [uri, signatures] of Object.entries(groupedByUri)) { @@ -103,10 +113,17 @@ class RepoMapGenerator { await this.writeToStream(content); } } - if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) { + if (this.contentTokens >= this.maxRepoMapTokens) { + break; + } + if (hasMoreSnippets) { + snippetOffset += this.SNIPPETS_BATCH_SIZE; + } else if (hasMoreUris) { + snippetOffset = 0; + uriOffset += this.URI_BATCH_SIZE; + } else { break; } - offset += this.BATCH_SIZE; } // Remaining Uris just so that written repo map isn't incomplete diff --git a/core/util/index.ts b/core/util/index.ts index 4cb0f4920..196104f4f 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -204,3 +204,10 @@ export function removeCodeBlocksAndTrim(text: string): string { return textWithoutCodeBlocks.trim(); } + +export function splitCamelCaseAndNonAlphaNumeric(value: string) { + return value + .split(/(?<=[a-z0-9])(?=[A-Z])|[^a-zA-Z0-9]/) + .filter(t => t.length > 0) + .map(t => t.toLowerCase()); +} diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts index 89462a1bf..31c447389 100644 --- a/core/util/messageContent.ts +++ b/core/util/messageContent.ts @@ -18,13 +18,16 @@ export function stripImages(messageContent: MessageContent): string { } export function renderChatMessage(message: ChatMessage): string { - switch (message.role) { + switch (message?.role) { case "user": case "assistant": + case "thinking": case "system": return stripImages(message.content); case "tool": return message.content; + default: + return ""; } } @@ -36,6 +39,7 @@ export function normalizeToMessageParts(message: ChatMessage): MessagePart[] { switch (message.role) { case "user": case "assistant": + case "thinking": case "system": return Array.isArray(message.content) ? message.content diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index a00e869dd..2d5266318 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -1,6 +1,13 @@ +import crypto from "crypto"; +import { exec } from "node:child_process"; import path from "node:path"; import { IDE } from ".."; -import { exec } from "node:child_process"; + +export interface ModelInfo { + id: string; + size: number; + digest: string; +} export async function isOllamaInstalled(): Promise { return new Promise((resolve, _reject) => { @@ -39,3 +46,54 @@ export async function startLocalOllama(ide: IDE): Promise { }); } } + +export async function getRemoteModelInfo( + modelId: string, + signal?: AbortSignal, + ): Promise { + const start = Date.now(); + const [modelName, tag = "latest"] = modelId.split(":"); + const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`; + try { + const sig = signal ? signal : AbortSignal.timeout(3000); + const response = await fetch(url, { signal: sig }); + + if (!response.ok) { + throw new Error(`Failed to fetch the model page: ${response.statusText}`); + } + + // First, read the response body as an ArrayBuffer to compute the digest + const buffer = await response.arrayBuffer(); + const digest = getDigest(buffer); + + // Then, decode the ArrayBuffer into a string and parse it as JSON + const text = new TextDecoder().decode(buffer); + const manifest = JSON.parse(text) as { + config: { size: number }; + layers: { size: number }[]; + }; + const modelSize = + manifest.config.size + + manifest.layers.reduce((sum, layer) => sum + layer.size, 0); + + const data: ModelInfo = { + id: modelId, + size: modelSize, + digest, + }; + // Cache the successful result + return data; + } catch (error) { + console.error(`Error fetching or parsing model info: ${error}`); + } finally { + const elapsed = Date.now() - start; + console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`); + } + return undefined; + } + + function getDigest(buffer: ArrayBuffer): string { + const hash = crypto.createHash("sha256"); + hash.update(new Uint8Array(buffer)); + return hash.digest("hex"); + } \ No newline at end of file diff --git a/core/util/pathToUri.ts b/core/util/pathToUri.ts index 67a249d74..ce83563fd 100644 --- a/core/util/pathToUri.ts +++ b/core/util/pathToUri.ts @@ -6,6 +6,11 @@ import * as URI from "uri-js"; // Converts a local path to a file:/// URI export function localPathToUri(path: string) { + // This may incidentally solve bugs, but it is primarily here to warn us if we accidentally try to double-convert. It doesn't handle other URI schemes. + if (path.startsWith("file://")) { + console.warn("localPathToUri: path already starts with file://"); + return path; + } const url = pathToFileURL(path); return URI.normalize(url.toString()); } diff --git a/core/util/paths.ts b/core/util/paths.ts index bd5a69e1a..3bc2ee3cf 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -103,7 +103,7 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string { return p; } -export function getConfigYamlPath(ideType: IdeType): string { +export function getConfigYamlPath(ideType?: IdeType): string { const p = path.join(getContinueGlobalPath(), "config.yaml"); // if (!fs.existsSync(p)) { // if (ideType === "jetbrains") { @@ -115,6 +115,14 @@ export function getConfigYamlPath(ideType: IdeType): string { return p; } +export function getPrimaryConfigFilePath(): string { + const configYamlPath = getConfigYamlPath(); + if (fs.existsSync(configYamlPath)) { + return configYamlPath; + } + return getConfigJsonPath(); +} + export function getConfigTsPath(): string { const p = path.join(getContinueGlobalPath(), "config.ts"); if (!fs.existsSync(p)) { @@ -353,6 +361,10 @@ export function getGlobalPromptsPath(): string { return path.join(getContinueGlobalPath(), "prompts"); } +export function getGlobalAssistantsPath(): string { + return path.join(getContinueGlobalPath(), "assistants"); +} + export function readAllGlobalPromptFiles( folderPath: string = getGlobalPromptsPath(), ): { path: string; content: string }[] { @@ -368,7 +380,7 @@ export function readAllGlobalPromptFiles( if (stats.isDirectory()) { const nestedPromptFiles = readAllGlobalPromptFiles(filepath); promptFiles.push(...nestedPromptFiles); - } else { + } else if (file.endsWith(".prompt")) { const content = fs.readFileSync(filepath, "utf8"); promptFiles.push({ path: filepath, content }); } @@ -406,6 +418,10 @@ export function migrateV1DevDataFiles() { moveToV1FolderIfExists("autocomplete", "autocomplete"); } +export function getLocalEnvironmentDotFilePath(): string { + return path.join(getContinueGlobalPath(), ".local"); +} + export function getStagingEnvironmentDotFilePath(): string { return path.join(getContinueGlobalPath(), ".staging"); } diff --git a/core/util/text.ts b/core/util/text.ts new file mode 100644 index 000000000..e4870dfa0 --- /dev/null +++ b/core/util/text.ts @@ -0,0 +1,6 @@ +export const capitalizeFirstLetter = (val: string) => { + if (val.length === 0) { + return ""; + } + return val[0].toUpperCase() + val.slice(1); +}; diff --git a/core/util/uri.ts b/core/util/uri.ts index 13d7956ac..e180a0a69 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -116,19 +116,23 @@ export function getLastNUriRelativePathParts( } export function joinPathsToUri(uri: string, ...pathSegments: string[]) { - const components = URI.parse(uri); + let baseUri = uri; + if (baseUri.at(-1) !== "/") { + baseUri += "/"; + } const segments = pathSegments.map((segment) => pathToUriPathSegment(segment)); - components.path = `${components.path}/${segments.join("/")}`; - return URI.serialize(components); + return URI.resolve(baseUri, segments.join("/")); } export function joinEncodedUriPathSegmentToUri( uri: string, pathSegment: string, ) { - const components = URI.parse(uri); - components.path = `${components.path}/${pathSegment}`; - return URI.serialize(components); + let baseUri = uri; + if (baseUri.at(-1) !== "/") { + baseUri += "/"; + } + return URI.resolve(baseUri, pathSegment); } export function getShortestUniqueRelativeUriPaths( diff --git a/docs/docs/customize/context-providers.mdx b/docs/docs/customize/context-providers.mdx index 41c6edc57..b31deedf4 100644 --- a/docs/docs/customize/context-providers.mdx +++ b/docs/docs/customize/context-providers.mdx @@ -879,6 +879,11 @@ assignee = currentUser() AND resolution = Unresolved order by updated DESC You can override this query by setting the `issueQuery` parameter. +#### Max results + +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/_apply.md b/docs/docs/customize/deep-dives/_apply.md new file mode 100644 index 000000000..1f87a1993 --- /dev/null +++ b/docs/docs/customize/deep-dives/_apply.md @@ -0,0 +1,16 @@ +--- +description: Learn how to use the Apply feature +keywords: [apply, speculative] +toc_max_heading_level: 5 +--- + + + +# Apply + +## Instant Diff Apply + +If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff". +The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change. + +Explainer Video: https://youtu.be/b7Xxsot4gyw diff --git a/docs/docs/customize/deep-dives/codebase.mdx b/docs/docs/customize/deep-dives/codebase.mdx index 24256672e..409ecd080 100644 --- a/docs/docs/customize/deep-dives/codebase.mdx +++ b/docs/docs/customize/deep-dives/codebase.mdx @@ -49,8 +49,8 @@ There are a few options that let you configure the behavior of the `@codebase` c context: - provider: codebase params: - nRetrieve: 25, - nFinal: 5, + nRetrieve: 25 + nFinal: 5 useReranking: true ``` diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index 11522e86f..dd48ddbe7 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -9,7 +9,7 @@ keywords: [config, settings, customize] Continue can be deeply customized. 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 Config File` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below. +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) @@ -18,7 +18,7 @@ To open your configuration file, you can click the "gear" icon in the bottom rig 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](../../reference.md). +See the full reference for `config.yaml` [here](../../yaml-reference.md). ## Deprecated configuration methods diff --git a/docs/docs/customize/deep-dives/development-data.md b/docs/docs/customize/deep-dives/development-data.md index 976c02833..da9f5136c 100644 --- a/docs/docs/customize/deep-dives/development-data.md +++ b/docs/docs/customize/deep-dives/development-data.md @@ -14,7 +14,7 @@ You can read more about how development data is generated as a byproduct of LLM- You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories. -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&block=data). +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) diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index 7a5be2263..ee806263e 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -64,7 +64,7 @@ Pre-indexed docs are only available in VS Code because the VS Code extension shi ### Hub `docs` Blocks -@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&block=docs). +@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs). ### Through the `@Docs` Context Provider @@ -137,7 +137,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo context: - provider: docs params: - nRetrieve: 25 # The number of docs to retreive from the embeddings query + nRetrieve: 25 # The number of docs to retrieve from the embeddings query nFinal: 5 # The number of docs chunks to return IF reranking useReranking: true # use reranking if a reranker is configured (defaults to true) ``` @@ -149,7 +149,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo { "name": "docs", "params": { - "nRetrieve": 25, // The number of docs to retreive from the embeddings query + "nRetrieve": 25, // The number of docs to retrieve from the embeddings query "nFinal": 5, // The number of docs chunks to return IF reranking "useReranking": true // use reranking if a reranker is configured (defaults to true) } diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 1ab90e94a..f5c834c17 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -4,7 +4,7 @@ title: Prompt files Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts. -On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&block=rules). +On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=rules). Prompt files can also be stored within your project's root directory as `.prompt` files. See below. diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index eac9137ce..59f816c15 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -9,7 +9,7 @@ Rules are used to provide instructions to **chat** models. They are inserted int ## Hub `rules` blocks -Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&block=rules) in the Hub. +Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. ## `.continuerules` diff --git a/docs/docs/customize/model-providers/more/ncompass.mdx b/docs/docs/customize/model-providers/more/ncompass.mdx index e6f98c296..2aa678569 100644 --- a/docs/docs/customize/model-providers/more/ncompass.mdx +++ b/docs/docs/customize/model-providers/more/ncompass.mdx @@ -3,15 +3,15 @@ import TabItem from "@theme/TabItem"; # nCompass -The nCompass Technologies API exposes an extremely fast inference engine for open-source language models. You can sign up [here](https://app.ncompass.tech/api-settings), copy your API key on the initial welcome screen, and then hit the play button on any model from the [nCompass Models list](https://console.ncompass.tech/models). Change `~/.continue/config.json` to look like this: +The nCompass Technologies API exposes an extremely fast inference engine for open-source language models. You can sign up [here](https://app.ncompass.tech/api-settings), copy your API key on the initial welcome screen, and then hit the play button on any model from the [nCompass Models list](https://ncompass.tech/models). Change `~/.continue/config.json` to look like this: ```yaml title="Package or config.yaml" models: - - name: Ncompass Qwen2.5 Coder + - name: Ncompass Gemma 3 Coder provider: ncompass - model: Qwen/Qwen2.5-Coder-32B-Instruct + model: google/gemma-3-27b-it apiKey: ``` @@ -20,9 +20,9 @@ The nCompass Technologies API exposes an extremely fast inference engine for ope { "models": [ { - "title": "Ncompass Qwen2.5 Coder", + "title": "Ncompass Gemma 3 Coder", "provider": "ncompass", - "model": "Qwen/Qwen2.5-Coder-32B-Instruct", + "model": "google/gemma-3-27b-it", "apiKey": "" } ] diff --git a/docs/docs/customize/model-providers/more/relace.mdx b/docs/docs/customize/model-providers/more/relace.mdx new file mode 100644 index 000000000..2b046c318 --- /dev/null +++ b/docs/docs/customize/model-providers/more/relace.mdx @@ -0,0 +1,38 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Relace + +Relace provides a fast apply model through their API that helps you reliably and almost instantly apply chat suggestions to your codebase. You can sign up and obtain an API key [here](https://app.relace.ai/settings/api-keys). Then, change your configuration file to look like this: + + + + ```yaml title="Package or config.yaml" + models: + - name: Relace Fast Apply + provider: relace + model: Fast-Apply + apiKey: + roles: + - apply + promptTemplates: + apply: "{{{ new_code }}}" + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Relace Fast Apply", + "provider": "relace", + "model": "Fast-Apply", + "apiKey": "" + } + ] + } + ``` + + + +[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Relace.ts) diff --git a/docs/docs/customize/model-providers/more/vllm.mdx b/docs/docs/customize/model-providers/more/vllm.mdx index 58431ec7d..9bae1880e 100644 --- a/docs/docs/customize/model-providers/more/vllm.mdx +++ b/docs/docs/customize/model-providers/more/vllm.mdx @@ -3,7 +3,7 @@ import Tabs from "@theme/Tabs"; # vLLM -vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html). +vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same time. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html). ```shell vllm serve meta-llama/Meta-Llama-3.1-8B-Instruct diff --git a/docs/docs/customize/model-providers/more/watsonx.mdx b/docs/docs/customize/model-providers/more/watsonx.mdx index 0854e0cd6..f2360788f 100644 --- a/docs/docs/customize/model-providers/more/watsonx.mdx +++ b/docs/docs/customize/model-providers/more/watsonx.mdx @@ -244,3 +244,37 @@ To view the list of available embeddings models, visit [this page](https://datap ``` + + +## Reranker + + + + ```yaml title="config.yaml" + models: + - name: Watsonx Reranker + provider: watsonx + model: cross-encoder/ms-marco-minilm-l-12-v2 + apiBase: https://us-south.ml.cloud.ibm.com + projectId: PROJECT_ID + apiKey: API_KEY/ZENAPI_KEY/USERNAME:PASSWORD + apiVersion: 2024-03-14 + ``` + + + ```json title="config.json" + { + "reranker": { + "name": "watsonx", + "params": { + "model": "cross-encoder/ms-marco-minilm-l-12-v2", + "apiBase": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "projectId": "PROJECT_ID", + "apiKey": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "apiVersion": "2024-03-14" + } + } + } + ``` + + diff --git a/docs/docs/customize/model-providers/top-level/azure.mdx b/docs/docs/customize/model-providers/top-level/azure.mdx index cbb955bca..2c201d938 100644 --- a/docs/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/docs/customize/model-providers/top-level/azure.mdx @@ -51,7 +51,7 @@ We recommend configuring **GPT-4o** as your chat model. ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. +We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral: @@ -60,6 +60,8 @@ We recommend configuring **Codestral** as your autocomplete model. - name: Codestral provider: mistral model: codestral-latest + apiBase: https://..models.ai.azure.com/v1 + apiKey: roles: - autocomplete ``` @@ -70,7 +72,9 @@ We recommend configuring **Codestral** as your autocomplete model. "tabAutocompleteModel": { "title": "Codestral", "provider": "mistral", - "model": "codestral-latest" + "model": "codestral-latest", + "apiBase": "https://..models.ai.azure.com/v1", + "apiKey": "" } } ``` diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index 2024673f9..ae2baf79a 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -21,7 +21,7 @@ Most custom configuration is done by editing `config.yaml` (or the older `config - MacOS and Linux: `~/.continue/config.yaml` - Windows: `%USERPROFILE%\.continue\config.yaml` -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 configuration file`. +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) diff --git a/docs/docs/customize/settings.md b/docs/docs/customize/settings.md index 0d917df6e..f76494032 100644 --- a/docs/docs/customize/settings.md +++ b/docs/docs/customize/settings.md @@ -14,7 +14,7 @@ Which takes you to this page: ![User Settings Page](/img/settings-page.png) -Click the `Open Config File` button to open your configuration file. See the [Configuration Reference](../reference.md) for more information. +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: diff --git a/docs/docs/customize/tools.mdx b/docs/docs/customize/tools.mdx index 45280697e..1aad549f1 100644 --- a/docs/docs/customize/tools.mdx +++ b/docs/docs/customize/tools.mdx @@ -30,7 +30,7 @@ Currently custom tools can be configured using the [Model Context Protocol](http 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&block=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](../customize/deep-dives/configuration.md): diff --git a/docs/docs/json-reference.md b/docs/docs/json-reference.md index ba21ccb65..11e92a183 100644 --- a/docs/docs/json-reference.md +++ b/docs/docs/json-reference.md @@ -36,6 +36,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. _(AWS Only)_ diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index 79ebefecb..3065bdc28 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -41,7 +41,7 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c 1. Open the "Output" panel (right next to the terminal) 2. In the dropdown, select "Continue - LLM Prompts/Completions" -3. View the exact prompts that were sent to the LLM and the completions recieved +3. View the exact prompts that were sent to the LLM and the completions received ### JetBrains diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index 0a7773670..ec189e429 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](/reference) +- [YAML Continue Config Reference](/yaml-reference) ## Create YAML file @@ -23,6 +23,7 @@ Give your configuration a `name` and a `version`: ```yaml title="config.yaml" name: my-configuration version: 0.0.1 +schema: v1 ``` ### Models @@ -37,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](/reference#requestoptions) +Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions) -Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/reference#completionoptions) +Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions) diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md index d4e63d1b4..2039c3887 100644 --- a/docs/docs/yaml-reference.md +++ b/docs/docs/yaml-reference.md @@ -31,6 +31,10 @@ Hub blocks and assistants are identified with a slug in the format `owner-slug/b 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" @@ -134,6 +138,7 @@ The `models` section defines the language models used in your configuration. Mod - `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. @@ -187,6 +192,17 @@ models: 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 ``` --- @@ -428,6 +444,7 @@ a `config.yaml` configuration file using anchors: --- name: MyProject version: 0.0.1 +schema: v1 model_defaults: &model_defaults provider: openai diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 8216da215..c8d987266 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -19,7 +19,7 @@ const config = { favicon: "img/favicon.ico", // Set the production url of your site here - url: "https://continue.dev", + url: "https://docs.continue.dev", // Set the // pathname under which your site is served // For GitHub pages deployment, it is often '//' baseUrl: "/", diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md index 0a280cda8..7f9106075 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md @@ -45,13 +45,13 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo ## Embeddings model -We recommend configuring **text-embedding-004** as your embeddings model. +We recommend configuring **text-embedding-005** as your embeddings model. ```json title="config.json" { "embeddingsProvider": { "provider": "vertexai", - "model": "text-embedding-004", + "model": "text-embedding-005", "projectId": "[PROJECT_ID]", "region": "us-central1" } diff --git a/docs/package-lock.json b/docs/package-lock.json index 6fb4d260f..abd1275c6 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -1756,9 +1756,9 @@ } }, "node_modules/@babel/runtime": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.0.tgz", - "integrity": "sha512-FDSOghenHTiToteC/QRlv2q3DhPZ/oOXTBoirfWNx1Cx3TMVcGWQtMMmQcSvb/JjpNeGzx8Pq/b4fKEJuWm1sw==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.10.tgz", + "integrity": "sha512-2WJMeRQPHKSPemqk/awGrAiuFfzBmOIPXKizAsVhWH9YJqLZ0H+HS4c8loHGgW6utJ3E/ejXQUsiGaQy2NZ9Fw==", "license": "MIT", "dependencies": { "regenerator-runtime": "^0.14.0" @@ -1768,9 +1768,10 @@ } }, "node_modules/@babel/runtime-corejs3": { - "version": "7.26.0", - "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.26.0.tgz", - "integrity": "sha512-YXHu5lN8kJCb1LOb9PgV6pvak43X2h4HvRApcN5SdWeaItQOzfn1hgP6jasD6KWQyJDBxrVmA9o9OivlnNJK/w==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.26.10.tgz", + "integrity": "sha512-uITFQYO68pMEYR46AHgQoyBg7KPPJDAbGn4jUTIRgCFJIp88MIBUianVOplhZDEec07bp9zIyr4Kp0FCyQzmWg==", + "license": "MIT", "dependencies": { "core-js-pure": "^3.30.2", "regenerator-runtime": "^0.14.0" diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 8553d3528..0d846c3d2 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.2 +pluginVersion=1.0.5 # 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 53a8ebd0b..9d48705df 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,5 +1,5 @@ package com.github.continuedev.continueintellijextension.activities - +import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.github.continuedev.continueintellijextension.auth.AuthListener import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.auth.ControlPlaneSessionInfo @@ -37,6 +37,7 @@ import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.ide.ui.LafManagerListener +import com.intellij.openapi.vfs.VirtualFile fun showTutorial(project: Project) { val tutorialFileName = getTutorialFileName() @@ -199,6 +200,24 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { } }) + + connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { + override fun fileClosed(source: FileEditorManager, file: VirtualFile) { + file.toUriOrNull()?.let { uri -> + val data = mapOf("uris" to listOf(uri)) + continuePluginService.coreMessenger?.request("files/closed", data, null) { _ -> } + } + } + override fun fileOpened(source: FileEditorManager, file: VirtualFile) { + file.toUriOrNull()?.let { uri -> + val data = mapOf("uris" to listOf(uri)) + continuePluginService.coreMessenger?.request("files/opened", data, null) { _ -> } + } + } + }) + + + // Listen for theme changes connection.subscribe(LafManagerListener.TOPIC, LafManagerListener { val colors = GetTheme().getTheme(); diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index 23b6b66bd..f65404dcd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.auth import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.Desktop import com.google.gson.Gson import com.intellij.credentialStore.Credentials import com.intellij.ide.passwordSafe.PasswordSafe @@ -12,7 +13,6 @@ import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes import kotlinx.coroutines.CoroutineScope -import java.awt.Desktop import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -153,8 +153,7 @@ class ContinueAuthService { ) { response -> val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String if (authUrl != null) { - // Open the auth URL in the browser - Desktop.getDesktop().browse(java.net.URI(authUrl)) + Desktop.browse(java.net.URI(authUrl)) } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt index 6477f5403..2f2fa593b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt @@ -29,18 +29,18 @@ class AutocompleteLookupListener(project: Project) : LookupManagerListener { newLookup.addLookupListener( object : LookupListener { override fun lookupShown(event: LookupEvent) { - super.lookupShown(event) + isLookupShown.set(false) ApplicationManager.getApplication().invokeLater { - isLookupShown.set(false) event.lookup.editor.project?.service()?.hideCompletions(newEditor) } } override fun lookupCanceled(event: LookupEvent) { - super.lookupCanceled(event) - ApplicationManager.getApplication().invokeLater { - isLookupShown.set(true) - } + isLookupShown.set(true) + } + + override fun itemSelected(event: LookupEvent) { + isLookupShown.set(true) } }) } 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 e71401b15..fcf9a468b 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 @@ -58,7 +58,6 @@ class MessageTypes { // Note: If updating these values, make a corresponding update in // core/protocol/passThrough.ts val PASS_THROUGH_TO_WEBVIEW = listOf( - "configError", "configUpdate", "getDefaultModelTitle", "indexProgress", // Codebase @@ -71,6 +70,8 @@ class MessageTypes { "getWebviewHistoryLength", "getCurrentSessionId", "docs/suggestions", + "didCloseFiles", + "didSelectOrganization" ) // Note: If updating these values, make a corresponding update in @@ -102,10 +103,8 @@ class MessageTypes { "autocomplete/complete", "autocomplete/cancel", "autocomplete/accept", - "command/run", "tts/kill", "llm/complete", - "llm/streamComplete", "llm/streamChat", "llm/listModels", "streamDiffLines", 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 796b3aac6..e903e1238 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 @@ -6,6 +6,7 @@ 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.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine @@ -36,7 +37,6 @@ import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody -import java.awt.Desktop import java.awt.Toolkit import java.awt.datatransfer.DataFlavor import java.io.BufferedReader @@ -83,7 +83,7 @@ class IntelliJIDE( val extensionVersion = plugin?.version ?: "Unknown" return IdeInfo( - ideType = IdeType.JETBRAINS, + ideType = "jetbrains", name = ideName, version = ideVersion, remoteName = remoteName, @@ -239,7 +239,7 @@ class IntelliJIDE( override suspend fun openUrl(url: String) { withContext(Dispatchers.IO) { - Desktop.getDesktop().browse(URI(url)) + Desktop.browse(java.net.URI(url)) } } @@ -343,7 +343,7 @@ class IntelliJIDE( } override suspend fun getSearchResults(query: String): String { - val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--", query, ".") + val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--heading", "-e", query, ".") command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout } 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 e44c08dd5..55df303a8 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 @@ -13,6 +13,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile +import kotlin.math.max import kotlin.math.min @@ -179,7 +180,7 @@ class DiffStreamHandler( // Update the highlighter to show the current line curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) } curLine.highlighter = editor.markupModel.addLineHighlighter( - curLineKey, min(curLine.index, editor.document.lineCount - 1), HighlighterLayer.LAST + curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST ) // Remove the unfinished lines highlighter diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt index 1c683253d..489ef9006 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt @@ -111,7 +111,10 @@ class OpenedConnection(private val connection: URLConnection?) : ) { try { if (connection != null) { - val url = connection.url.toString() + val fullUrl = connection.url.toString() + // Extract only the resource path after the JAR prefix to prevent incorrect mime type matching + // (e.g., if a user's home folder contains "js" in the path) + val url = fullUrl.substringAfterLast("jar!/", fullUrl) when { url.contains("css") -> cefResponse.mimeType = "text/css" url.contains("js") -> cefResponse.mimeType = "text/javascript" diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 4c2ad3b59..8cb700f15 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -14,6 +14,7 @@ import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.jcef.* +import com.intellij.ui.jcef.JBCefClient.Properties import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter @@ -32,10 +33,16 @@ class ContinueBrowser(val project: Project, url: String) { init { val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR - this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build() + this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply { + // To avoid using System.setProperty to affect other plugins, + // we should configure JS_QUERY_POOL_SIZE after JBCefClient is instantiated, + // and eliminate the 'Uncaught TypeError: window.cefQuery_xxx is not a function' error + // in the JS debug console, which is caused by ContinueBrowser lazy loading. + jbCefClient.setProperty(Properties.JS_QUERY_POOL_SIZE, JS_QUERY_POOL_SIZE) + } registerAppSchemeHandler() - browser.loadURL(url); + browser.loadURL(url) Disposer.register(ContinuePluginDisposable.getInstance(project), browser) // Listen for events sent from browser diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index d0d44655c..5d8335220 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -11,7 +11,7 @@ import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.content.ContentFactory import javax.swing.* -const val JS_QUERY_POOL_SIZE = "200" +const val JS_QUERY_POOL_SIZE = 200 class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { @@ -43,11 +43,6 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { class ContinuePluginWindow(project: Project) { private val defaultGUIUrl = "http://continue/index.html" - init { - System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE) - System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true") - } - val browser: ContinueBrowser by lazy { val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl 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 852325859..7dfa83da4 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 @@ -2,11 +2,6 @@ package com.github.continuedev.continueintellijextension import com.google.gson.JsonElement -enum class IdeType(val value: String) { - JETBRAINS("jetbrains"), - VSCODE("vscode"), -} - enum class ToastType(val value: String) { INFO("info"), ERROR("error"), @@ -30,7 +25,7 @@ data class Position(val line: Int, val character: Int) data class Range(val start: Position, val end: Position) data class IdeInfo( - val ideType: IdeType, + val ideType: String, val name: String, val version: String, val remoteName: String, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt new file mode 100644 index 000000000..8dd20536c --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt @@ -0,0 +1,214 @@ +/* + * Copyright © 2017 jjYBdx4IL (https://github.com/jjYBdx4IL) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.github.continuedev.continueintellijextension.utils + +import org.apache.commons.lang3.SystemUtils +import org.slf4j.LoggerFactory +import java.io.File +import java.io.IOException +import java.net.URI + +object Desktop { + private val LOG = LoggerFactory.getLogger(Desktop::class.java) + + fun browse(uri: URI): Boolean { + if (browseDESKTOP(uri)) { + return true + } + + if (openSystemSpecific(uri.toString())) { + return true + } + + LOG.warn("failed to browse {}", uri) + return false + } + + fun open(file: File): Boolean { + if (openDESKTOP(file)) { + return true + } + + if (openSystemSpecific(file.path)) { + return true + } + + LOG.warn("failed to open {}", file.absolutePath) + return false + } + + fun edit(file: File): Boolean { + if (editDESKTOP(file)) { + return true + } + + if (openSystemSpecific(file.path)) { + return true + } + + LOG.warn("failed to edit {}", file.absolutePath) + return false + } + + private fun openSystemSpecific(what: String): Boolean { + if (SystemUtils.IS_OS_LINUX) { + if (isXDG() && runCommand("xdg-open", "%s", what)) { + return true + } + if (isKDE() && runCommand("kde-open", "%s", what)) { + return true + } + if (isGNOME() && runCommand("gnome-open", "%s", what)) { + return true + } + if (runCommand("kde-open", "%s", what)) { + return true + } + if (runCommand("gnome-open", "%s", what)) { + return true + } + } + + if (SystemUtils.IS_OS_MAC && runCommand("open", "%s", what)) { + return true + } + + if (SystemUtils.IS_OS_WINDOWS && runCommand("explorer", "%s", what)) { + return true + } + + return false + } + + private fun browseDESKTOP(uri: URI): Boolean { + return try { + if (!java.awt.Desktop.isDesktopSupported()) { + LOG.debug("Platform is not supported.") + return false + } + + if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.BROWSE)) { + LOG.debug("BROWSE is not supported.") + return false + } + + LOG.info("Trying to use Desktop.getDesktop().browse() with {}", uri.toString()) + java.awt.Desktop.getDesktop().browse(uri) + true + } catch (t: Throwable) { + LOG.error("Error using desktop browse.", t) + false + } + } + + private fun openDESKTOP(file: File): Boolean { + return try { + if (!java.awt.Desktop.isDesktopSupported()) { + LOG.debug("Platform is not supported.") + return false + } + + if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.OPEN)) { + LOG.debug("OPEN is not supported.") + return false + } + + LOG.info("Trying to use Desktop.getDesktop().open() with {}", file.toString()) + java.awt.Desktop.getDesktop().open(file) + true + } catch (t: Throwable) { + LOG.error("Error using desktop open.", t) + false + } + } + + private fun editDESKTOP(file: File): Boolean { + return try { + if (!java.awt.Desktop.isDesktopSupported()) { + LOG.debug("Platform is not supported.") + return false + } + + if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.EDIT)) { + LOG.debug("EDIT is not supported.") + return false + } + + LOG.info("Trying to use Desktop.getDesktop().edit() with {}", file) + java.awt.Desktop.getDesktop().edit(file) + true + } catch (t: Throwable) { + LOG.error("Error using desktop edit.", t) + false + } + } + + private fun runCommand(command: String, args: String, file: String): Boolean { + LOG.info("Trying to exec:\n cmd = {}\n args = {}\n %s = {}", command, args, file) + + val parts = prepareCommand(command, args, file) + + return try { + val p = Runtime.getRuntime().exec(parts) + if (p == null) { + false + } else { + try { + val retval = p.exitValue() + if (retval == 0) { + LOG.error("Process ended immediately.") + false + } else { + LOG.error("Process crashed.") + false + } + } catch (itse: IllegalThreadStateException) { + LOG.error("Process is running.") + true + } + } + } catch (e: IOException) { + LOG.error("Error running command.", e) + false + } + } + + private fun prepareCommand(command: String, args: String?, file: String): Array { + val parts = mutableListOf() + parts.add(command) + + args?.split(" ")?.forEach { s -> + parts.add(String.format(s, file).trim()) + } + + return parts.toTypedArray() + } + + private fun isXDG(): Boolean { + val xdgSessionId = System.getenv("XDG_SESSION_ID") + return !xdgSessionId.isNullOrEmpty() + } + + private fun isGNOME(): Boolean { + val gdmSession = System.getenv("GDMSESSION") + return gdmSession?.lowercase()?.contains("gnome") == true + } + + private fun isKDE(): Boolean { + val gdmSession = System.getenv("GDMSESSION") + return gdmSession?.lowercase()?.contains("kde") == true + } +} \ No newline at end of file diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 8a1153d0b..2a908c045 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -175,6 +175,7 @@ "openai", "free-trial", "anthropic", + "anthropic-vertexai", "cohere", "bedrock", "bedrockimport", @@ -187,9 +188,11 @@ "llama.cpp", "replicate", "gemini", + "gemini-vertexai", "lmstudio", "llamafile", "mistral", + "mistral-vertexai", "deepinfra", "groq", "fireworks", @@ -212,7 +215,8 @@ "moonshot", "siliconflow", "function-network", - "scaleway" + "scaleway", + "relace" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -251,12 +255,15 @@ "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)", + "### Nebius\nNebius AI platform is a cloud service for machine learning model inference and training. To get started, obtain an API key from the [Nebius console](https://console.nebius.ai/).", + "### Vertex AI\nVertex AI provides access to Google's foundation models and ML tools. To get started, enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", "### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)", "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)", "### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)", "### SiliconFlow\nTo get started with SiliconFlow, obtain your API key from [SiliconCloud](https://cloud.siliconflow.cn/account/ak). SiliconCloud provides cost-effective GenAI services based on excellent open source basic models.\n> [Models](https://siliconflow.cn/zh-cn/models)", "### Function Network offers private, affordable user-owned AI\nTo get started with Function Network, obtain your API key from [Function Network](https://www.function.network/join-waitlist). Function Network provides a variety of models for chat, completion, and embeddings.", - "### Scaleway\n Generative APIs are serverless endpoints for the most popular AI models.\nHosted in European data centers and priced competitively per million tokens used, models served by Scaleway are ideal for users requiring low latency, full data privacy, and 100% compliance with EU AI Act. To get access to the Scaleway Generative APIs, read the [Quickstart guide](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/) and get a [valid API key](https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/)." + "### Scaleway\n Generative APIs are serverless endpoints for the most popular AI models.\nHosted in European data centers and priced competitively per million tokens used, models served by Scaleway are ideal for users requiring low latency, full data privacy, and 100% compliance with EU AI Act. To get access to the Scaleway Generative APIs, read the [Quickstart guide](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/) and get a [valid API key](https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/).", + "### Relace\n Relace provides a fast apply model. To get started, obtain an API key from [here](https://app.relace.ai/settings/api-keys)." ], "type": "string" }, @@ -946,7 +953,10 @@ "gemini-1.5-flash", "gemini-1.5-flash-8b", "gemini-2.0-flash-exp", - "gemini-2.0-flash" + "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" ] } } @@ -1319,7 +1329,17 @@ "nvidia/Llama-3.1-Nemotron-70B-Instruct", "Qwen/Qwen2-VL-72B-Instruct", "TeleAI/TeleMM", - "deepseek-ai/DeepSeek-V2.5" + "deepseek-ai/DeepSeek-V2.5", + "deepseek-ai/deepseek-vl2", + "deepseek-ai/Janus-Pro-7B", + "deepseek-ai/DeepSeek-V3", + "deepseek-ai/DeepSeek-R1", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B", + "deepseek-ai/DeepSeek-R1-Distill-Llama-70B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", + "deepseek-ai/DeepSeek-R1-Distill-Llama-8B" ] } } @@ -2311,6 +2331,10 @@ "type": "string", "description": "Customize the query used to find Jira issues" }, + "maxResults": { + "type": "string", + "description": "The maximum number of issues that will be returned. Defaults to 50." + }, "apiVersion": { "type": "integer", "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property.", @@ -2837,11 +2861,11 @@ "description": "The name of your VertexAI project" }, "region": { - "description": "The region your VertexAI model is hosted in - typically central1", - "default": "central1" + "description": "The region your VertexAI model is hosted in - typically us-central1", + "default": "us-central1" }, "model": { - "default": "text-embedding-004" + "default": "text-embedding-005" } }, "required": ["projectId", "model", "region"] @@ -2859,6 +2883,7 @@ "bedrock", "cohere", "voyage", + "watsonx", "llm", "free-trial", "huggingface-tei" diff --git a/extensions/vscode/e2e/test-continue-yaml/config.yaml b/extensions/vscode/e2e/test-continue-yaml/config.yaml index 5de426a94..b905443e2 100644 --- a/extensions/vscode/e2e/test-continue-yaml/config.yaml +++ b/extensions/vscode/e2e/test-continue-yaml/config.yaml @@ -1,5 +1,6 @@ name: Test Config version: 0.0.1 +schema: v1 rules: - TEST_SYS_MSG diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index cbcebc34e..e8f7b966b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.3", + "version": "1.1.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.3", + "version": "1.1.13", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -99,17 +99,17 @@ }, "../../core": { "name": "@continuedev/core", - "version": "1.0.13", + "version": "1.1.0", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.620.1", - "@aws-sdk/client-sagemaker-runtime": "^3.621.0", - "@aws-sdk/credential-providers": "^3.620.1", + "@aws-sdk/client-bedrock-runtime": "^3.758.0", + "@aws-sdk/client-sagemaker-runtime": "^3.758.0", + "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.63", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", - "@continuedev/openai-adapters": "^1.0.10", + "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -171,7 +171,7 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", - "@types/diff": "^5.2.2", + "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 04b3aee59..b6d94af28 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.4", + "version": "1.1.13", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -52,6 +52,7 @@ "llama" ], "activationEvents": [ + "onUri", "onStartupFinished", "onView:continueGUIView" ], @@ -319,7 +320,7 @@ "group": "Continue" }, { - "command": "continue.focusContinueSessionId", + "command": "continue.focusContinueInput", "category": "Continue", "title": "Focus Continue Chat", "group": "Continue" @@ -594,7 +595,7 @@ "e2e:compile": "tsc -p ./tsconfig.e2e.json", "e2e:build": "npm --prefix ../../gui run build && npm run package", "e2e:create-storage": "mkdir -p ./e2e/storage", - "e2e:get-chromedriver": "extest get-chromedriver --storage ./e2e/storage", + "e2e:get-chromedriver": "CODE_VERSION=\"1.95.0\" extest get-chromedriver --storage ./e2e/storage", "e2e:get-vscode": "CODE_VERSION=\"1.95.0\" extest get-vscode --storage ./e2e/storage", "e2e:sign-vscode": "codesign --entitlements entitlements.plist --deep --force -s - './e2e/storage/Visual Studio Code.app'", "e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh", diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index cd4589b9c..6972ad9ff 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -5,11 +5,12 @@ 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 * as URI from "uri-js"; import * as vscode from "vscode"; -import * as URI from "uri-js"; import { executeGotoProvider } from "./autocomplete/lsp"; import { Repository } from "./otherExtensions/git"; +import { SecretStorage } from "./stubs/SecretStorage"; import { VsCodeIdeUtils } from "./util/ideUtils"; import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; import { VsCodeWebviewProtocol } from "./webviewProtocol"; @@ -28,7 +29,6 @@ import type { TerminalOptions, Thread, } from "core"; -import { SecretStorage } from "./stubs/SecretStorage"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; @@ -212,7 +212,7 @@ class VsCodeIde implements IDE { .showInformationMessage( "We'll only ask you to log in if using the free trial. To avoid this prompt, make sure to remove free trial models from your config.json", "Remove for me", - "Open config.json", + "Open Assistant configuration", ) .then((selection) => { if (selection === "Remove for me") { @@ -223,7 +223,7 @@ class VsCodeIde implements IDE { configJson.tabAutocompleteModel = undefined; return configJson; }); - } else if (selection === "Open config.json") { + } else if (selection === "Open Assistant configuration") { this.openFile(getConfigJsonPath()); } }); @@ -545,6 +545,7 @@ class VsCodeIde implements IDE { "-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 @@ -573,9 +574,51 @@ class VsCodeIde implements IDE { } async getSearchResults(query: string): Promise { - const results = []; + const results: string[] = []; for (const dir of await this.getWorkspaceDirs()) { - results.push(await this._searchDir(query, dir)); + const dirResults = await this._searchDir(query, dir); + + 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")); } return results.join("\n\n"); diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 497de3875..05e263117 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -1,9 +1,11 @@ import { CompletionProvider } from "core/autocomplete/CompletionProvider"; +import { processSingleLineCompletion } from "core/autocomplete/util/processSingleLineCompletion"; import { type AutocompleteInput, type AutocompleteOutcome, } from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; +import { startLocalOllama } from "core/util/ollamaHelper"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -21,17 +23,8 @@ import { stopStatusBarLoading, } from "./statusBar"; -import { startLocalOllama } from "core/util/ollamaHelper"; import type { IDE } from "core"; - -const Diff = require("diff"); - -interface DiffType { - count: number; - added: boolean; - removed: boolean; - value: string; -} +import { handleLLMError } from "../util/errorHandling"; interface VsCodeCompletionInput { document: vscode.TextDocument; @@ -40,19 +33,15 @@ interface VsCodeCompletionInput { } export class ContinueCompletionProvider - implements vscode.InlineCompletionItemProvider -{ + implements vscode.InlineCompletionItemProvider { private onError(e: any) { - let options = ["Documentation"]; - if (e.message.includes("Ollama may not be installed")) { - options.push("Download Ollama"); - } else if (e.message.includes("Ollama may not be running")) { - options = ["Start Ollama"]; // We want "Start" to be the only choice + if (handleLLMError(e)) { + return; } - - if (e.message.includes("Please sign in with GitHub")) { + let message = e.message; + if (message.includes("Please sign in with GitHub")) { showFreeTrialLoginMessage( - e.message, + message, this.configHandler.reloadConfig.bind(this.configHandler), () => { void this.webviewProtocol.request("openOnboardingCard", undefined); @@ -60,17 +49,13 @@ export class ContinueCompletionProvider ); return; } - vscode.window.showErrorMessage(e.message, ...options).then((val) => { + vscode.window.showErrorMessage(message, "Documentation").then((val) => { if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( "https://docs.continue.dev/features/tab-autocomplete", ), ); - } else if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - startLocalOllama(this.ide); } }); } @@ -103,7 +88,6 @@ export class ContinueCompletionProvider _lastShownCompletion: AutocompleteOutcome | undefined; - _lastVsCodeCompletionInput: VsCodeCompletionInput | undefined; public async provideInlineCompletionItems( document: vscode.TextDocument, @@ -128,28 +112,26 @@ export class ContinueCompletionProvider return null; } - // If the text at the range isn't a prefix of the intellisense text, - // no completion will be displayed, regardless of what we return - if ( - context.selectedCompletionInfo && - !context.selectedCompletionInfo.text.startsWith( - document.getText(context.selectedCompletionInfo.range), - ) - ) { - return null; - } - - let injectDetails: string | undefined = undefined; - - // The first time intellisense dropdown shows up, and the first choice is selected, - // we should not consider this. Only once user explicitly moves down the list - const newVsCodeInput = { - context, - document, - position, - }; const selectedCompletionInfo = context.selectedCompletionInfo; - this._lastVsCodeCompletionInput = newVsCodeInput; + + // This code checks if there is a selected completion suggestion in the given context and ensures that it is valid + // To improve the accuracy of suggestions it checks if the user has typed at least 4 characters + // This helps refine and filter out irrelevant autocomplete options + if (selectedCompletionInfo) { + const { text, range } = selectedCompletionInfo; + const typedText = document.getText(range); + + const typedLength = range.end.character - range.start.character; + + if (typedLength < 4) { + return null; + } + + if (!text.startsWith(typedText)) { + return null; + } + } + let injectDetails: string | undefined = undefined; try { const abortController = new AbortController(); @@ -264,54 +246,29 @@ export class ContinueCompletionProvider const isSingleLineCompletion = outcome.completion.split("\n").length <= 1; if (isSingleLineCompletion) { - const lastLineOfCompletionText = completionText.split("\n").pop(); + const lastLineOfCompletionText = completionText.split("\n").pop() || ""; const currentText = document .lineAt(startPos) .text.substring(startPos.character); - const diffs: DiffType[] = Diff.diffWords( - currentText, + + const result = processSingleLineCompletion( lastLineOfCompletionText, + currentText, + startPos.character ); - if (diffPatternMatches(diffs, ["+"])) { - // Just insert, we're already at the end of the line - } else if ( - diffPatternMatches(diffs, ["+", "="]) || - diffPatternMatches(diffs, ["+", "=", "+"]) - ) { - // The model repeated the text after the cursor to the end of the line - range = new vscode.Range( - startPos, - document.lineAt(startPos).range.end, - ); - } else if ( - diffPatternMatches(diffs, ["+", "-"]) || - diffPatternMatches(diffs, ["-", "+"]) - ) { - // We are midline and the model just inserted without repeating to the end of the line - // We want to move the cursor to the end of the line - // range = new vscode.Range( - // startPos, - // document.lineAt(startPos).range.end, - // ); - // // Find the last removed part of the diff - // const lastRemovedIndex = findLastIndex( - // diffs, - // (diff) => diff.removed === true, - // ); - // const lastRemovedContent = diffs[lastRemovedIndex].value; - // completionText += lastRemovedContent; - } else { - // Diff is too complicated, just insert the first added part of the diff - // This is the safe way to ensure that it is displayed - if (diffs[0]?.added) { - completionText = diffs[0].value; - } else { - // If the first part of the diff isn't an insertion, then the model is - // probably rewriting other parts of the line - // return undefined; - Let's assume it's simply an insertion - } + if (result === undefined) { + return undefined; } + + completionText = result.completionText; + if (result.range) { + range = new vscode.Range( + new vscode.Position(startPos.line, result.range.start), + new vscode.Position(startPos.line, result.range.end) + ); + } + } else { // Extend the range to the end of the line for multiline completions range = new vscode.Range(startPos, document.lineAt(startPos).range.end); @@ -358,26 +315,3 @@ export class ContinueCompletionProvider return true; } } - -type DiffPartType = "+" | "-" | "="; - -function diffPatternMatches( - diffs: DiffType[], - pattern: DiffPartType[], -): boolean { - if (diffs.length !== pattern.length) { - return false; - } - - for (let i = 0; i < diffs.length; i++) { - const diff = diffs[i]; - const diffPartType: DiffPartType = - !diff.added && !diff.removed ? "=" : diff.added ? "+" : "-"; - - if (diffPartType !== pattern[i]) { - return false; - } - } - - return true; -} diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 69b9b4d0f..d32f362dd 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -47,7 +47,7 @@ export class RecentlyEditedTracker { editedRange: Omit, ): Promise { - if (editedRange.uri.scheme === "output") { + if (editedRange.uri.scheme !== "file") { return; } @@ -83,7 +83,6 @@ export class RecentlyEditedTracker { RecentlyEditedTracker.maxRecentlyEditedRanges, ); } - } private insertDocument(uri: vscode.Uri): void { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index fa6b44c2a..de8f5cd1e 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,7 +1,12 @@ /* eslint-disable @typescript-eslint/naming-convention */ import * as os from "node:os"; -import { ContextMenuConfig, RangeInFileWithContents } from "core"; +import { + ContextMenuConfig, + ILLM, + ModelInstaller, + RangeInFileWithContents, +} from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -14,13 +19,13 @@ import readLastLines from "read-last-lines"; import * as vscode from "vscode"; import { - StatusBarStatus, getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, getStatusBarStatus, getStatusBarStatusFromQuickPickItemLabel, quickPickStatusText, setupStatusBar, + StatusBarStatus, } from "./autocomplete/statusBar"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; @@ -32,6 +37,7 @@ import { getMetaKeyLabel } from "./util/util"; import { VsCodeIde } from "./VsCodeIde"; import { LOCAL_DEV_DATA_VERSION } from "core/data/log"; +import { isModelInstaller } from "core/llm"; import { startLocalOllama } from "core/util/ollamaHelper"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; @@ -123,9 +129,20 @@ function getRangeInFileWithContents( return null; } - // adjust starting position to include indentation - const start = new vscode.Position(selection.start.line, 0); - const selectionRange = new vscode.Range(start, selection.end); + let selectionRange = new vscode.Range(selection.start, selection.end); + const document = editor.document; + // Select the context from the beginning of the selection start line to the selection start position + const beginningOfSelectionStartLine = selection.start.with(undefined, 0); + const textBeforeSelectionStart = document.getText( + new vscode.Range(beginningOfSelectionStartLine, selection.start), + ); + // If there are only whitespace before the start of the selection, include the indentation + if (textBeforeSelectionStart.trim().length === 0) { + selectionRange = selectionRange.with({ + start: beginningOfSelectionStartLine, + }); + } + const contents = editor.document.getText(selectionRange); return { @@ -266,9 +283,7 @@ async function processDiff( }); } - if (action === "accept") { - await sidebar.webviewProtocol.request("exitEditMode", undefined); - } + await sidebar.webviewProtocol.request("exitEditMode", undefined); } function waitForSidebarReady( @@ -341,13 +356,12 @@ const getCommandsMap: ( throw new Error("Config not loaded"); } - const defaultModelTitle = await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - ); - const modelTitle = - config.selectedModelByRole.edit?.title ?? defaultModelTitle; + config.selectedModelByRole.edit?.title ?? + (await sidebar.webviewProtocol.request( + "getDefaultModelTitle", + undefined, + )); void sidebar.webviewProtocol.request("incrementFtc", undefined); @@ -534,9 +548,26 @@ const getCommandsMap: ( return; } + const startFromCharZero = editor.selection.start.with(undefined, 0); + const document = editor.document; + let lastLine, lastChar; + // If the user selected onto a trailing line but didn't actually include any characters in it + // they don't want to include that line, so trim it off. + if (editor.selection.end.character === 0) { + // This is to prevent the rare case that the previous line gets selected when user + // is selecting nothing and the cursor is at the beginning of the line + if (editor.selection.end.line === editor.selection.start.line) { + lastLine = editor.selection.start.line; + } else { + lastLine = editor.selection.end.line - 1; + } + } else { + lastLine = editor.selection.end.line; + } + lastChar = document.lineAt(lastLine).range.end.character; + const endAtCharLast = new vscode.Position(lastLine, lastChar); const range = - args?.range ?? - new vscode.Range(editor.selection.start, editor.selection.end); + args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast); editDecorationManager.setDecoration(editor, range); @@ -813,7 +844,9 @@ const getCommandsMap: ( .stat(uri) ?.then((stat) => stat.type === vscode.FileType.Directory); if (isDirectory) { - for await (const fileUri of walkDirAsync(uri.toString(), ide)) { + for await (const fileUri of walkDirAsync(uri.toString(), ide, { + source: "vscode continue.selectFilesAsContext command", + })) { addEntireFileToContext( vscode.Uri.parse(fileUri), sidebar.webviewProtocol, @@ -954,12 +987,9 @@ const getCommandsMap: ( } } else if (selectedOption === "$(feedback) Give feedback") { vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); - } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + } else if (selectedOption === "$(comment) Open chat") { vscode.commands.executeCommand("continue.focusContinueInput"); - } else if ( - selectedOption === - "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" - ) { + } else if (selectedOption === "$(screen-full) Open full screen chat") { vscode.commands.executeCommand("continue.toggleFullScreen"); } else if (selectedOption === "$(question) Open help center") { focusGUI(); @@ -996,6 +1026,25 @@ const getCommandsMap: ( "continue.startLocalOllama": () => { startLocalOllama(ide); }, + "continue.installModel": async ( + modelName: string, + llmProvider: ILLM | undefined, + ) => { + try { + if (!isModelInstaller(llmProvider)) { + const msg = llmProvider + ? `LLM provider '${llmProvider.providerName}' does not support installing models` + : "Missing LLM Provider"; + throw new Error(msg); + } + await installModelWithProgress(modelName, llmProvider); + } catch (e) { + const message = e instanceof Error ? e.message : String(e); + vscode.window.showErrorMessage( + `Failed to install '${modelName}': ${message}`, + ); + } + }, }; }; @@ -1037,6 +1086,45 @@ const registerCopyBufferSpy = ( context.subscriptions.push(typeDisposable); }; +async function installModelWithProgress( + modelName: string, + modelInstaller: ModelInstaller, +) { + return vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Installing model '${modelName}'`, + cancellable: true, + }, + async (windowProgress, token) => { + let currentProgress: number = 0; + const progressWrapper = ( + details: string, + worked?: number, + total?: number, + ) => { + let increment = 0; + if (worked && total) { + const progressValue = Math.round((worked / total) * 100); + increment = progressValue - currentProgress; + currentProgress = progressValue; + } + windowProgress.report({ message: details, increment }); + }; + const abortController = new AbortController(); + token.onCancellationRequested(() => { + console.log(`Pulling ${modelName} model was cancelled`); + abortController.abort(); + }); + await modelInstaller.installModel( + modelName, + abortController.signal, + progressWrapper, + ); + }, + ); +} + export function registerAllCommands( context: vscode.ExtensionContext, ide: VsCodeIde, diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index ced48e03d..2e90de6e6 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -86,17 +86,8 @@ export class VerticalDiffHandler implements vscode.Disposable { } private async insertDeletionBuffer() { - // Don't remove trailing whitespace line const totalDeletedContent = this.deletionBuffer.join("\n"); - if ( - totalDeletedContent === "" && - this.currentLineIndex >= this.endLine + this.newLinesAdded && - this.insertedInCurrentBlock === 0 - ) { - return; - } - if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) { const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || []; @@ -359,7 +350,7 @@ export class VerticalDiffHandler implements vscode.Disposable { // Clear deletion buffer await this.insertDeletionBuffer(); - await this.reapplyWithMeyersDiff(diffLines); + await this.reapplyWithMyersDiff(diffLines); this.options.onStatusUpdate( "done", @@ -482,10 +473,10 @@ export class VerticalDiffHandler implements vscode.Disposable { /** * This method is used to apply diff decorations after the intiial stream. * This is to handle scenarios where we miscalculate the original diff blocks, - * and decide to follow up with a deterministic algorithm like Meyers Diff once + * and decide to follow up with a deterministic algorithm like Myers Diff once * we have received all of the diff lines. */ - async reapplyWithMeyersDiff(diffLines: DiffLine[]) { + async reapplyWithMyersDiff(diffLines: DiffLine[]) { // Diff is messed up without this delay. await new Promise((resolve) => setTimeout(resolve, 100)); @@ -504,23 +495,28 @@ export class VerticalDiffHandler implements vscode.Disposable { this.clearDecorations(); // Then, get our old/new file content based on the original lines + // We need the input to be "newline terminated" rather than + // newline separated, because myersDiff() would consider + // ["A"] => "A" and ["A", ""] => "A\n" to be the same single line. + // "A\n" and "A\n\n" are unambiguous. + // const oldFileContent = diffLines .filter((line) => line.type === "same" || line.type === "old") .map((line) => line.line) - .join("\n"); + .join("\n") + "\n"; const newFileContent = diffLines .filter((line) => line.type === "same" || line.type === "new") .map((line) => line.line) - .join("\n"); + .join("\n") + "\n"; const diffs = myersDiff(oldFileContent, newFileContent); - const meyersDiffLines = diffs.map((diff) => diff.line).join("\n"); + const myersDiffLines = diffs.map((diff) => diff.line).join("\n"); // Then, we insert our diff lines await this.editor.edit((editBuilder) => { - editBuilder.replace(this.range, meyersDiffLines), + editBuilder.replace(this.range, myersDiffLines), { undoStopAfter: false, undoStopBefore: false, diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index a62406b00..34c3345ac 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -9,6 +9,7 @@ import * as vscode from "vscode"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; +import { handleLLMError } from "../../util/errorHandling"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -230,7 +231,7 @@ export class VerticalDiffManager { ); if (!diffHandler) { - console.warn("Issue occured while creating new vertical diff handler"); + console.warn("Issue occurred while creating new vertical diff handler"); return; } @@ -255,7 +256,9 @@ export class VerticalDiffManager { this.enableDocumentChangeListener(); } catch (e) { this.disableDocumentChangeListener(); - vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + if (!handleLLMError(e)) { + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } } finally { vscode.commands.executeCommand( "setContext", @@ -353,7 +356,7 @@ export class VerticalDiffManager { ); if (!diffHandler) { - console.warn("Issue occured while creating new vertical diff handler"); + console.warn("Issue occurred while creating new vertical diff handler"); return undefined; } @@ -446,7 +449,9 @@ export class VerticalDiffManager { return `${prefix}${streamedLines.join("\n")}${suffix}`; } catch (e) { this.disableDocumentChangeListener(); - vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + if (!handleLLMError(e)) { + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } return undefined; } finally { vscode.commands.executeCommand( diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 8953c91a0..a4a90afd3 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -28,6 +28,7 @@ import { registerAllPromptFilesCompletionProviders } from "../lang-server/prompt import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { QuickEdit } from "../quickEdit/QuickEditQuickPick"; import { setupRemoteConfigSync } from "../stubs/activation"; +import { UriEventHandler } from "../stubs/uriHandler"; import { getControlPlaneSessionInfo, WorkOsAuthProvider, @@ -55,10 +56,11 @@ export class VsCodeExtension { private battery: Battery; private workOsAuthProvider: WorkOsAuthProvider; private fileSearch: FileSearch; + private uriHandler = new UriEventHandler(); constructor(context: vscode.ExtensionContext) { // Register auth provider - this.workOsAuthProvider = new WorkOsAuthProvider(context); + this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler); this.workOsAuthProvider.refreshSessions(); context.subscriptions.push(this.workOsAuthProvider); @@ -158,7 +160,7 @@ export class VsCodeExtension { }); this.configHandler.onConfigUpdate( - async ({ config: newConfig, errors, configLoadInterrupted }) => { + async ({ config: newConfig, configLoadInterrupted }) => { if (configLoadInterrupted) { // Show error in status bar setupStatusBar(undefined, undefined, true); @@ -193,6 +195,41 @@ export class VsCodeExtension { ), ); + // Handle uri events + this.uriHandler.event((uri) => { + const queryParams = new URLSearchParams(uri.query); + let profileId = queryParams.get("profile_id"); + let orgId = queryParams.get("org_id"); + + if (orgId) { + if (orgId === "null") { + 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; + } + this.core.invoke("didChangeSelectedOrg", { + id: orgId, + profileId, + }); + } else { + this.core.invoke("didChangeSelectedOrg", { + id: orgId, + }); + } + } else if (profileId) { + if (profileId === "null") { + profileId = null; + } + this.core.invoke("didChangeSelectedProfile", { + id: profileId, + }); + } + }); + // Battery this.battery = new Battery(); context.subscriptions.push(this.battery); @@ -273,6 +310,12 @@ export class VsCodeExtension { }); }); + vscode.workspace.onDidCloseTextDocument(async (event) => { + this.core.invoke("files/closed", { + uris: [event.uri.toString()], + }); + }); + vscode.workspace.onDidCreateFiles(async (event) => { this.core.invoke("files/created", { uris: event.files.map((uri) => uri.toString()), diff --git a/extensions/vscode/src/quickEdit/EditDecorationManager.ts b/extensions/vscode/src/quickEdit/EditDecorationManager.ts index 04e27d7ee..544287483 100644 --- a/extensions/vscode/src/quickEdit/EditDecorationManager.ts +++ b/extensions/vscode/src/quickEdit/EditDecorationManager.ts @@ -6,7 +6,10 @@ class EditDecorationManager { constructor(context: vscode.ExtensionContext) { this.decorationType = vscode.window.createTextEditorDecorationType({ backgroundColor: new vscode.ThemeColor( - "editor.inactiveSelectionBackground", + // "editor.selectionHighlightBackground" requires partial transparency. + // This ensures the highlight does not completely obscure the selection, + // making it useful for repurposing here. + "editor.selectionHighlightBackground", ), isWholeLine: true, }); diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 8f0e00c8c..03d9b2174 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -15,13 +15,13 @@ import { ExtensionContext, ProgressLocation, Uri, - UriHandler, window, workspace, } from "vscode"; import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; import { SecretStorage } from "./SecretStorage"; +import { UriEventHandler } from "./uriHandler"; const AUTH_NAME = "Continue"; @@ -35,11 +35,6 @@ const controlPlaneEnv = getControlPlaneEnvSync( const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`; -class UriEventHandler extends EventEmitter implements UriHandler { - public handleUri(uri: Uri) { - this.fire(uri); - } -} // Function to generate a random string of specified length function generateRandomString(length: number): string { const possibleCharacters = @@ -83,13 +78,15 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { string, { promise: Promise; cancel: EventEmitter } >(); - private _uriHandler = new UriEventHandler(); private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes private secretStorage: SecretStorage; - constructor(private readonly context: ExtensionContext) { + constructor( + private readonly context: ExtensionContext, + private readonly _uriHandler: UriEventHandler, + ) { this._disposable = Disposable.from( authentication.registerAuthenticationProvider( controlPlaneEnv.AUTH_TYPE, @@ -169,19 +166,10 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { } get ideRedirectUri() { - if ( - env.uriScheme === "vscode-insiders" || - env.uriScheme === "vscode" || - env.uriScheme === "code-oss" - ) { - // We redirect to a page that says "you can close this page", and that page finishes the redirect - const url = new URL(controlPlaneEnv.APP_URL); - url.pathname = `/auth/${env.uriScheme}-redirect`; - return url.toString(); - } - const publisher = this.context.extension.packageJSON.publisher; - const name = this.context.extension.packageJSON.name; - return `${env.uriScheme}://${publisher}.${name}`; + // We redirect to a page that says "you can close this page", and that page finishes the redirect + const url = new URL(controlPlaneEnv.APP_URL); + url.pathname = `/auth/${env.uriScheme}-redirect`; + return url.toString(); } public static useOnboardingUri: boolean = false; diff --git a/extensions/vscode/src/stubs/uriHandler.ts b/extensions/vscode/src/stubs/uriHandler.ts new file mode 100644 index 000000000..cc324f856 --- /dev/null +++ b/extensions/vscode/src/stubs/uriHandler.ts @@ -0,0 +1,10 @@ +import * as vscode from "vscode"; + +export class UriEventHandler + extends vscode.EventEmitter + implements vscode.UriHandler +{ + public handleUri(uri: vscode.Uri) { + this.fire(uri); + } +} diff --git a/extensions/vscode/src/util/FileSearch.ts b/extensions/vscode/src/util/FileSearch.ts index c6707fa51..a1f419e73 100644 --- a/extensions/vscode/src/util/FileSearch.ts +++ b/extensions/vscode/src/util/FileSearch.ts @@ -1,5 +1,6 @@ import { IDE } from "core"; import { walkDirs } from "core/indexing/walkDir"; +import { deduplicateArray, splitCamelCaseAndNonAlphaNumeric } from "core/util"; // @ts-ignore import MiniSearch from "minisearch"; import * as vscode from "vscode"; @@ -17,6 +18,7 @@ export class FileSearch { private miniSearch = new MiniSearch({ fields: ["relativePath", "id"], storeFields: ["relativePath", "id"], + tokenize: text => deduplicateArray(MiniSearch.getDefault('tokenize')(text).concat(splitCamelCaseAndNonAlphaNumeric(text)), (a, b) => a === b), searchOptions: { prefix: true, fuzzy: 2, @@ -24,7 +26,9 @@ export class FileSearch { }, }); private async initializeFileSearchState() { - const results = await walkDirs(this.ide); + const results = await walkDirs(this.ide, { + source: "file search initialization", + }); this.miniSearch.addAll( results.flat().map((uri) => ({ id: uri, diff --git a/extensions/vscode/src/util/errorHandling.ts b/extensions/vscode/src/util/errorHandling.ts new file mode 100644 index 000000000..de68f0ce2 --- /dev/null +++ b/extensions/vscode/src/util/errorHandling.ts @@ -0,0 +1,49 @@ +import * as vscode from "vscode"; + +function supportSpecialHandling(error: any): boolean { + let message: string | undefined = error.message; + return message !== undefined && message.toLowerCase().includes("ollama"); +} + +/** + * @param error Handles common LLM errors. Currently only handles Ollama-related errors. + * @returns true if error is handled, false otherwise + */ +export function handleLLMError(error: any): boolean { + if (!supportSpecialHandling(error)) { + return false; + } + let message: string = error.message; + let options: string[] | undefined; + let modelName = undefined; + if (message.includes("Ollama may not be installed")) { + options = ["Download Ollama"]; + } else if (message.includes("Ollama may not be running")) { + options = ["Start Ollama"]; // We want "Start" to be the only choice + } else if (message.includes("ollama run") && error.llm) { + //extract model name from error message matching the pattern "ollama run " + modelName = message.match(/`ollama run (.*)`/)?.[1]; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + options = [`Install Model`]; + } + if (options === undefined) { + console.log("Found an unhandled Ollama error: ", message); + return false; + } + + vscode.window.showErrorMessage(message, ...options).then((val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } else if (val === "Install Model" && error.llm) { + //Eventually, we might be able to support installing models for other LLM providers than Ollama + vscode.commands.executeCommand( + "continue.installModel", + modelName, + error.llm, + ); + } + }); + return true; +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 14854f1c3..0d58532ae 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -7,6 +7,7 @@ import * as vscode from "vscode"; import { IMessenger } from "../../../core/protocol/messenger"; +import { handleLLMError } from "./util/errorHandling"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol @@ -86,31 +87,12 @@ export class VsCodeWebviewProtocol respond({ done: true, content: response, status: "success" }); } } catch (e: any) { - let message = e.message; - //Intercept Ollama errors for special handling - if (message.includes("Ollama may not")) { - const options = []; - if (message.includes("be installed")) { - options.push("Download Ollama"); - } else if (message.includes("be running")) { - options.push("Start Ollama"); - } - if (options.length > 0) { - // Respond without an error, so the UI doesn't show the error component - respond({ done: true, status: "error" }); - // Show native vscode error message instead, with options to download/start Ollama - vscode.window.showErrorMessage(e.message, ...options).then(async (val) => { - if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - vscode.commands.executeCommand("continue.startLocalOllama"); - } - }); - return; - } + if (handleLLMError(e)) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); } - - respond({ done: true, error: e.message, status: "error" }); + let message = e.message; + respond({ done: true, error: message, status: "error" }); const stringified = JSON.stringify({ msg }, null, 2); console.error( diff --git a/gui/package-lock.json b/gui/package-lock.json index 74273c5aa..b0918360d 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.63", "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -46,6 +46,7 @@ "react-switch": "^7.0.0", "react-syntax-highlighter": "^15.5.0", "react-tooltip": "^5.18.0", + "redux-logger": "^3.0.6", "redux-persist": "^6.0.0", "redux-persist-transform-filter": "^0.0.22", "redux-thunk": "^3.1.0", @@ -79,6 +80,7 @@ "@types/react-dom": "^18.3.1", "@types/react-router-dom": "^5.3.3", "@types/react-syntax-highlighter": "^15.5.7", + "@types/redux-logger": "^3.0.13", "@types/styled-components": "^5.1.26", "@vitejs/plugin-react-swc": "^3.7.0", "@vitest/coverage-v8": "^2.1.3", @@ -100,17 +102,17 @@ }, "../core": { "name": "@continuedev/core", - "version": "1.0.13", + "version": "1.1.0", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/client-bedrock-runtime": "^3.620.1", - "@aws-sdk/client-sagemaker-runtime": "^3.621.0", - "@aws-sdk/credential-providers": "^3.620.1", + "@aws-sdk/client-bedrock-runtime": "^3.758.0", + "@aws-sdk/client-sagemaker-runtime": "^3.758.0", + "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.63", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", - "@continuedev/openai-adapters": "^1.0.10", + "@continuedev/openai-adapters": "^1.0.18", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -172,7 +174,7 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", - "@types/diff": "^5.2.2", + "@types/diff": "^7.0.1", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", @@ -231,11 +233,13 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", - "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", + "version": "7.26.2", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", + "integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==", + "license": "MIT", "dependencies": { - "@babel/highlight": "^7.24.7", + "@babel/helper-validator-identifier": "^7.25.9", + "js-tokens": "^4.0.0", "picocolors": "^1.0.0" }, "engines": { @@ -407,17 +411,19 @@ } }, "node_modules/@babel/helper-string-parser": { - "version": "7.24.8", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.8.tgz", - "integrity": "sha512-pO9KhhRcuUyGnJWwyEgnRJTSIZHiT+vMD0kPeD+so0l7mxkMT19g3pjY9GTnHySck/hDzq+dtW/4VgnMkippsQ==", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz", + "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==", + "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", - "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", + "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", + "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -432,38 +438,26 @@ } }, "node_modules/@babel/helpers": { - "version": "7.25.6", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.25.6.tgz", - "integrity": "sha512-Xg0tn4HcfTijTwfDwYlvVCl43V6h4KyVVX2aEm4qdO/PC6L2YvzLHFdmxhoeSA3eslcE6+ZVXHgWwopXYLNq4Q==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.10.tgz", + "integrity": "sha512-UPYc3SauzZ3JGgj87GgZ89JVdC5dj0AoetR5Bw6wj4niittNyFh6+eOGonYvJ1ao6B8lEa3Q3klS7ADZ53bc5g==", + "license": "MIT", "peer": true, "dependencies": { - "@babel/template": "^7.25.0", - "@babel/types": "^7.25.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/highlight": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", - "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", - "dependencies": { - "@babel/helper-validator-identifier": "^7.24.7", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0", - "picocolors": "^1.0.0" + "@babel/template": "^7.26.9", + "@babel/types": "^7.26.10" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.25.6", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.6.tgz", - "integrity": "sha512-trGdfBdbD0l1ZPmcJ83eNxB9rbEax4ALFTF7fN386TMYbeCQbyme5cOEXQhbGXKebwGaB/J52w1mrklMcbgy6Q==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.10.tgz", + "integrity": "sha512-6aQR2zGE/QFi8JpDLjUZEPYOs7+mhKXm86VaKFiLP35JQwQb6bwUE+XbvkH0EptsYhbNBSUGaUBLKqxH1xSgsA==", + "license": "MIT", "dependencies": { - "@babel/types": "^7.25.6" + "@babel/types": "^7.26.10" }, "bin": { "parser": "bin/babel-parser.js" @@ -487,9 +481,10 @@ } }, "node_modules/@babel/runtime": { - "version": "7.25.6", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.25.6.tgz", - "integrity": "sha512-VBj9MYyDb9tuLq7yzqjgzt6Q+IBQLrGZfdjOekyEirZPHxXWoTSGUTMrpsfi58Up73d13NfYLv8HT9vmznjzhQ==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.10.tgz", + "integrity": "sha512-2WJMeRQPHKSPemqk/awGrAiuFfzBmOIPXKizAsVhWH9YJqLZ0H+HS4c8loHGgW6utJ3E/ejXQUsiGaQy2NZ9Fw==", + "license": "MIT", "dependencies": { "regenerator-runtime": "^0.14.0" }, @@ -498,13 +493,14 @@ } }, "node_modules/@babel/template": { - "version": "7.25.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.0.tgz", - "integrity": "sha512-aOOgh1/5XzKvg1jvVz7AVrx2piJ2XBi227DHmbY6y+bM9H2FlN+IfecYu4Xl0cNiiVejlsCri89LUsbj8vJD9Q==", + "version": "7.26.9", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.26.9.tgz", + "integrity": "sha512-qyRplbeIpNZhmzOysF/wFMuP9sctmh2cFzRAZOn1YapxBsE1i9bJIY586R/WBLfLcmcBlM8ROBiQURnnNy+zfA==", + "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.24.7", - "@babel/parser": "^7.25.0", - "@babel/types": "^7.25.0" + "@babel/code-frame": "^7.26.2", + "@babel/parser": "^7.26.9", + "@babel/types": "^7.26.9" }, "engines": { "node": ">=6.9.0" @@ -528,13 +524,13 @@ } }, "node_modules/@babel/types": { - "version": "7.25.6", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.6.tgz", - "integrity": "sha512-/l42B1qxpG6RdfYf343Uw1vmDjeNhneUXtzhojE7pDgfpEypmRhI6j1kr17XCVv4Cgl9HdAiQY2x0GwKm7rWCw==", + "version": "7.26.10", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.10.tgz", + "integrity": "sha512-emqcG3vHrpxUKTrxcblR36dcrcoRDvKmnL/dCL6ZsHaShW80qxCAcNhzQZrpeM765VzEos+xOi4s+r4IXzTwdQ==", + "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^7.24.8", - "@babel/helper-validator-identifier": "^7.24.7", - "to-fast-properties": "^2.0.0" + "@babel/helper-string-parser": "^7.25.9", + "@babel/helper-validator-identifier": "^7.25.9" }, "engines": { "node": ">=6.9.0" @@ -555,9 +551,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.52", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.52.tgz", - "integrity": "sha512-x0m4bcQpjHrrv95cq5tsen4Hb6yKCVGn+NeojyzNQYnRD0If/On+ATgX78uXtQtZxsdO4ip73HHCyQlA0O3ZyQ==", + "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==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -3067,6 +3063,15 @@ "@types/react": "*" } }, + "node_modules/@types/redux-logger": { + "version": "3.0.13", + "resolved": "https://registry.npmjs.org/@types/redux-logger/-/redux-logger-3.0.13.tgz", + "integrity": "sha512-jylqZXQfMxahkuPcO8J12AKSSCQngdEWQrw7UiLUJzMBcv1r4Qg77P6mjGLjM27e5gFQDPD8vwUMJ9AyVxFSsg==", + "dev": true, + "dependencies": { + "redux": "^5.0.0" + } + }, "node_modules/@types/responselike": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz", @@ -3509,17 +3514,6 @@ "node": ">=8" } }, - "node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", @@ -4197,27 +4191,6 @@ "node": ">=12" } }, - "node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/chalk/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "engines": { - "node": ">=0.8.0" - } - }, "node_modules/character-entities": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", @@ -4309,19 +4282,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" - }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -4583,6 +4543,11 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/deep-diff": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/deep-diff/-/deep-diff-0.3.8.tgz", + "integrity": "sha512-yVn6RZmHiGnxRKR9sJb3iVV2XTF1Ghh2DiWRZ3dMnGc43yUdWWF/kX6lQyk3+P84iprfWKU/8zFTrlkvtFm1ug==" + }, "node_modules/deep-eql": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", @@ -10204,6 +10169,14 @@ "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==" }, + "node_modules/redux-logger": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/redux-logger/-/redux-logger-3.0.6.tgz", + "integrity": "sha512-JoCIok7bg/XpqA1JqCqXFypuqBbQzGQySrhFzewB7ThcnysTO30l4VCst86AuB9T9tuT03MAA56Jw2PNhRSNCg==", + "dependencies": { + "deep-diff": "^0.3.5" + } + }, "node_modules/redux-persist": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/redux-persist/-/redux-persist-6.0.0.tgz", @@ -11634,14 +11607,6 @@ "integrity": "sha512-bu9oCYYWC1iRjx+3UnAjqCsfrWNZV1ghNQf49b3w5xE8J/tNShHTzp5syWJfwGH+pxUgTTLUnzHnfuydW7wmbg==", "dev": true }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", - "engines": { - "node": ">=4" - } - }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", diff --git a/gui/package.json b/gui/package.json index 9a9b8d737..6724bd757 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.63", "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -54,6 +54,7 @@ "react-switch": "^7.0.0", "react-syntax-highlighter": "^15.5.0", "react-tooltip": "^5.18.0", + "redux-logger": "^3.0.6", "redux-persist": "^6.0.0", "redux-persist-transform-filter": "^0.0.22", "redux-thunk": "^3.1.0", @@ -87,6 +88,7 @@ "@types/react-dom": "^18.3.1", "@types/react-router-dom": "^5.3.3", "@types/react-syntax-highlighter": "^15.5.7", + "@types/redux-logger": "^3.0.13", "@types/styled-components": "^5.1.26", "@vitejs/plugin-react-swc": "^3.7.0", "@vitest/coverage-v8": "^2.1.3", diff --git a/gui/src/components/AddModelButtonSubtext.tsx b/gui/src/components/AddModelButtonSubtext.tsx index 0ebb2ed9d..aa7ef99b5 100644 --- a/gui/src/components/AddModelButtonSubtext.tsx +++ b/gui/src/components/AddModelButtonSubtext.tsx @@ -12,7 +12,7 @@ function AddModelButtonSubtext() { className="cursor-pointer underline" onClick={() => ideMessenger.post("config/openProfile", { - profileId: "local", + profileId: undefined, }) } > diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx new file mode 100644 index 000000000..c546becd4 --- /dev/null +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -0,0 +1,61 @@ +import { ChevronRightIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { Button, ButtonSubtext } from ".."; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice"; +import { LocalStorageKey, setLocalStorage } from "../../util/localStorage"; +import { ReusableCard } from "../ReusableCard"; + +export function ExploreHubCard() { + const dispatch = useAppDispatch(); + const isOpen = useAppSelector((state) => state.ui.isExploreDialogOpen); + const ideMessenger = useContext(IdeMessengerContext); + + if (!isOpen) return null; + + return ( + { + setLocalStorage(LocalStorageKey.IsExploreDialogOpen, false); + setLocalStorage(LocalStorageKey.HasDismissedExploreDialog, true); + return dispatch(setIsExploreDialogOpen(false)); + }} + > +
+

Create Your Own Assistant

+ +

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

+ + + + { + ideMessenger.request("controlPlane/openUrl", { + path: "/new?type=assistant", + orgSlug: undefined, + }); + }} + > +
+ Or, create your own assistant from scratch + +
+
+
+
+ ); +} diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index a10fc7b6e..b098bda70 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -204,17 +204,21 @@ const Layout = () => { ); const isInEditMode = useAppSelector(selectIsInEditMode); - useWebviewListener("exitEditMode", async () => { - if (!isInEditMode) { - return; - } - dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - dispatch(exitEditMode()); - }); + useWebviewListener( + "exitEditMode", + async () => { + if (!isInEditMode) { + return; + } + dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + dispatch(exitEditMode()); + }, + [isInEditMode], + ); useEffect(() => { const handleKeyDown = (event: any) => { diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index f48e2939d..a4baa9a1e 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -1,20 +1,9 @@ -import * as Tabs from "./tabs"; -import { TabTitle, OnboardingCardTabs } from "./components/OnboardingCardTabs"; -import { XMarkIcon } from "@heroicons/react/24/outline"; -import styled from "styled-components"; -import { CloseButton, defaultBorderRadius, vscInputBackground } from "../"; -import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; -import { useOnboardingCard } from "./hooks/useOnboardingCard"; import { useAppSelector } from "../../redux/hooks"; - -const StyledCard = styled.div` - margin: auto; - border-radius: ${defaultBorderRadius}; - background-color: ${vscInputBackground}; - box-shadow: - 0 20px 25px -5px rgb(0 0 0 / 0.1), - 0 8px 10px -6px rgb(0 0 0 / 0.1); -`; +import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import { ReusableCard } from "../ReusableCard"; +import { OnboardingCardTabs, TabTitle } from "./components/OnboardingCardTabs"; +import { useOnboardingCard } from "./hooks/useOnboardingCard"; +import * as Tabs from "./tabs"; export interface OnboardingCardState { show?: boolean; @@ -47,20 +36,16 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { } return ( - onboardingCard.close()} + testId="onboarding-card" > - {!isDialog && !!config.models.length && ( - onboardingCard.close()}> - - - )} -
{renderTabContent()}
-
+ {renderTabContent()} + ); } diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index a48845c44..63d2c4f32 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -1,23 +1,12 @@ -import { XMarkIcon } from "@heroicons/react/24/outline"; import { useState } from "react"; -import styled from "styled-components"; -import { CloseButton, defaultBorderRadius, vscInputBackground } from "../.."; +import { useAppSelector } from "../../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; import Alert from "../../gui/Alert"; +import { ReusableCard } from "../../ReusableCard"; import { TabTitle } from "../components/OnboardingCardTabs"; import { useOnboardingCard } from "../hooks"; import OnboardingLocalTab from "../tabs/OnboardingLocalTab"; import MainTab from "./tabs/main"; -import { useAppSelector } from "../../../redux/hooks"; - -const StyledCard = styled.div` - margin: auto; - border-radius: ${defaultBorderRadius}; - background-color: ${vscInputBackground}; - box-shadow: - 0 20px 25px -5px rgb(0 0 0 / 0.1), - 0 8px 10px -6px rgb(0 0 0 / 0.1); -`; export interface OnboardingCardState { show?: boolean; @@ -31,44 +20,38 @@ interface OnboardingCardProps { export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { const onboardingCard = useOnboardingCard(); const config = useAppSelector((store) => store.config.config); + const [currentTab, setCurrentTab] = useState<"main" | "local">("main"); if (getLocalStorage("onboardingStatus") === undefined) { setLocalStorage("onboardingStatus", "Started"); } - const [currentTab, setCurrentTab] = useState<"main" | "local">("main"); - return ( - - {!isDialog && !!config.models.length && ( - onboardingCard.close()}> - - - )} -
-
- {currentTab === "main" ? ( - setCurrentTab("local")} - isDialog={isDialog} - /> - ) : ( -
- - By choosing this option, Continue will be configured by a local{" "} - config.yaml file. If you're just looking to use - Ollama and still want to manage your configuration through - Continue, click{" "} - setCurrentTab("main")}> - here - - - - -
- )} -
+ onboardingCard.close()} + > +
+ {currentTab === "main" ? ( + setCurrentTab("local")} + isDialog={isDialog} + /> + ) : ( +
+ + By choosing this option, Continue will be configured by a local{" "} + config.yaml file. If you're just looking to use + Ollama and still want to manage your configuration through + Continue, click{" "} + setCurrentTab("main")}> + here + + + +
+ )}
- +
); } diff --git a/gui/src/components/PageHeader.tsx b/gui/src/components/PageHeader.tsx index 22755926e..d37d82e6f 100644 --- a/gui/src/components/PageHeader.tsx +++ b/gui/src/components/PageHeader.tsx @@ -4,26 +4,36 @@ export interface PageHeaderProps { onTitleClick?: () => void; title?: string; rightContent?: React.ReactNode; + showBorder?: boolean; } export default function PageHeader({ onTitleClick, title, rightContent, + showBorder, }: PageHeaderProps) { return ( -
-
+
+
{title && ( -
- - - {title} - -
+ <> +
+ + + {title} + +
+ )}
{rightContent}
diff --git a/gui/src/components/ReusableCard.tsx b/gui/src/components/ReusableCard.tsx new file mode 100644 index 000000000..2eb2c483d --- /dev/null +++ b/gui/src/components/ReusableCard.tsx @@ -0,0 +1,42 @@ +import { XMarkIcon } from "@heroicons/react/24/outline"; +import styled from "styled-components"; +import { CloseButton, defaultBorderRadius, vscInputBackground } from "."; + +const StyledCard = styled.div` + margin: auto; + border-radius: ${defaultBorderRadius}; + background-color: ${vscInputBackground}; + box-shadow: + 0 20px 25px -5px rgb(0 0 0 / 0.1), + 0 8px 10px -6px rgb(0 0 0 / 0.1); +`; + +interface ReusableCardProps { + children: React.ReactNode; + showCloseButton?: boolean; + onClose?: () => void; + className?: string; + testId?: string; +} + +export function ReusableCard({ + children, + showCloseButton, + onClose, + className = "", + testId, +}: ReusableCardProps) { + return ( + + {showCloseButton && ( + + + + )} +
{children}
+
+ ); +} diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index b395db076..102d0151d 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -9,9 +9,9 @@ import { selectUIConfig } from "../../redux/slices/configSlice"; import { deleteMessage } from "../../redux/slices/sessionSlice"; import { getFontSize } from "../../util"; import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import Reasoning from "./Reasoning"; import ResponseActions from "./ResponseActions"; import ThinkingIndicator from "./ThinkingIndicator"; -import Reasoning from "./Reasoning"; interface StepContainerProps { item: ChatHistoryItem; @@ -36,7 +36,9 @@ export default function StepContainer(props: StepContainerProps) { ); const uiConfig = useAppSelector(selectUIConfig); - const hideActionSpace = historyItemAfterThis?.message.role === "assistant"; + const hideActionSpace = + historyItemAfterThis?.message.role === "assistant" || + historyItemAfterThis?.message.role === "thinking"; const hideActions = hideActionSpace || (isStreaming && props.isLast); // const isStepAheadOfCurCheckpoint = @@ -92,7 +94,7 @@ export default function StepContainer(props: StepContainerProps) { ) : ( <> - + state.tabs.tabs); - useEffect(() => { - console.log("session", currentSession); - }, [currentSession.id]); - // Simple UUID generator for our needs const generateId = useCallback(() => { return Date.now().toString(36) + Math.random().toString(36).substring(2); diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index ace2ae991..d948dc288 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -6,6 +6,8 @@ import styled from "styled-components"; import { defaultBorderRadius, lightGray, + vscButtonBackground, + vscButtonForeground, vscForeground, vscInputBackground, } from ".."; @@ -46,14 +48,15 @@ const StyledDiv = styled.div<{ isHidden?: boolean }>` } `; -const EnterButton = styled.button` +const EnterButton = styled.button<{ isPrimary?: boolean }>` all: unset; padding: 2px 4px; display: flex; align-items: center; - background-color: ${lightGray}33; + background-color: ${(props) => + props.isPrimary ? vscButtonBackground : lightGray + "33"}; border-radius: ${defaultBorderRadius}; - color: ${vscForeground}; + color: ${(props) => (props.isPrimary ? vscButtonForeground : vscForeground)}; cursor: pointer; :disabled { @@ -79,6 +82,7 @@ interface InputToolbarProps { activeKey: string | null; toolbarOptions?: ToolbarOptions; disabled?: boolean; + isMainInput?: boolean; } function InputToolbar(props: InputToolbarProps) { @@ -207,6 +211,7 @@ function InputToolbar(props: InputToolbarProps) { )} { if (props.onEnter) { diff --git a/gui/src/components/mainInput/ThinkingBlockPeek.tsx b/gui/src/components/mainInput/ThinkingBlockPeek.tsx new file mode 100644 index 000000000..851635230 --- /dev/null +++ b/gui/src/components/mainInput/ThinkingBlockPeek.tsx @@ -0,0 +1,177 @@ +// src/components/ThinkingBlockPeek.tsx +import { ChevronDownIcon } from "@heroicons/react/24/outline"; +import { ChevronUpIcon } from "@heroicons/react/24/solid"; +import { ChatHistoryItem } from "core"; +import { useEffect, useState } from "react"; +import styled from "styled-components"; +import { defaultBorderRadius, lightGray, vscBackground } from ".."; +import { getFontSize } from "../../util"; +import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; + +const SpoilerButton = styled.div` + background-color: ${vscBackground}; + width: fit-content; + margin: 8px 6px 0px 2px; + font-size: ${getFontSize() - 2}px; + border: 0.5px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 4px 8px; + color: ${lightGray}; + cursor: pointer; + box-shadow: + 0 4px 6px rgba(0, 0, 0, 0.1), + 0 1px 3px rgba(0, 0, 0, 0.08); + transition: box-shadow 0.3s ease; + + &:hover { + box-shadow: + 0 6px 8px rgba(0, 0, 0, 0.15), + 0 3px 6px rgba(0, 0, 0, 0.1); + } +`; + +const ButtonContent = styled.div` + display: flex; + align-items: center; + gap: 6px; +`; + +export const ThinkingText = styled.span` + position: relative; + padding-right: 12px; + + &:after { + content: "..."; + position: absolute; + animation: ellipsis 1s steps(4, end) infinite; + width: 0px; + display: inline-block; + overflow: hidden; + } + + @keyframes ellipsis { + 0%, + 100% { + width: 0px; + } + 33% { + width: 8px; + } + 66% { + width: 16px; + } + 90% { + width: 24px; + } + } +`; + +const MarkdownWrapper = styled.div` + & > div > *:first-child { + margin-top: 0 !important; + } +`; + +interface ThinkingBlockPeekProps { + content: string; + redactedThinking?: string; + index: number; + prevItem: ChatHistoryItem | null; + inProgress?: boolean; + signature?: string; + tokens?: number; +} + +function ThinkingBlockPeek({ + content, + redactedThinking, + index, + prevItem, + inProgress, + signature, + tokens, +}: ThinkingBlockPeekProps) { + const [open, setOpen] = useState(false); + const [startTime, setStartTime] = useState(null); + const [elapsedTime, setElapsedTime] = useState(""); + + const duplicateRedactedThinkingBlock = + prevItem && + prevItem.message.role === "thinking" && + redactedThinking && + prevItem.message.redactedThinking; + + useEffect(() => { + if (inProgress) { + setStartTime(Date.now()); + setElapsedTime(""); + } else if (startTime) { + const endTime = Date.now(); + const diff = endTime - startTime; + const diffString = `${(diff / 1000).toFixed(1)}s`; + setElapsedTime(diffString); + } + }, [inProgress]); + + return duplicateRedactedThinkingBlock ? null : ( +
+
+
+ setOpen((prev) => !prev)}> + + {inProgress ? ( + + {redactedThinking ? "Redacted Thinking" : "Thinking"} + + ) : redactedThinking ? ( + "Redacted Thinking" + ) : ( + "Thought" + + (elapsedTime ? ` for ${elapsedTime}` : "") + + (tokens ? ` (${tokens} tokens)` : "") + )} + {open ? ( + + ) : ( + + )} + + +
+ +
+ {redactedThinking ? ( +
+ Thinking content redacted due to safety reasons. +
+ ) : ( + <> + + + + + )} +
+
+
+ ); +} + +export default ThinkingBlockPeek; diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 35e993a54..046da1021 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -424,7 +424,8 @@ function TipTapEditor(props: TipTapEditorProps) { }, Escape: () => { if (inDropdownRef.current || !isInEditModeRef.current) { - return false; + ideMessenger.post("focusEditor", undefined); + return true; } (async () => { await dispatch( @@ -988,6 +989,7 @@ function TipTapEditor(props: TipTapEditorProps) { }} />